从 txt 文件中读取并执行 os 命令

Reading from txt file and executing an os command

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

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

例如:当 ping 行在编译器上执行时,它告诉我 "bad parameters 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

问题出在您传递给 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 Whosebugll.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: Whosebugll.com is down!