Ping a Site 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']).

Making a Python script to ping websites

So I got this fixed up a bit and mostly works:

from os import system
print('1. Ping Google')
print('2. Ping Yahoo')
print('3. Ping custom URL')
key = int(input('Input your choice: '))
if key == 1:
system("ping www.google.com")
elif key == 2:
system("ping www.yahoo.com")
elif key == 3:
url = input('Enter URL: ')
system("ping " + url)
else:
print("Invalid Option!")

Hope this helped!

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.

How can I make a python API to ping an ip address?

In order to ping using python, you can use the pythonping package.
You can also easily use it in flask.
A sample of the package at play is shown below.

import flask
from pythonping import ping

app = flask.Flask(__name__)
app.config["DEBUG"] = True

@app.route('/', methods=['GET'])
def home():
return ping('127.0.0.1', verbose=True)

app.run()

PYTHON PING IP ADDRESS WITH RESULTS

If you need to capture the output, or just don't like the way you are doing it currently then you could capture stdout and check the output for a failure string. You can capture stdout like this:

def ping(host):
param = '-n' if platform.system().lower()=='windows' else '-c'
command = ['ping', param, '1', host]

result = subprocess.run(command, stdout=subprocess.PIPE)
output = result.stdout.decode('utf8')
if "Request timed out." in output or "100% packet loss" in output:
return "NOT CONNECTED"
return "CONNECTED"

print(ping(ip_addr))


Related Topics



Leave a reply



Submit