簡體   English   中英

無法從文件 ping 多個 IP 地址

[英]Unable to ping multiple IP addresses from file

我有一個包含 IP 地址列表的文件ip.txt文件。 我想 ping 文件中的每個地址並永遠重復這個。 但是我的腳本只 ping 最后一行中包含的地址(見下面的輸出)。 如何修改我的腳本來解決這個問題?

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文件:

192.168.1.91
192.168.1.92
192.168.1.93
192.168.1.94
192.168.1.95
192.168.1.96
192.168.1.97
192.168.1.98
192.168.1.99
192.168.1.100
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.

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

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)
    ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM