Reputation: 688
I want to build a simple ping function and get a result of either 0 or 1. But if this function below i keep getting an access denied error, i've tried with several web sites and i always get the same error.
from os import *
hostname = "localhost"
status = system("ping -c " + hostname)
if status == 1:
print('yes')
else:
print('no')
Upvotes: 0
Views: 6102
Reputation: 9
the command needs to be run like administrator. For example if you start your Python shell by right click and "Run like administrator" it should work.
This is tested on windows, but I believe it will be similar on Linux, just you will have to run it like root. I am not much experienced with Linux so can be wrong.
Upvotes: 1
Reputation: 101
The following works for me.
import subprocess
hostname = "localhost"
cmd = "ping -n 1 " + hostname
status = subprocess.getstatusoutput(cmd)
if status[0] == 0:
print ("yes")
else:
print ("no")
Note: I ran the script on Windows. Hence -n
option instead of -c
for specifying the count.
Upvotes: 1
Reputation: 6564
When pinging with -c
option, you have to specify the number of pings. When you ping <somehost>
in windows, default 4 packets will send (and recieve, unless there is problem in connection, or you break the process). But in linux systems it pings infinitely. Honestly I don't know the count, I just CTRL+C and break the process after enough count of packets transmitted and recieved:)
$ 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
as a python script
>>> 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
>>>
or your case
>>> 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
if you don't specify counts,
$ ping -c google.com
ping: bad number of packets to transmit.
or,
>>> os.system("ping -c google.com")
ping: bad number of packets to transmit.
512
Upvotes: 0