I've pinged a list of computers many times however I am trying to use Python for my first time with a list of about 4,000 computer names and my script is very slow. How would I go about making this much faster and writing the output to a comma delimited text file?
import pandas as pd
import os
import sys
import subprocess
import datetime
#Get current date and time
now = datetime.datetime.now()
dt = now.strftime("%Y-%m-%d")
dtnow = now.strftime("%Y-%m-%d %H:%M")
#Open the file and read into memory
fh = pd.read_csv('list.csv')
#Fix column headers by replacing the spaces with a underscore
fh.columns = fh.columns.str.strip().str.replace(' ', '_')
#Read the computer names into a variable called "computers"
computers = fh.Machine_Name
#Debug - Uncomment line below to see a list of computer names from csv file
#print(computers)
def ping(comp):
args = ["ping", "-n", "2", comp]
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = p.communicate()
if 'bytes=32' in output:
writetofile(comp, ',online')
else:
writetofile(comp, ',offline')
#endIf
#endDef
def writetofile(compname, data):
with open('DLPProv_' + dt + '.txt', 'a') as f:
f.write(compname + data + '\n')
#endWith
#endDef
for i in computers:
ping(i)
#endFor
f.write('END: ' + dtnow)
f.close()
I've tried using the code that @rolandsmith posted but i'm getting errors:
import concurrent.futures as cf
import os
import pandas as pd
from pythonping import ping
#Open the file and read into memory
fh = pd.read_csv('list.csv')
#Fix column headers by replacing the spaces with a underscore
fh.columns = fh.columns.str.strip().str.replace(' ', '_')
#Read the computer names into a variable called "computers"
computers = fh.Machine_Name
def pingworker(address):
rv = ping(address, count=4)
if rv.success():
return address, True
return address,False
with cf.ThreadPoolExecutor() as tp:
res = tp.map(pingworker, computers)
pingfunction takes more time. Could add a debug statement before and after it printing to calculate the time it takes?concurrent.futures.ThreadPoolExecutor'smapormultiprocessing.dummy.Pool'simap/imap_unorderedto get thread-based parallelism? That's the usual solution for latency bound problems like this.