YMC M
YMC M

Reputation: 61

parallel ping using gevent

I am new to python and I am trying to run this code to want parallel ping of multiple machines.but I can not ping all IP concurrently. seems it run one after another .can some one please guide me on how can i ping multiple server concurrently.

import gevent
import urllib2
import os
from gevent import monkey
monkey.patch_all()


def print_head(i):
    switch='192.168.182.170'
    response = os.system("ping -c 5 " + switch)


jobs = [gevent.spawn(print_head, i) for i  in range(1,10)]
gevent.joinall(jobs, timeout=2)

Upvotes: 3

Views: 799

Answers (2)

falsetru
falsetru

Reputation: 369274

os.system is not patched, but subprocess.call is patched; Replace os.system with subprocess.call (You can also use subprocess.run if you are using Python 3.5+)

import subprocess

...

def print_head(i):
    switch = '192.168.182.170'
    response = subprocess.call("ping " + switch, shell=True)

Upvotes: 1

Tim Givois
Tim Givois

Reputation: 2014

The problem is that os.system("ping -c 5 " + switch) is running synchronously, because the function is blocking. You should try to do it in different processes.

Here is a concurrent code that does the same.

from multiprocessing import Process
import os

def print_head(i):
    switch='192.168.182.170'
    response = os.system("ping -c 5 " + switch)

processes = [Process(target=print_head, args=(i,)) for i in range(1,10)]
for process in processes:
    process.start()

Upvotes: 0

Related Questions