Advertisement
Nickpips

Ping

Jul 24th, 2016 (edited)
30
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.42 KB | None | 0 0
  1. from threading import Thread
  2. import socket
  3. import csv
  4. import os
  5.  
  6. def program():
  7.     nThreads = 20
  8.  
  9.     def runthread(urls,inds,index):
  10.         outfile = open('output' + str(index) + '.csv','wb')
  11.         out = csv.writer(outfile)
  12.         for i in xrange(0,len(urls)):
  13.             url = urls[i]
  14.             try:
  15.                 ip = socket.gethostbyname(url)
  16.             except:
  17.                 ip = 'NOT AVAILABLE'
  18.                 s = '--------- ERROR: ' + url + '\n'
  19.             else:
  20.                 s = url + '\n'
  21.                 s += 'IP: ' + ip + '\n'
  22.                 s += 'row: ' + str(inds[i]) + '\n'
  23.             s += '--------------------------\n'
  24.             print s
  25.             out.writerow([inds[i],url,ip])
  26.             outfile.flush()
  27.  
  28.     print '--------------------------'
  29.  
  30.     threadinputs = [[[], []] for i in xrange(0,nThreads)]
  31.  
  32.     ind = 1
  33.     for row in csv.reader(open('input.csv','rb')):
  34.         thread = (ind-1) % nThreads
  35.         threadinputs[thread][0].append(row[0])
  36.         threadinputs[thread][1].append(ind)
  37.         ind += 1
  38.  
  39.     threads = []
  40.  
  41.     for t in threadinputs:
  42.         ind = len(threads)
  43.         threads.append(Thread(target=runthread, args=(t[0],t[1],ind)))
  44.         threads[-1].setDaemon(True)
  45.         threads[-1].start()
  46.  
  47.     for t in threads:
  48.         t.join()
  49.    
  50.     vals = []
  51.     for i in xrange(0,nThreads):
  52.         for row in csv.reader(open('output' + str(i) + '.csv','rb')):
  53.             vals.append([int(row[0]),row[1],row[2]])
  54.         os.remove('output' + str(i) + '.csv')
  55.     vals = sorted(vals)
  56.    
  57.     outwriter = csv.writer(open('output.csv','wb'))
  58.     for val in vals:
  59.         outwriter.writerow(val[1:])
  60.    
  61.     print "DONE"
  62.  
  63. program()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement