[英]PYTHON PING IP ADDRESS WITH RESULTS
I am using this code to verify the connection of an ip address using python and this code works for me.我正在使用此代码使用 python 验证 ip 地址的连接,并且此代码适用于我。 However, I would like to use this code to return a value if it has connectivity or not with the ip address.但是,如果它与 ip 地址有连接,我想使用此代码返回一个值。 How should I do this?我该怎么做?
the code here goes like this:这里的代码是这样的:
import subprocess
import platform
ip_addr = '192.168.0.10'
def ping(host):
"""
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, '1', host]
return subprocess.call(command) == 0
ping(ip_addr)
If you need to capture the output, or just don't like the way you are doing it currently then you could capture stdout and check the output for a failure string.如果您需要捕获 output,或者只是不喜欢您当前的操作方式,那么您可以捕获标准输出并检查 output 是否有故障字符串。 You can capture stdout
like this:您可以像这样捕获stdout
:
def ping(host):
param = '-n' if platform.system().lower()=='windows' else '-c'
command = ['ping', param, '1', host]
result = subprocess.run(command, stdout=subprocess.PIPE)
output = result.stdout.decode('utf8')
if "Request timed out." in output or "100% packet loss" in output:
return "NOT CONNECTED"
return "CONNECTED"
print(ping(ip_addr))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.