0

In Python, is there a way to ping a network device like switch, router etc. without logging to particular site server?

Jung-suk
  • 172
  • 2
  • 12

1 Answers1

0

Yes. Worked on top of a solution from here . If you want to just 'ping', just use the function ping({ insert IP})

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', '-t','1', host]

    return subprocess.call(command) == 0

#Simple test to see how many IPs are allocated by my router
IPV4_in_router=[f"192.168.86.{x}" for x in range(1,254)]
used=[]
for x in IPV4_in_router:
    y=ping(x)
    if y:
        used.append(x)
print(used)
Red
  • 110
  • 1
  • 9
  • 1
    You may want to consider crediting https://stackoverflow.com/a/32684938/2525388 since the ping() function appears to come from there. – Joe Marley Aug 20 '21 at 16:21
  • @Red, Thanks for the response.. i am aware of ping function but it wont work for the private IP.. what if we need to ping the any private ip from our local system ? – Jung-suk Aug 20 '21 at 21:00
  • @Jung-suk Private IP works. Anything inside your Subnet should be able to be able to connect. Make sure you arent connected to a VPN, else you're on a different IP than your physical router. – Red Aug 21 '21 at 22:37