目前想的步骤如下:
/System/Library/PrivateFrameworks/Apple80211.framework/Versions/A/Resources/airport -I | awk '/ SSID:/ {print $2}'
)步骤 1 和获取有线网络标识暂时没办法,求教大佬支招
1
ToughGuy 2021-08-30 11:32:14 +08:00
#!/usr/bin/env python3
# -*- coding: utf-8 -*- import time import subprocess as sp device = 'en0' interval = 2 networks = { 'SSID1': 'LOCATION', 'SSID2': 'LOCATION', } def send_notify(title, content): sp.check_output(['osascript', '-e', 'display notification "{}" with title "{}"'.format(title, content)]) def get_ssid(): cmd = ['networksetup', '-getairportnetwork', device] out = sp.check_output(cmd).decode().strip() if not out: return fields = out.split() if len(fields) == 4: return fields[-1] return None def get_location(): return sp.check_output(['networksetup', '-getcurrentlocation']).decode().strip() def set_location(location): # send_notify('网络位置发生变化', '当前位置: {}'.format(location)) sp.check_output(['networksetup', '-switchtolocation', location]) def main(): while 1: ssid = get_ssid() location = networks.get(ssid, 'Automatic') if get_location() != location: set_location(location) time.sleep(interval) if __name__ == '__main__': try: main() except Exception: pass |
2
ToughGuy 2021-08-30 11:34:15 +08:00
之前写过一个根据当前所连接 WIFI 自动切换网络区域的脚本, 你可以参考一下
IyEvdXNyL2Jpbi9lbnYgcHl0aG9uMwojIC0qLSBjb2Rpbmc6IHV0Zi04IC0qLQoKaW1wb3J0IHRpbWUKaW1wb3J0IHN1YnByb2Nlc3MgYXMgc3AKCmRldmljZSA9ICdlbjAnCmludGVydmFsID0gMgpuZXR3b3JrcyA9IHsKICAgICdTU0lEMSc6ICdMT0NBVElPTicsCiAgICAnU1NJRDInOiAnTE9DQVRJT04nLAp9CgoKZGVmIHNlbmRfbm90aWZ5KHRpdGxlLCBjb250ZW50KToKICAgIHNwLmNoZWNrX291dHB1dChbJ29zYXNjcmlwdCcsICctZScsICdkaXNwbGF5IG5vdGlmaWNhdGlvbiAie30iIHdpdGggdGl0bGUgInt9IicuZm9ybWF0KHRpdGxlLCBjb250ZW50KV0pCgoKZGVmIGdldF9zc2lkKCk6CiAgICBj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
我选择 hammerspoon
|
6
hguandl 2021-08-30 16:42:52 +08:00
最好的方法就是用原生的系统 API 。我搜索得到了 NWPathMonitor,试了下有效。无线网络有办法可以获得 SSID ;有线网络似乎没有什么很好的区分方法,顶多就是获取 IP 网关之类的。
Demo 代码在这里: https://gist.github.com/hguandl/284ae3b032587eda2958e31383e5135b 我不会写 Swift,这是根据文档照猫画虎写出来的,希望没什么问题。 |
7
hguandl 2021-08-30 16:48:44 +08:00
|
8
zitup OP @hguandl 666,大佬就是大佬,学习了。提供了原生 API 的思路,我顺着摸索下,我是想写一个 node 版本的 shell,所以想找一个 node 包,或者 mac 下的命令,监听网络变化,获取当前网络标识
|
9
FrankAdler 2021-08-31 15:24:12 +08:00 1
3 楼提到的 hammerspoon 确实好用
|