Guest User

Untitled

a guest
Jan 22nd, 2019
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. import sys
  2. import os
  3. import platform
  4. import subprocess
  5. import Queue
  6. import threading
  7.  
  8. def worker_func(pingArgs, pending, done):
  9. try:
  10. while True:
  11. # Get the next address to ping.
  12. address = pending.get_nowait()
  13.  
  14. ping = subprocess.Popen(ping_args + [address],
  15. stdout = subprocess.PIPE,
  16. stderr = subprocess.PIPE
  17. )
  18. out, error = ping.communicate()
  19.  
  20. # Output the result to the 'done' queue.
  21. done.put((out, error))
  22. except Queue.Empty:
  23. # No more addresses.
  24. pass
  25. finally:
  26. # Tell the main thread that a worker is about to terminate.
  27. done.put(None)
  28.  
  29. # The number of workers.
  30. NUM_WORKERS = 4
  31.  
  32. plat = platform.system()
  33. scriptDir = sys.path[0]
  34. hosts = os.path.join(scriptDir, 'hosts.txt')
  35.  
  36. # The arguments for the 'ping', excluding the address.
  37. if plat == "Windows":
  38. pingArgs = ["ping", "-n", "1", "-l", "1", "-w", "100"]
  39. elif plat == "Linux":
  40. pingArgs = ["ping", "-c", "1", "-l", "1", "-s", "1", "-W", "1"]
  41. else:
  42. raise ValueError("Unknown platform")
  43.  
  44. # The queue of addresses to ping.
  45. pending = Queue.Queue()
  46.  
  47. # The queue of results.
  48. done = Queue.Queue()
  49.  
  50. # Create all the workers.
  51. workers = []
  52. for _ in range(NUM_WORKERS):
  53. workers.append(threading.Thread(target=worker_func, args=(pingArgs, pending, done)))
  54.  
  55. # Put all the addresses into the 'pending' queue.
  56. with open(hosts, "r") as hostsFile:
  57. for line in hostsFile:
  58. pending.put(line.strip())
  59.  
  60. # Start all the workers.
  61. for w in workers:
  62. w.daemon = True
  63. w.start()
  64.  
  65. # Print out the results as they arrive.
  66. numTerminated = 0
  67. while numTerminated < NUM_WORKERS:
  68. result = done.get()
  69. if result is None:
  70. # A worker is about to terminate.
  71. numTerminated += 1
  72. else:
  73. print result[0] # out
  74. print result[1] # error
  75.  
  76. # Wait for all the workers to terminate.
  77. for w in workers:
  78. w.join()
Add Comment
Please, Sign In to add comment