有没有办法在for中使用os.system?

时间:2019-05-07 00:44:19

标签: python arrays list os.system iwconfig

我制作了一个bash脚本,目的是在设备连接到热点时打印有关设备的IP,MAC地址,信号强度和设备名称之类的信息。我想改用python,所以我要重写它。

当我执行代码时,它仅显示mac地址和信号强度,而对于for循环似乎没有任何作用。另外我还需要使用一些字符串连接,例如在os.system()中使用python变量,但是为此,我读到我必须使用字符串连接作为实现它的简便方法。

第一个循环是查找无线接口wlan0,第二个循环是检索两个列表的数据:maclist和signallist,其中存储了mac地址和信号强度。

print("IP address" "\tHostname" "\tMAC address" "\tSignal")
leasefile="/var/lib/misc/dnsmasq.leases"
displayInterface = "iw dev | grep Interface | cut -f 2 -s -d\" \""

for interface in os.popen(displayInterface):

retrieveMac = "iw dev wlan0 station dump | grep Station | cut -f 2 -s -d\" \""
retrieveSignal = "iw dev wlan0 station dump | grep signal: | awk '{print $2}'"
maclist = []
listLength = len(maclist)
maclist.append(os.system(retrieveMac))
signallist = []
signallist.append(os.system(retrieveSignal))

    for i in range(listLength):
        ip = "UNKN"
        host = ""
        retrieveIP = "cut -f 2,3,4 -s -d" " "+"$"+leasefile+"| grep $"+maclist[i]+" | cut -f 2 -s -d\" \""
        retrieveHost = "cut -f 2,3,4 -s -d" " "+"$"+leasefile+"| grep $"+maclist[i]+" | cut -f 3 -s -d\" \""
        ip = os.system(retrieveIP)
        host = os.system(retrieveHost)

        print(ip +"\t"+host +"\t"+maclist[i] +"\t"+signallist[i])

输出是这样的:

IP address  Hostname    MAC address Signal
b8:27:eb:...
b4:9d:0b:...
-43
-32

应为:

IP address  Hostname    MAC address      Signal
192.16...   dev name    b8:27:eb:...    -43
192.16...   dev name    b4:9d:0b:...    -32

数据不是问题,因为命令本身可以很好地工作,但它既是布局又是使用os.system()时显示的事实

P.D在这行代码中,我尝试使用interface而不是wlan0,但是它不起作用

retrieveMac = "iw dev wlan0 station dump | grep Station | cut -f 2 -s -d\" \""

retrieveMac = "iw dev "+interface+" station dump | grep Station | cut -f 2 -s -d\" \""

0 个答案:

没有答案