无法从文件中ping多个IP地址

时间:2017-01-19 18:14:21

标签: python loops while-loop ping

我有一个文件In [4]: mydevice.getId() OUT[4]: 'x.x.x.x'文件,其中包含一个IP地址列表。我想ping文件中的每个地址并永远重复。但是我的脚本只会ping最后一行中包含的地址(参见下面的输出)。如何修改我的脚本来修复此问题?

ip.txt

输出:

import cmd
import time
import sys
import os

my_file = open("ip.txt","rb")
for line in my_file:
        l = [i.strip() for i in line.split(' ')]
        IP = l[0]

def Main():

    while True:
        ping = os.system("ping", "-c", "1", "-n", "-W", "2", IP)
        if ping:
            print IP 'no connection'
            CT =time.strftime("%H:%M:%S %d/%m/%y")
            alert=' No Connection'
            with open('logfile.txt','a+') as f:
                f.write('\n'+CT)
                f.write(alert)

        time.sleep(4)

if __name__ == "__main__":
    Main()

[root@localhost PythonScript]# python pingloop.py PING 192.168.1.100 (192.168.1.100) 56(84) bytes of data. 64 bytes from 192.168.1.100: icmp_seq=1 ttl=128 time=0.655 ms 64 bytes from 192.168.1.100: icmp_seq=2 ttl=128 time=1.15 ms 64 bytes from 192.168.1.100: icmp_seq=3 ttl=128 time=1.14 ms 64 bytes from 192.168.1.100: icmp_seq=4 ttl=128 time=0.529 ms 64 bytes from 192.168.1.100: icmp_seq=5 ttl=128 time=0.538 ms --- 192.168.1.100 ping statistics --- 5 packets transmitted, 5 received, 0% packet loss, time 4006ms rtt min/avg/max/mdev = 0.529/0.805/1.156/0.287 ms PING 192.168.1.100 (192.168.1.100) 56(84) bytes of data. 64 bytes from 192.168.1.100: icmp_seq=1 ttl=128 time=0.476 ms 64 bytes from 192.168.1.100: icmp_seq=2 ttl=128 time=0.416 ms 64 bytes from 192.168.1.100: icmp_seq=3 ttl=128 time=0.471 ms 64 bytes from 192.168.1.100: icmp_seq=4 ttl=128 time=0.478 ms 64 bytes from 192.168.1.100: icmp_seq=5 ttl=128 time=0.574 ms 档案:

ip.txt

2 个答案:

答案 0 :(得分:1)

for line in my_file:
        l = [i.strip() for i in line.split(' ')]
        IP = l[0]

在这里,在每次迭代中使用新地址覆盖先前读取的IP地址。所以最后,正如你所观察到的,你只有最后一个地址。

而是构建地址的列表

addresses = []
for line in my_file:
    IP = line.split()[0].strip()
    addresses.append(IP)

或只是

addresses = [line.split()[0].strip() for line in my_file]

稍后,您必须在地址列表上添加一个额外的循环。而不是:

while True:
    ping = os.system("ping", "-c", "1", "-n", "-W", "2", IP)
    # etc.

DO

while True:
    for IP in addresses:
        ping = os.system("ping", "-c", "1", "-n", "-W", "2", IP)
        # etc.

答案 1 :(得分:0)

IP定义为全局列表变量,并将所有IP地址添加到此列表中,然后遍历列表:

IP = []
for line in my_file: 
    l = [i.strip() for i in line.split(' ')] 
    IP.append(l[0])

# instead while use for 
for ip in IP: 
    ping = os.system("ping", "-c", "1", "-n", "-W", "2", ip)
    ...