我想构建一个简单的ping函数并得到0或1的结果。但是,如果下面的这个功能我不断收到拒绝访问错误,我已经尝试了几个网站,但我总是得到相同的错误。
from os import *
hostname = "localhost"
status = system("ping -c " + hostname)
if status == 1:
print('yes')
else:
print('no')
以下内容对我有用。
import subprocess
hostname = "localhost"
cmd = "ping -n 1 " + hostname
status = subprocess.getstatusoutput(cmd)
if status[0] == 0:
print ("yes")
else:
print ("no")
注意:我在Windows上运行了脚本。因此-n
选项而不是-c
来指定计数。
需要像管理员一样运行。例如,如果您通过右键单击并"像管理员一样运行"来启动Python shell,它应该可以工作。
这是在Windows上测试的,但我相信它在Linux上会类似,只是你必须像root一样运行它。我对Linux没有太多经验,所以可能是错的。
-c
选项时,您必须指定 ping 数。当您在 Windows 中ping <somehost>
时,默认将发送 4 个数据包(并接收,除非连接出现问题,或者您中断了该过程)。但是在 Linux 系统中,它会无限地 ping 。老实说,我不知道计数,我只是 CTRL+C 并在传输和接收的数据包足够多后中断进程:)
$ ping -c 2 google.com
PING google.com (62.212.252.123) 56(84) bytes of data.
64 bytes from 62.212.252.123: icmp_req=1 ttl=58 time=30.8 ms
64 bytes from 62.212.252.123: icmp_req=2 ttl=58 time=32.6 ms
--- google.com ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 30.860/31.761/32.663/0.918 ms
作为 Python 脚本
>>> import os
>>> status = os.system("ping -c 2 google.com")
PING google.com (62.212.252.45) 56(84) bytes of data.
64 bytes from cache.google.com (62.212.252.45): icmp_req=1 ttl=58 time=31.6 ms
64 bytes from cache.google.com (62.212.252.45): icmp_req=2 ttl=58 time=31.6 ms
--- google.com ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 31.622/31.632/31.642/0.010 ms
>>>
或您的案例
>>> host = "localhost"
>>> status = os.system("ping -c 2 "+ host)
PING localhost (127.0.0.1) 56(84) bytes of data.
64 bytes from localhost (127.0.0.1): icmp_req=1 ttl=64 time=0.053 ms
64 bytes from localhost (127.0.0.1): icmp_req=2 ttl=64 time=0.040 ms
--- localhost ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 999ms
rtt min/avg/max/mdev = 0.040/0.046/0.053/0.009 ms
如果未指定计数,
$ ping -c google.com
ping: bad number of packets to transmit.
或
>>> os.system("ping -c google.com")
ping: bad number of packets to transmit.
512