2

以下 AppleScript 代码将返回网络设置中的所有网络服务。

tell application "System Events"
        tell current location of network preferences
            set names to get name of every service
        end tell
 end tell

如何仅获取活动网络服务名称而不是全部?

更新说明:在此上下文中,“活动”表示当前 [主要] IPv4 地址绑定到其接口的网络服务。

4

2 回答 2

2

您只需将其包含在您的查询中:)

tell application "System Events"
    tell current location of network preferences
        set names to get name of every service whose active is true
    end tell
end tell
于 2014-06-30T00:58:58.117 回答
2

@mcgrailm 的回答向您展示了如何获取所有活动的(阅读:未禁用)网络服务,无论当前是否绑定到地址

相比之下,这个答案向您展示了如何确定当前(主)IPv4 地址绑定到其接口的网络服务

不幸的是,这并非微不足道,因为信息必须来自多个来源:

  • services对象(来自 dictionary System Events.sdef)不包含有关当前绑定地址的信息。
  • 但是,service对象的interface属性包含一个MAC address属性。
  • 虽然IPv4 address of (system info)返回当前(主)IPv4 地址,但遗憾的是,primary Ethernet address of (system info)总是返回有线以太网接口的 MAC 地址,该地址可能是也可能不是当前 IPv4 地址所绑定的接口。
  • 因此,要确定与当前 IPv4 地址对应的 MAC 地址,下面的解决do shell script方案ifconfigawk.
# Obtain the [network] `service` instance underlying the 
# current IPv4 address...
set serviceWithPrimaryIpv4Address to my networkServiceByIp4Address("")
# ... and extract the name.
set nameOfServiceWithPrimaryIpv4Address to name of serviceWithPrimaryIpv4Address

# ---- Helper handlers.

# SYNOPSIS
#   networkServiceByIp4Address([addr])
# DESCRIPTION
#   Given (one of) the local system's IPv4 address(es), returns the network service object whose interface
#   the address is bound to (class `network service` is defined in `Sytem Events.sdef`).
#   If `addr` is an empty string or a missing value, the current primary IPv4 address is used.
#  An error is thrown if no matching service is found.
on networkServiceByIp4Address(addr)
  local macAddress
  set macAddress to my ip4ToMacAddress(addr)
  tell application "System Events"
    try
      tell current location of network preferences
        return first service whose (MAC address of interface of it) is macAddress
      end tell
    end try
  end tell
  error "No network service found matching IP address '" & addr & "'." number 500
end networkServiceByIp4Address

# SYNOPSIS
#   ip4ToMacAddress([addr])
# DESCRIPTION
#   Given (one of) the local system's IPv4 address(es), returns the corresponding network interface's
#   MAC address (regardless of interface type).
#   If `addr` is an empty string or a missing value, the current primary IPv4 address is used.
#  An error is thrown if no matching MAC address is found.
on ip4ToMacAddress(addr)
  if addr as string is "" then set addr to IPv4 address of (system info)
  try
    do shell script "ifconfig | awk -v ip4=" & ¬
      quoted form of addr & ¬
      " 'NF==2 && $2 ~ /^[a-f0-9]{2}(:[a-f0-9]{2}){5}$/ {macAddr=$2; next} $1 == \"inet\" && $2 == ip4 {print macAddr; exit}'"
    if result ≠ "" then return result
  end try
  error "No MAC address found matching IP address '" & addr & "'." number 500
end ip4ToMacAddress

my ip4ToMacAddress("")
于 2014-06-30T02:55:04.060 回答