我想编写一个python脚本,该脚本应检查特定IP地址是否可访问。我是python编程的新手,不知道代码的外观。帮忙
答案 0 :(得分:7)
你可以这样试试;
>>> import os
>>> if os.system("ping -c 1 google.com") == 0:
... print "host appears to be up"
答案 1 :(得分:5)
您可以使用子进程模块和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])