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

时间:2019-11-21 00:02:37

标签: python operating-system python-aiofiles

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

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

例如:当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

1 个答案:

答案 0 :(得分:2)

问题出在-a无效参数之后,您要传递给ping 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!