Advertisement
Guest User

Untitled

a guest
Jun 10th, 2016
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.84 KB | None | 0 0
  1. #!/usr/bin/env python2
  2.  
  3. # Zedspider concept
  4. # Takes csv file of ipaddr, port as input
  5. # If service is unique, DB is updated with service info
  6.  
  7. from gevent import monkey
  8. monkey.patch_all()
  9.  
  10. import gevent.pool
  11. import gevent.queue
  12.  
  13. import socket
  14. import html2text
  15. import requests
  16. import sys
  17. import os
  18. import time
  19. import csv
  20. import mysql.connector
  21. import telnetlib
  22. import GeoIP
  23.  
  24. from randua import randomua
  25.  
  26. #TODO:
  27. # Batch update for SQL instead of sequential.
  28.  
  29. class zedspider_update():
  30.  
  31. def __init__(self):
  32. self.headers={'User-Agent':randomua(),
  33. 'Accept':'text/html, application/xml;q=0.9, application/xhtml+xml, image/png, image/webp, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.1',
  34. 'Connection':'Keep-Alive'}
  35. self.counter_uip = 0
  36. self.counter_usvc = 0
  37. self.counter_esvc = 0
  38.  
  39. def run(self):
  40. # Load the initial list of IPs and ports
  41. ipdata = self.load_list()
  42.  
  43. # Append the geolocation data
  44. ipdata = self.geo_data(ipdata)
  45. total_ips = len(ipdata)
  46. test_queue = []
  47. # For each row: Build variables, query DB, and update
  48.  
  49. while ipdata:
  50. # Build out variables
  51. for counter in range(0, min(100, len(ipdata))):
  52. qrow = []
  53. qrow.append(ipdata[0][0])
  54. qrow.append(ipdata[0][1])
  55. qrow.append(ipdata[0][2])
  56. qrow.append(ipdata[0][3])
  57. qrow.append(ipdata[0][4])
  58. qrow.append(ipdata[0][5])
  59. test_queue.append(qrow)
  60. del ipdata[0]
  61.  
  62. # SQL batch update code will go here
  63.  
  64. jobs = [gevent.spawn(self.process_data, testrow) for testrow in test_queue]
  65. gevent.joinall(jobs, timeout=30)
  66. test_queue = []
  67. print str(self.counter_usvc + self.counter_esvc) + "/" + str(total_ips) + " tested."
  68. counter = 0
  69.  
  70. print "Updated with " + str(self.counter_uip) + " unique IP addresses ; " + str(self.counter_usvc) + " unique services ; " + str(self.counter_esvc) + " existing services."
  71.  
  72. def process_data(self, ipdata):
  73. qrow = []
  74. qrow.append(ipdata[0])
  75. qrow.append(ipdata[1])
  76. qrow.append(ipdata[2])
  77. qrow.append(ipdata[3])
  78. qrow.append(ipdata[4])
  79. qrow.append(time.strftime('%Y/%m/%d %H:%M:%S'))
  80. qrow.append(self.dump_data(ipdata[0], ipdata[1], 8))
  81. qrow.append(ipdata[5])
  82. self.sql_update(qrow[0], qrow[1], qrow[2], qrow[3], qrow[4], qrow[5], qrow[6], qrow[7])
  83.  
  84. def load_list(self):
  85. #read csv into list
  86. data = []
  87. filename = sys.argv[1]
  88. datafile = open(filename, 'r')
  89. datafile.readline()
  90. datareader = csv.reader(datafile)
  91. for row in datareader:
  92. data.append(row)
  93. return data
  94.  
  95. def geo_data(self, ipdata):
  96. # Fetch country, region, and city from GeoLite db. Nice and fast.
  97.  
  98. gi = GeoIP.open("/usr/share/GeoIP/GeoLiteCity.dat", GeoIP.GEOIP_STANDARD)
  99. gorg = GeoIP.open("/usr/share/GeoIP/GeoIPOrg.dat", GeoIP.GEOIP_STANDARD)
  100.  
  101. counter = 0
  102. geodata = []
  103. print "Adding GeoIP information."
  104. for row in ipdata:
  105. gir = gi.record_by_addr(row[0])
  106.  
  107. geodata.append(row)
  108. try:
  109. geodata[counter].append(str(gir['country_name']))
  110. except:
  111. geodata[counter].append("NA")
  112. try:
  113. geodata[counter].append(str(gir['region_name']))
  114. except:
  115. geodata[counter].append("NA")
  116. try:
  117. geodata[counter].append(str(gir['city']))
  118. except:
  119. geodata[counter].append("NA")
  120. try:
  121. geodata[counter].append(str(gorg.org_by_addr(row[0])))
  122. except:
  123. geodata[counter].append("NA")
  124.  
  125. counter += 1
  126.  
  127. return geodata
  128.  
  129. def geo_data_old(self, ipdata):
  130. # Fetch country, region, and city from geoiptool.
  131. # This can also be done with a geolocation db, but
  132. # for today's purposes this'll work.
  133. # -- Fuck this. It's slow as fuck. Retained for reference.
  134.  
  135. geodata = []
  136. counter = 0
  137. cc = 'NA'
  138. cc_line_found=False
  139. re = 'NA'
  140. re_line_found=False
  141. ct = 'NA'
  142. ct_line_found=False
  143.  
  144. for row in ipdata:
  145. try:
  146. self.headers={'User-Agent':randomua()}
  147. r = requests.get('http://www.geoiptool.com/en/?IP=%s' % row[0], headers=self.headers)
  148. html = r.text
  149. except:
  150. html = "geoip failed"
  151. html_text = html2text.html2text(html)
  152. html_lines = html_text.splitlines()
  153.  
  154. # Fetch Country Code
  155. for l in html_lines:
  156. if 'country:' in l.lower():
  157. try:
  158. cc = l.split('gif) ')[1]
  159. except:
  160. cc = "NA"
  161. break
  162.  
  163. # Fetch Region/State
  164. for l in html_lines:
  165. if 'region:' in l.lower():
  166. try:
  167. re = l.split(': ')[1]
  168. except:
  169. re = "NA"
  170. break
  171.  
  172. # Fetch City
  173. for l in html_lines:
  174. if 'city:' in l.lower():
  175. try:
  176. ct = l.split(': ')[1]
  177. except:
  178. ct = "NA"
  179. break
  180.  
  181. geodata.append(row)
  182. geodata[counter].append(cc)
  183. geodata[counter].append(re)
  184. geodata[counter].append(ct)
  185.  
  186. counter += 1
  187. return geodata
  188.  
  189. def dump_data(self, strIPAddr, intPort, TIMEOUT):
  190. banner='NA'
  191. try:
  192. # Telnet requires different handling. In the future can add multiple protocols.
  193. if intPort == "23":
  194. tn = telnetlib.Telnet(strIPAddr, intPort)
  195. ret1 = tn.read_until("Shouldneverseethissojusttimeout", TIMEOUT)
  196. banner = ret1
  197. tn.close()
  198. else:
  199. self.headers={'User-Agent':randomua(),
  200. 'Accept':'text/html, application/xml;q=0.9, application/xhtml+xml, image/png, image/webp, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.1',
  201. 'Connection':'Keep-Alive'}
  202.  
  203. r = requests.get('http://'+strIPAddr+':'+str(intPort), headers=self.headers, timeout=TIMEOUT)
  204. html = r.text
  205. #s=socket.socket()
  206. #s.settimeout(TIMEOUT)
  207. #s.connect((strIPAddr,int(intPort)))
  208. #packet='GET / HTTP/1.0\r\n' + "User-Agent: " + self.headers['User-Agent'] + '\r\nHost: ' + strIPAddr + '\r\n\r\n'
  209. #s.send(packet)
  210. banner = html
  211. #s.close()
  212.  
  213. return banner
  214. except:
  215. return banner
  216.  
  217. def sql_update(self, strIPAddr, intPort, strCC, strRE, strCT, date, banner, strORG):
  218. cnx = mysql.connector.connect(user='login', password='password', database='database')
  219. cursor = cnx.cursor()
  220.  
  221. res1 = []
  222. res2 = []
  223.  
  224. # Query IP address from IPAddress table and store it in res1
  225. cursor.execute("select idIPAddr from tbl_IPAddresses where strIPAddr = %s limit 1", (strIPAddr, ))
  226. res1 = [item[0] for item in cursor.fetchall()]
  227.  
  228. # If this IP address doesn't already exist, add its info to the DB
  229. if not res1:
  230. #print '%s does not exist, so add it.' % strIPAddr
  231. self.counter_uip += 1
  232. add_IP = ("INSERT INTO tbl_IPAddresses (strIPAddr, strCountry, strCity, strRegion, strOrg) "
  233. "VALUES (%s, %s, %s, %s, %s)")
  234. IP_data = (strIPAddr, strCC, strCT, strRE, strORG)
  235. #print IP_data
  236. cursor.execute(add_IP, IP_data)
  237. idIPAddr = cursor.lastrowid
  238.  
  239. cnx.commit()
  240. else:
  241. idIPAddr = res1[0]
  242.  
  243.  
  244. # Query IP address AND port# from service table and store it in res2
  245. cursor.execute("select idSvc from tbl_service where (idIPAddr = %s AND intPort = %s) limit 1", (idIPAddr, intPort))
  246. res2 = [item[0] for item in cursor.fetchall()]
  247.  
  248. # If this service (port) doesn't exist, add its info to the DB
  249. if not res2:
  250. self.counter_usvc += 1
  251. #print '%s does not exist for %s, so add it.' % (intPort, strIPAddr)
  252. add_service = ("INSERT INTO tbl_service (idIPAddr, intPort, dateDiscovered, dateLastChecked) "
  253. "VALUES (%s, %s, %s, %s)")
  254. service_data = (idIPAddr, intPort, date, date)
  255. #print service_data
  256. cursor.execute(add_service, service_data)
  257. idSvc = cursor.lastrowid
  258.  
  259. cnx.commit()
  260. else:
  261. idSvc = res2[0]
  262. self.counter_esvc += 1
  263. #print 'Updating service date last checked.'
  264. update_service = ("UPDATE tbl_service SET dateLastChecked = %s WHERE (idSvc = %s)")
  265. update_service_data = (date, idSvc)
  266. #print update_service_data
  267. cursor.execute(update_service, update_service_data)
  268.  
  269. # Update Service Content
  270. add_dump = ("INSERT INTO tbl_service_content (idSvc, dateChecked, txtDump) "
  271. "VALUES (%s, %s, %s)")
  272. dump_data = (idSvc, date, banner)
  273. cursor.execute(add_dump, dump_data)
  274. cnx.commit()
  275.  
  276. # Close cursor
  277. # Make sure data is committed to the database
  278. cursor.close()
  279. cnx.close()
  280.  
  281. P=zedspider_update()
  282. P.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement