【问题标题】:Reading from txt file and executing an os command从 txt 文件读取并执行 os 命令
【发布时间】:2019-11-21 00:02:37
【问题描述】:

我想要实现的是从 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

【问题讨论】:

    标签: python operating-system python-aiofiles


    【解决方案1】:

    问题在于您传递给 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!
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-22
      • 1970-01-01
      • 2018-08-12
      相关资源
      最近更新 更多