I just started learning threading so I decided to make a program to ping a network. Probably not the best way to approach it. Just posted this so I can get some constructive feedback and hope to help other programmers learn python too.
#!/usr/bin/python
import subprocess
import threading
import time
import sys
def ping_it_boy(ip_addr):
p = subprocess.Popen(["ping","-n","1",ip_addr], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in p.stdout.read().split("\n"):
if line.strip().startswith("Reply from "):
l = line.strip().split()
m = line.replace(l[0]+" "+l[1]+" "+l[2], "")
if m.strip() != "Destination host unreachable.":
print(l[2][:-1] + " >>> " + m)
def get_input(prompt):
"""
Function Get input from the user maintaining the python compatibility with earlier and newer versions.
:param prompt:
:rtype : str
:return: Returns the Hash string received from user.
"""
if sys.hexversion > 0x03000000:
return input(prompt)
else:
return raw_input(prompt)
if __name__ == "__main__":
ip = get_input("Enter the base IP. Example: 192.168.1 \n>>> ")
ip = ip.strip() + "."
print("Starting multiply threads for "+ ip + "0/24")
t_thread = []
t_sleep_on = 20
for i in range(1, 255):
t = threading.Thread(target=ping_it_boy, args=(ip + str(i),))
t_thread.append(t)
t.start()
if i == t_sleep_on:
for i in t_thread:
i.join()
t_thread.remove(i)
# print("Wakey Wakey")
t_sleep_on += 20
ohh btw the reason why i cut the thread by 20 is because I have a slow pc. Launching a lot of thread cause my computer to crash so I capped it at 20.