Pinging Servers in Python

Pinging servers in Python

This function works in any OS (Unix, Linux, macOS, and Windows)
Python 2 and Python 3

EDITS:

By @radato os.system was replaced by subprocess.call. This avoids shell injection vulnerability in cases where your hostname string might not be validated.

import platform    # For getting the operating system name
import subprocess # For executing a shell command

def ping(host):
"""
Returns True if host (str) responds to a ping request.
Remember that a host may not respond to a ping (ICMP) request even if the host name is valid.
"""

# Option for the number of packets as a function of
param = '-n' if platform.system().lower()=='windows' else '-c'

# Building the command. Ex: "ping -c 1 google.com"
command = ['ping', param, '1', host]

return subprocess.call(command) == 0

Note that, according to @ikrase on Windows this function will still return True if you get a Destination Host Unreachable error.

Explanation

The command is ping in both Windows and Unix-like systems.

The option -n (Windows) or -c (Unix) controls the number of packets which in this example was set to 1.

platform.system() returns the platform name. Ex. 'Darwin' on macOS.

subprocess.call() performs a system call. Ex. subprocess.call(['ls','-l']).

How to ping a web server in Python 3.10

I figured it out thanks to the help of @Moanos! Here is the code:

from icmplib import ping

def host_up(hostname:str):
host = ping(hostname, count=5, interval=0.2)
return host.packets_sent == host.packets_received

hosts = "facebook.gov"

try:
if host_up(hosts):
print(f"{hosts} is valid")
except:
print(f"{hosts} is not valid")

So to the function is @Moanos's code, but the rest is mine. The reason I am using a try, except block is to prevent the NameLookupError from printing out! So when it's valid, it says only that it's valid and same case for when it is not a valid domain.

Python Function to test ping

It looks like you want the return keyword

def check_ping():
hostname = "taylor"
response = os.system("ping -c 1 " + hostname)
# and then check the response...
if response == 0:
pingstatus = "Network Active"
else:
pingstatus = "Network Error"

return pingstatus

You need to capture/'receive' the return value of the function(pingstatus) in a variable with something like:

pingstatus = check_ping()

NOTE: ping -c is for Linux, for Windows use ping -n

Some info on python functions:

http://www.tutorialspoint.com/python/python_functions.htm

http://www.learnpython.org/en/Functions

It's probably worth going through a good introductory tutorial to Python, which will cover all the fundamentals. I recommend investigating Udacity.com and codeacademy.com

EDIT: This is an old question now, but.. for people who have issues with pingstatus not being defined, or returning an unexpected value, first make triple sure your code is right. Then try defining pingstatus before the if block. This may help, but issues arising from this change are for a different question. All the best.

Python ping script

You should print the result immediately after pinging each hostname. Try this:

import os

hostnames = [
'10.40.161.2',
'10.40.161.3',
'10.40.161.4',
'10.40.161.5',
]

for hostname in hostnames:
response = os.system('ping -c 1 ' + hostname)
if response == 0:
print(hostname, 'is up')
else:
print(hostname, 'is down')

Also, you should consider using the subprocess module instead of os.system() as the latter is deprecated.

Pinging Multiple servers using Python with PyCharm IDE

Your code makes no sense. Especially your for-loop

You should keep hosts on list and use for-loop to work with every host separatelly.

You can't assign response many times because it will remove previous value and you will check only last result.

import os

# --- before loop ---

hostnames = ["google.con", "google.com", "stackoverflow.com"]

all_ok = True # at start I assume that all hosts are OK

# --- loop ---

for host in hostnames:
response = os.system("ping -n 1 " + host)
if response != 0:
all_ok = False # one of host is down
# don't use `else: all_ok = True`

# --- after loop ---

if all_ok:
print('all hosts are up!')
else:
print('something is wrong')

Similar way you can count hosts with problems

import os

# --- before loop ---

hostnames = ["google.con", "google.com", "stackoverflow.com"]

count = 0

# --- loop ---

for host in hostnames:
response = os.system("ping -n 1 " + host)
if response != 0:
count += 1 # one of host is down

# --- after loop ---

if count == 0:
print('all hosts are up!')
else:
print('number of down hosts:', count)

or you can use list for hosts with problems

import os

# --- before loop ---

hostnames = ["google.con", "google.com", "stackoverflow.com"]

problems = [] # hosts with problems

# --- loop ---

for host in hostnames:
response = os.system("ping -n 1 " + host)
if response != 0:
problems.append(host) # one of host is down

# --- after loop ---

if not problems: # if len(problems) == 0:
print('all hosts are up!')
else:
print('number of downed hosts:', len(problems))
print('hosts:', problems)

Python script that pings an internet server and let's you know when you are reconnected

You have few mistakes.


First: you have to assing result to variable

def response():
result = os.system("ping -w 2s " + ip_list)
return result

or you could use it directly with return

def response():
return os.system("ping -w 2s " + ip_list)

Second: you have to run this function and get result

result = response()

if result == 0:
# ... code ...

Third: it is preferred to send all values as arguments

def response(ip):
return os.system("ping -w 2s " + ip)

result = response(ip_list)

if result == 0:
# ... code ...

Fourth: result can be equal 0 or not equal 0 - there is no other option - so using else is useless

if result == 0:
print (("!!! ") + ip_list + (" IS UP AND RUNNING AGAIN !!!"))
else:
response()

Fifth: if you want it check again and again then you should use while-loop.

while True:
result = response(ip_list)

if result == 0:
# if the result of the ping is positive (== 0), then print message
print(("!!! ") + ip_list + (" IS UP AND RUNNING AGAIN !!!"))
break # exit loop

BTW: it is preferred to put comment in line beforeof code, not in line after code. Eventually at the end of line of code. And it is preferred to put single space after # (and two space before # when it is in the same line.)

See more: PEP 8 -- Style Guide for Python Code



import os
import time

# --- functions --- # PEP8: functions before main code

if os.name == "nt":
def response(ip):
# if the os name is nt (Windows)
return os.system("ping -w 2s " + ip)
else:
def response(ip):
# if the os name is something else (Linux)
return os.system("ping -i 2s " + ip)

# --- main ---

ip_list = "8.8.8.8"

while True:
result = response(ip_list)

if result == 0:
# if the result of the ping is positive (== 0), then print message
#print("!!! " + ip_list + " IS UP AND RUNNING AGAIN !!!") # there is no need to put string in `( )`
print(f"!!! {ip_list} IS UP AND RUNNING AGAIN !!!") # f-string can be more readable.
break # exit loop

time.sleep(5)

How To Ping IP With Python

Why don't you just use the os module from the standard python library:

import os

hosts = [] # list of host addresses

for host in hosts:
os.system('ping ' + host)


Related Topics



Leave a reply



Submit