MacOS 雙網線網絡快速切換
方法一:直接打開系統網絡設置,手動設置即可
方法二:對於Coders來講,方式一實在太low了,我們來看一下如何使用代碼控制網絡切換
#!/usr/bin/python
# -*- coding: UTF-8 -*-
## Create by Cyril.
import os
import sys
import commands
import time
global homePath
homePath = os.path.abspath("./Desktop/Tools//")
print("HomePath->",homePath)
##此函數可自由切換Apple網絡和PDCA網絡,可重複調用
##/** 切換PDCA網絡與APPLE網絡, 注意:使用此函數前請確保網絡列表中有且僅有兩個Ethernet網絡 */
def changeIP():
global homePath
netKey = "Ethernet"
scriptPath = homePath + "/checkNetStatus"
net_array=[]
net_1=0
net_2=0
j=0
execShellScript("networksetup -listallnetworkservices > %s 2>&1" %(homePath + "/networks.txt"))
net_array=readlineFromFile(homePath+ "/networks.txt") ##net_array[0] 爲無用字符串
net_array[0]="echo helloworld | sudo -S networksetup -ordernetworkservices "
index=0
for item in net_array:
if index == 0:
pass
elif "*" in net_array[index]:
net_array[index]=net_array[index][1:]
net_array[index]="\"%s\""%(net_array[index])
else:
net_array[index]="\"%s\""%(net_array[index])
if netKey in net_array[index]:
if j == 0:
net_1=index
else:
net_2=index
tmp=net_array[net_1]
net_array[net_1]=net_array[net_2]
## print("net_array[net_1]",net_array[net_1])
net_array[net_2]=tmp
## print("net_array[net_2]",net_array[net_2])
j+=1
##print(net_array[index])
index+=1
execShellScript(*net_array) ##changeIP
##while res==1:
##time.sleep(5)
return execShellScript(scriptPath) ##checkNetStatus
## /**逐行讀取txt ,將值賦給列表*/
def readlineFromFile(filePath):
with open(filePath, "r") as f:
txt=f.read()
array=txt.split("\n") ##
for item in array:
if item == '':
array.remove(item) ##刪除列表中的空元素
return array
##/**
## * arg0 : scriptPath // 第一個參數是腳本路徑
## * arg1 : ${1} // 第二個參數是腳本參數1 (log存放路徑)
## * arg2 : ${2} // 第三個參數是腳本參數2 (sn.txt 路徑)
## * arg3 : ${3} // 第四個參數是腳本參數3 (log名稱,如:SW-DOWNLOAD.zip)
## * ...
## * argn : ${n}
## */
def execShellScript(scriptPath, *args):
index = 0
cmd = scriptPath + " "
for i in args:
cmd += i + " "
##print("Exec CMD->",cmd)
(status, output) = commands.getstatusoutput(cmd)
##print status, output ##輸出shell執行返回狀態碼和輸出結果
return output
print(changeIP())
執行結果如圖: