Skip to content

Instantly share code, notes, and snippets.

@Symeon-Carle
Forked from athoune/ping.py
Last active May 6, 2023 05:38
Show Gist options
  • Save Symeon-Carle/03e04990dde14f31b8d846b36e92e577 to your computer and use it in GitHub Desktop.
Save Symeon-Carle/03e04990dde14f31b8d846b36e92e577 to your computer and use it in GitHub Desktop.
async ping for python 3 on Windows
import asyncio
# How to use : Launch next to a file named MachineList.txt with one address per line
# Out comes Results.csv with the address and either "Up" or "Down" on each line
# Original line order is preserved
# Pings ~1700 hosts in 30 seconds on my laptop
async def ping(adresse, indice, tableau):
proc = await asyncio.create_subprocess_shell('ping -n 1 ' + adresse + " | find \"TTL\"",
stdout=asyncio.subprocess.PIPE)
line = await proc.stdout.readline()
if line != b"":
#print("{} Up !".format(adresse))
tableau[indice][1] = "Up"
else:
#print("{} Down ...".format(adresse))
tableau[indice][1] = "Down"
return
if __name__ == '__main__':
# pour Windows ça ne marche pas si on utilise get_event_loop()
# allez savoir pourquoi, je ne comprends rien à asyncio je ne fais
# que bidouiller un script existant
loop = asyncio.ProactorEventLoop()
asyncio.set_event_loop(loop)
indice = 0
tableau = []
taches = []
with open("MachineList.txt",'r') as liste_machines:
for ligne in liste_machines:
tableau.append([ligne.strip(),""])
taches.append(asyncio.async(ping(ligne.strip(),indice,tableau)))
indice += 1
loop.run_until_complete(asyncio.wait(taches))
with open("Results.csv",'w') as fichier_sortie:
for ligne in tableau:
fichier_sortie.write(",".join(ligne)+"\n")
print("\nDONE !")
@hirman74
Copy link

hirman74 commented May 6, 2023

Thanks!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment