在 Python 中 Ping
Pinging in Python
我开始学习 python 所以我尝试制作一个需要 host.txt
的程序并且对于 host.txt
的每一行尝试 ping,最后显示所有好的 answers.But 问题是它在 host.txt
的最后一行工作正常并且它说其他人无法访问(比如 google.com)但是如果你把它们放在最后一行它工作 fine.What 应该我做?
我的代码:
import platform # For getting the operating system name
import subprocess # For executing a shell command
ip_addresses = []
i = 1
j = 1.0
z = 1.0
alive_addresses = []
f = open("host.txt", "r")
for x in f:
ip_addresses.append(x)
i += 1
#readfile()
def ping(host,i,j,z):
"""
Returns True if host (str) responds to a ping request.
Remember that a host may not respond to a ping (ICMP) request even if the host name is valid.
"""
# Option for the number of packets as a function of
param = '-n' if platform.system().lower()=='windows' else '-c'
# Building the command. Ex: "ping -c 1 google.com"
command = ['ping', param, '10', host]
result = subprocess.call(command)
if result == 0:
print("%s is Alive ===> %s" %(host,z) + '%')
alive_addresses.append(host)
else:
print("%s is Dead ===> %s" %(host,z) + '%')
for x in ip_addresses:
try:
ping(x,i,j,z)
j += 1
z = round((j/i), 1) * 100
except ZeroDivisionError:
z = 0
print("")
print("")
for x in alive_addresses:
print("%s is Alive" %(x))
尝试用 command = ['ping', param, '10', host.strip()]
替换 command = ['ping', param, '10', host]
,根据我的测试,您的地址末尾有无效字符(换行符),子进程不会像 shell/CMD 那样忽略那些
正在插入
print("DBG: '"+host+"' / '"+host.strip()+"'})")
版画
DBG: '1.1.1.1
' / '1.1.1.1'})
显示换行符。
在处理开头和结尾的空格不重要的行时,通常应始终 strip
/trim
字符串。
我开始学习 python 所以我尝试制作一个需要 host.txt
的程序并且对于 host.txt
的每一行尝试 ping,最后显示所有好的 answers.But 问题是它在 host.txt
的最后一行工作正常并且它说其他人无法访问(比如 google.com)但是如果你把它们放在最后一行它工作 fine.What 应该我做?
我的代码:
import platform # For getting the operating system name
import subprocess # For executing a shell command
ip_addresses = []
i = 1
j = 1.0
z = 1.0
alive_addresses = []
f = open("host.txt", "r")
for x in f:
ip_addresses.append(x)
i += 1
#readfile()
def ping(host,i,j,z):
"""
Returns True if host (str) responds to a ping request.
Remember that a host may not respond to a ping (ICMP) request even if the host name is valid.
"""
# Option for the number of packets as a function of
param = '-n' if platform.system().lower()=='windows' else '-c'
# Building the command. Ex: "ping -c 1 google.com"
command = ['ping', param, '10', host]
result = subprocess.call(command)
if result == 0:
print("%s is Alive ===> %s" %(host,z) + '%')
alive_addresses.append(host)
else:
print("%s is Dead ===> %s" %(host,z) + '%')
for x in ip_addresses:
try:
ping(x,i,j,z)
j += 1
z = round((j/i), 1) * 100
except ZeroDivisionError:
z = 0
print("")
print("")
for x in alive_addresses:
print("%s is Alive" %(x))
尝试用 command = ['ping', param, '10', host.strip()]
替换 command = ['ping', param, '10', host]
,根据我的测试,您的地址末尾有无效字符(换行符),子进程不会像 shell/CMD 那样忽略那些
正在插入
print("DBG: '"+host+"' / '"+host.strip()+"'})")
版画
DBG: '1.1.1.1
' / '1.1.1.1'})
显示换行符。
在处理开头和结尾的空格不重要的行时,通常应始终 strip
/trim
字符串。