简体   繁体   中英

Pinging servers in Python3

I have a python3 code that checks ip host access using command ping ip_host.txt contains ip: 212.19.24.234 and 212.19.24.219. if I run code, I get following result: ['212.19.24.219\\n - is down'] ['212.19.24.234 - is up']

if I check using cmd-ping: 212.19.24.234 and 212.19.24.219 is up. But I can not find an error in my code? please help me

import subprocess
fp = open('ip_host.txt')
for ip in fp.readlines():
    response = subprocess.Popen(["ping.exe",ip])
    response.wait()
    result = []
    if response.poll():
       res = (ip + " - is down")
    else:
       res = (ip + " - is up")

    result.append(res)
    print(result)
  1. (the most important problem here) ip will hold lines from your file. This includes the newline character that you should remove using str.strip / str.rstrip .

  2. You could also use with...as when opening files so you don't have to worry about closing them later.

with open('ip_host.txt') as fp:
    for line in fp:
        res = subprocess.Popen(["ping.exe", line.rstrip()])
        ...

The only difference between strip and rstrip is that the latter removes only trailing whitespace. If you have leading whitespaces too, use strip .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM