Home:ALL Converter>Multiple ping script in Python

Multiple ping script in Python

Ask Time:2012-08-24T07:09:43         Author:kuiper

Json Formatter

I'm unable to find any good easy to learn documentation on python and networking. In this instance, I'm just trying to make a easy script which I can ping a number of remote machines.

for ping in range(1,10):
   ip="127.0.0."+str(ping)
   os.system("ping -c 3 %s" % ip)

A simple script like that will ping the machines fine, but I'd like to get the script to returns 'active' 'no response' Which makes me think I'll have to look up the time module as well, I think time.sleep(5) and after that, there would be a break statement. Which makes me think there should be a while loop inside for. I'm not 100% sure, I could be going in the wrong direction completely :/ if anyone could help or point me in the direction of some documentation that'd be great.

Author:kuiper,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/12101239/multiple-ping-script-in-python
jfs :

To ping several hosts at once you could use subprocess.Popen():\n\n#!/usr/bin/env python3\nimport os\nimport time\nfrom subprocess import Popen, DEVNULL\n\np = {} # ip -> process\nfor n in range(1, 100): # start ping processes\n ip = \"127.0.0.%d\" % n\n p[ip] = Popen(['ping', '-n', '-w5', '-c3', ip], stdout=DEVNULL)\n #NOTE: you could set stderr=subprocess.STDOUT to ignore stderr also\n\nwhile p:\n for ip, proc in p.items():\n if proc.poll() is not None: # ping finished\n del p[ip] # remove from the process list\n if proc.returncode == 0:\n print('%s active' % ip)\n elif proc.returncode == 1:\n print('%s no response' % ip)\n else:\n print('%s error' % ip)\n break\n\n\nIf you can run as a root you could use a pure Python ping script or scapy:\n\nfrom scapy.all import sr, ICMP, IP, L3RawSocket, conf\n\nconf.L3socket = L3RawSocket # for loopback interface\nans, unans = sr(IP(dst=\"127.0.0.1-99\")/ICMP(), verbose=0) # make requests\nans.summary(lambda (s,r): r.sprintf(\"%IP.src% is alive\"))\n",
2012-08-24T01:11:44
Razi Ahmed :

import subprocess\nimport os\n'''\nservers.txt contains ip address in following format\n192.168.1.1\n192.168.1.2\n'''\n with open('servers.txt', 'r') as f:\n for ip in f:\n result=subprocess.Popen([\"ping\", \"-c\", \"1\", \"-n\", \"-W\", \"2\", ip],stdout=f, stderr=f).wait()\n if result:\n print(ip, \"inactive\")\n else:\n print(ip, \"active\")\n",
2016-01-12T07:29:30
andylukem :

Python actually has a really sweet method that will 'return an iterator over the usable hosts in the network'. (setting strict to false iterates over all IPs)\n\nFor example:\n\nimport subprocess\nimport ipaddress\n\nsubnet = ipaddress.ip_network('192.168.1.0/24', strict=False)\nfor i in subnet.hosts():\n i = str(i)\n subprocess.call([\"ping\", \"-c1\", \"-n\", \"-i0.1\", \"-W1\", i])\n\n\nThe wait interval (-i0.1) may be important for automations, even a one second timeout (-t1) can take forever over a .0/24\n\nEDIT:\nSo, in order to track ICMP (ping) requests, we can do something like this:\n\n#!/usr/bin/env python\n\nimport subprocess\nimport ipaddress\n\nalive = []\nsubnet = ipaddress.ip_network('192.168.1.0/23', strict=False)\nfor i in subnet.hosts():\n i = str(i)\n retval = subprocess.call([\"ping\", \"-c1\", \"-n\", \"-i0.1\", \"-W1\", i])\n if retval == 0:\n alive.append(i)\nfor ip in alive:\n print(ip + \" is alive\") \n\n\nWhich will return something like:\n\n192.168.0.1 is alive\n192.168.0.2 is alive\n192.168.1.1 is alive\n192.168.1.246 is alive\n\n\ni.e. all of the IPs responding to ICMP ranging over an entire /23-- Pretty cool!",
2016-05-22T05:27:30
umesh pant :

I have done a few modifications in the above code with multithreading in python 2.7:\nimport subprocess,os,threading,time\nimport Queue\n\nlock=threading.Lock()\n_start=time.time()\ndef check(n):\n with open(os.devnull, "wb") as limbo:\n ip=n\n result=subprocess.Popen(["ping", "-n", "2", "-w", "300", ip],stdout=limbo, stderr=limbo).wait()\n with lock:\n if not result:\n print ip, "active"\n else:\n print ip, "Inactive"\n\ndef threader():\n while True:\n worker=q.get()\n check(worker)\n q.task_done()\nq = Queue.Queue()\n\nfor x in range(255):\n t=threading.Thread(target=threader)\n t.daemon=True\n t.start()\n\nip = ["13.45.23.523", "13.35.23.523","23.23.56.346"]\nfor worker in ip:\n q.put(worker)\nq.join()\nprint("Process completed in: ",time.time()-_start)\n",
2021-02-12T20:25:29
Roland Smith :

Try subprocess.call. It saves the return value of the program that was used.\n\nAccording to my ping manual, it returns 0 on success, 2 when pings were sent but no reply was received and any other value indicates an error.\n\n# typo error in import\nimport subprocess\n\nfor ping in range(1,10):\n address = \"127.0.0.\" + str(ping)\n res = subprocess.call(['ping', '-c', '3', address])\n if res == 0:\n print \"ping to\", address, \"OK\"\n elif res == 2:\n print \"no response from\", address\n else:\n print \"ping to\", address, \"failed!\"\n",
2012-08-23T23:21:56
hochl :

This script:\n\nimport subprocess\nimport os\nwith open(os.devnull, \"wb\") as limbo:\n for n in xrange(1, 10):\n ip=\"192.168.0.{0}\".format(n)\n result=subprocess.Popen([\"ping\", \"-c\", \"1\", \"-n\", \"-W\", \"2\", ip],\n stdout=limbo, stderr=limbo).wait()\n if result:\n print ip, \"inactive\"\n else:\n print ip, \"active\"\n\n\nwill produce something like this output:\n\n192.168.0.1 active\n192.168.0.2 active\n192.168.0.3 inactive\n192.168.0.4 inactive\n192.168.0.5 inactive\n192.168.0.6 inactive\n192.168.0.7 active\n192.168.0.8 inactive\n192.168.0.9 inactive\n\n\nYou can capture the output if you replace limbo with subprocess.PIPE and use communicate() on the Popen object:\n\np=Popen( ... )\noutput=p.communicate()\nresult=p.wait()\n\n\nThis way you get the return value of the command and can capture the text. Following the manual this is the preferred way to operate a subprocess if you need flexibility:\n\n\n The underlying process creation and management in this module is\n handled by the Popen class. It offers a lot of flexibility so that\n developers are able to handle the less common cases not covered by the\n convenience functions.\n",
2012-08-23T23:15:10
Robert N :

Thank you so much for this. I have modified it to work with Windows. I have also put a low timeout so, the IP's that have no return will not sit and wait for 5 seconds each. This is from hochl source code.\n\nimport subprocess\nimport os\nwith open(os.devnull, \"wb\") as limbo:\n for n in xrange(200, 240):\n ip=\"10.2.7.{0}\".format(n)\n result=subprocess.Popen([\"ping\", \"-n\", \"1\", \"-w\", \"200\", ip],\n stdout=limbo, stderr=limbo).wait()\n if result:\n print ip, \"inactive\"\n else:\n print ip, \"active\"\n\n\nJust change the ip= for your scheme and the xrange for the hosts.",
2013-09-23T20:27:01
Sumit :

I'm a beginner and wrote a script to ping multiple hosts.To ping multiple host you can use ipaddress module. \n\nimport ipaddress\nfrom subprocess import Popen, PIPE\n\nnet4 = ipaddress.ip_network('192.168.2.0/24')\nfor x in net4.hosts():\n x = str(x)\n hostup = Popen([\"ping\", \"-c1\", x], stdout=PIPE)\n output = hostup.communicate()[0]\n val1 = hostup.returncode\n if val1 == 0:\n print(x, \"is pinging\")\n else:\n print(x, \"is not responding\")\n",
2016-01-16T16:53:35
yy