使用 python ping 到特定的 IP 地址
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/25842744/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ping to a specific IP address using python
提问by Goblin
I want to write a python script that should check if a particular IP address is reachable or not. I'm new to python programming and have no idea how the code might look. Help out
我想编写一个 python 脚本来检查是否可以访问特定的 IP 地址。我是 python 编程的新手,不知道代码的外观。帮忙
采纳答案by Ram
You can use the subprocess module and shlex module to parse the shell command like below
您可以使用 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])
回答by Adem ?zta?
You can try like this;
你可以这样试试;
>>> import os
>>> if os.system("ping -c 1 google.com") == 0:
...     print "host appears to be up"

