0

我想要实现的是从 TXT 文件中读取 IP/域并执行操作系统导入命令,然后在 ping 时添加 IP/域。

但是问题是,由于某种原因,它在从 TXT 文件读取的 IP/域的末尾放置了一个句点,导致在 pining 时请求无效(代码有效,唯一的问题是末尾的句点)

例如:当 ping 行在编译器上执行时,它告诉我“google.com 参数错误”。然而,在它自己的 txt 文件中,只有一个句点是它自己的 .com 句点。

def scanlist():
ipopen = open("IPlist.txt")

#Opens the IPlist.txt file and strips each of the lines so that we can read individually.
with open("IPlist.txt", "r+") as ips_file:
    ips = [ip.strip() for ip in ips_file.readlines()]

#Read each line from the IPlist.txt file
with open("IPlist.txt", "r") as available_ips_file:
    for ip in ips:
        #Pings each line from the IPlist.txt file
        response = os.system('ping -a 1 {}'.format(ip))

        if response == 0:  # 512/DOWN value - 0/UP value
            # Up
            print("- Ip Address:", ip, 'is up!')
        elif response == 512:
            #down
            print("- IP Address:", ip, 'is down!')
        else:
            #other error
            print("- Bad parameters or other error!")

完整代码请访问 github:https ://github.com/Hontiris1/IPPing/blob/master/Ping.py

4

1 回答 1

2

问题出在您传递给 ping 的参数中 -a 之后的 1 不是有效参数

import os

def scanlist():

#Opens the IPlist.txt file and strips each of the lines so that we can read individually.
    with open("IPlist.txt") as ips_file:
        ips  = list(map(str.strip,ips_file.readlines()))

    #Read each line from the IPlist.txt file
    for ip in ips:
        #Pings each line from the IPlist.txt file
        response = os.system('ping {} -a -n 1'.format(ip)) # to send only one request
        if response == 0:  # 512/DOWN value - 0/UP value
            # Up
            print("- Ip Address:", ip, 'is up!')
        elif response == 1: # if it's time out
            #down
            print("- IP Address:", ip, 'is down!')
        else:
            #other error
            print("- Bad parameters or other error!")


scanlist()

输出

Pinging 8.8.8.8 with 32 bytes of data:
Reply from 8.8.8.8: bytes=32 time=55ms TTL=56

Ping statistics for 8.8.8.8:
Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 55ms, Maximum = 55ms, Average = 55ms
- Ip Address: 8.8.8.8 is up!

Pinging stackoverflowll.com [218.93.250.18] with 32 bytes of data:
Request timed out.

Ping statistics for 218.93.250.18:
Packets: Sent = 1, Received = 0, Lost = 1 (100% loss),
- IP Address: stackoverflowll.com is down!
于 2019-11-21T00:19:45.103 回答