【发布时间】:2014-09-15 07:21:38
【问题描述】:
我想编写一个 python 脚本来检查一个特定的 IP 地址是否可以访问。我是 python 编程的新手,不知道代码的外观。帮帮忙
【问题讨论】:
标签: python network-programming ip-address ping icmp
我想编写一个 python 脚本来检查一个特定的 IP 地址是否可以访问。我是 python 编程的新手,不知道代码的外观。帮帮忙
【问题讨论】:
标签: python network-programming ip-address ping icmp
你可以这样试试;
>>> import os
>>> if os.system("ping -c 1 google.com") == 0:
... print "host appears to be up"
【讨论】:
您可以使用 subprocess 模块和 shlex 模块来解析 shell 命令,如下所示
import shlex
import subprocess
# Tokenize the shell command
# cmd will contain ["ping","-c1","google.com"]
cmd=shlex.split("ping -c1 google.com")
try:
output = subprocess.check_output(cmd)
except subprocess.CalledProcessError,e:
#Will print the command failed with its exit status
print "The IP {0} is NotReacahble".format(cmd[-1])
else:
print "The IP {0} is Reachable".format(cmd[-1])
【讨论】:
rc = subprocess.call()的情况。如果是预期的,则无需引发异常。