Local network pinging in python

python ping
python ping monitor
python ping until response
python ping with timeout
python ping dns
python multithreaded ping
python network device discovery
lanscan python

Does anyone know how to use python to ping a local host to see if it is active or not? We (my team and I) have already tried using

os.system("ping 192.168.1.*") 

But the response for destination unreachable is the same as the response for the host is up.

Thanks for your help.

Use this ...

import os

hostname = "localhost" #example
response = os.system("ping -n 1 " + hostname)

#and then check the response...
if response == 0:
    print(hostname, 'is up!')
else:
    print(hostname, 'is down!')

If using this script on unix/Linux replace -n switch with -c ! Thats all :)

[Solved] How to ping in local network using python?, The ping example is shown here: http://stackoverflow.com/questions/316866/ping​-a-site-in-python[^]. You only need to replace domain names  Python I have a network 192.168.1.0 with two computer. Raspberry Pi with IP = 192.168.1.7 and laptop with IP = 192.168.1.4 I want to write code using python to ping laptop from raspberry pi.

I've found that using os.system(...) leads to false positives (as the OP said, 'destination host unreachable' == 0).

As stated before, using subprocess.Popen works. For simplicity I recommend doing that followed by parsing the results. You can easily do this like:

if ('unreachable' in output):
        print("Offline")

Just check the various outputs you want to check from ping results. Make a 'this' in 'that' check for it.

Example:

import subprocess

hostname = "10.20.16.30"
output = subprocess.Popen(["ping.exe",hostname],stdout = subprocess.PIPE).communicate()[0]

print(output)

if ('unreachable' in output):
    print("Offline")

Let's! Ping The Network with 15 Line Of Code Using Python & Scapy , Ping was my first tool,it is a basic networking utility which helps to check connectivity and communication b/w two systems.So When first time I  Python Ping (pythonping), an easy way to ping in Python. Python Ping (pythonping) is a public repository you can find on PyPI. We have released it with the MIT license, so anyone can use it. Since the repository is on PyPI, you can quickly install it with pip.

I've coded a little program a while back. It might not be the exact thing you are looking for, but you can always run a program on the host OS that opens up a socket on startup. Here is the ping program itself:

# Run this on the PC that want to check if other PC is online.
from socket import *

def pingit():                               # defining function for later use

    s = socket(AF_INET, SOCK_STREAM)         # Creates socket
    host = 'localhost' # Enter the IP of the workstation here 
    port = 80                # Select port which should be pinged

    try:
        s.connect((host, port))    # tries to connect to the host
    except ConnectionRefusedError: # if failed to connect
        print("Server offline")    # it prints that server is offline
        s.close()                  #closes socket, so it can be re-used
        pingit()                   # restarts whole process    

    while True:                    #If connected to host
        print("Connected!")        # prints message 
        s.close()                  # closes socket just in case
        exit()                     # exits program

pingit()                           #Starts off whole process

And here you have the program that can recieve the ping request:

# this runs on remote pc that is going to be checked
from socket import *

HOST = 'localhost'
PORT = 80
BUFSIZ = 1024
ADDR = (HOST, PORT)
serversock = socket(AF_INET, SOCK_STREAM)
serversock.bind(ADDR)
serversock.listen(2)

while 1:
    clientsock, addr = serversock.accept()
    serversock.close()
    exit()

To run a program without actually showing it, just save the file as .pyw instead of .py. It makes it invisible until user checks running processes.

Hope it helped you

Python Ping: How to ping with Python (super-easy), In fact, it doesn't matter if you are a network engineer or a programmer – anyone in the IT world knows the ping. This simple command allows you  To run this on Linux/Unix platforms just change the parameters for the ping command. Program Analysis. You need two Python modules - subprocess and ipaddress. The subprocess module lets you spawn new processes on which you run the ping command. The ipaddress module is used to define the network and to get the IP addresses that are available on that network.

For simplicity, I use self-made functions based on socket.

def checkHostPort(HOSTNAME, PORT):
    """
        check if host is reachable
    """
    result = False
    try:
        destIp  =  socket.gethostbyname(HOSTNAME)
    except:
        return result
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(15)
    try:
        conn = s.connect((destIp, PORT))
        result = True
        conn.close()
    except:
        pass
    return result

if Ip:Port is reachable, return True

If you wanna to simulate Ping, may refer to ping.py

Network Scanner in Python, A network scanner is an IP scanner that is used for scanning the networks that This code iterates over all the available IP addresses, ping them and check for a TCP/IP network to create a connection between a local host/client and server. My goal was to understand the inner workings of ping and accomplish a Python 3 port while adding some functionality. I’ve accomplished that… while learning that pinging natively with Python (or Perl, or any other scripting language) is an exercise in frustration because of OS-level restrictions on raw sockets.

The best way I could find to do this on Windows, if you don't want to be parsing the output is to use Popen like this:

num = 1
host = "192.168.0.2"
wait = 1000

ping = Popen("ping -n {} -w {} {}".format(num, wait, host),
             stdout=PIPE, stderr=PIPE)  ## if you don't want it to print it out
exit_code = ping.wait()

if exit_code != 0:
    print("Host offline.")
else:
    print("Host online.")  

This works as expected. The exit code gives no false positives. I've tested it in Python 2.7 and 3.4 on Windows 7 and Windows 10.

Pinging hosts on the network with ICMP, An ICMP ping is the most common type of network scanning you have ever encountered. It is very easy to Querying a local XML-RPC server You can lazily write a Python script that calls the system ping command-line tool, as follows: Copy. Python is widely used to perform network automation. With its wide set of libraries (such as Netmiko and Paramiko), there are endless possibilities for network device interactions for different vendors. Let us understand one of the most widely used libraries for network interactions. We will be using Netmiko to perform our network interactions.

Python Network Scanner, Python Network Scanner - Port scanning may be defined as a surveillance ICMP is not a port scan but it is used to ping the remote host to check if the host is​  Python Network Scanner. Port scanning may be defined as a surveillance technique, which is used in order to locate the open ports available on a particular host. Network administrator, penetration tester or a hacker can use this technique.

Ping Using Python Script, According to WikiBooks, "Ping is a basic Internet tool that allows a user to LFI (​Local File Injection) and XSS (Cross-Site Scripting) are the . Ping your router to see if you can reach it. If you can’t successfully ping an internet location, you can then try pinging your router. A successful response lets you know that your local network is working okay, and that the problem reaching the internet location is somewhere out of your control. Ping your loopback address (127.0.0.1). If

An introduction to the ipaddress module, It is aimed primarily at users that aren't already familiar with IP networking terminology, but may also be useful to network engineers wanting an overview of how  Ping Sweep using Python (How to ping using Python) Vignesh SP. PFNA- Pinging bulk devices using python - Duration: Python 3 Network Automation for Network Engineers: Telnet script Part 1.

Comments
  • in case i get reply 'Destination host unreachable.' its not working.
  • Be careful that parsing the output depends on the host OS language.
  • Sorry - but the question was for pinging the server, which is a different scenario. The connect only makes sense once you know that the server exists and is alive!