使用python ping到特定的IP地址

Gob*_*lin 0 python network-programming ping ip-address icmp

我想编写一个python脚本,该脚本应检查特定IP地址是否可访问.我是python编程的新手,不知道代码的外观.帮忙

Ade*_*taş 7

你可以这样试试;

>>> import os
>>> if os.system("ping -c 1 google.com") == 0:
...     print "host appears to be up"
Run Code Online (Sandbox Code Playgroud)


Ram*_*Ram 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])
Run Code Online (Sandbox Code Playgroud)