Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.89 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. __author__ = 'mtur'
  3.  
  4. import csv
  5. import os,sys
  6. import includes.IPsManager as ipmanager
  7. import xlrd,xlsxwriter
  8. import xlwt
  9. import json
  10. book = xlrd.open_workbook("Data/Assets being scanned in schedules.xlsx")
  11. sheet = book.sheet_by_index(0)
  12. scans = {}
  13.  
  14.  
  15.  
  16. def read_csv(filepath):
  17.  
  18. ffile = filepath
  19. print "\n- Utilizaremos el CSV: " + ffile
  20.  
  21. f = open(ffile, 'rt')
  22. tree = {}
  23. firmas = {}
  24. cliente = {}
  25. try:
  26. count = 0
  27. reader = csv.reader(f,delimiter=';')
  28. for row in reader:
  29. #print row
  30. firma = row[0] + ';' + row[1].strip()
  31. firma = unicode(firma,errors='replace').encode('utf-8',errors='replace')
  32. firmas[firma] = {"Scans":{},"RangoFirmas":[],"TotalRangoIps":0,"TotalScansIps":0}
  33.  
  34. for ipmask in row[2].strip().split('\n'):
  35. #print ipmask
  36. count += 1
  37. try:
  38. splitter = '/'
  39. if '\\' in ipmask: splitter = '\\'
  40. ipmask = ipmask.replace('?','').strip()
  41. ip = ipmask.strip().split(splitter)[0]
  42. mask = ipmask.strip().split(splitter)[1]
  43. #print ip
  44.  
  45. first = ip
  46. last = get_last_IP_From_CIDR_ipmask(first,mask)
  47. #print last
  48.  
  49. lfirst = ipmanager.IPtoLong(first)
  50. llast = ipmanager.IPtoLong(last)
  51.  
  52. firstpartip = ip.split('.')[0] #+ '.' + ip.split('.')[1]
  53.  
  54. if not firstpartip in tree:
  55. tree[firstpartip] = []
  56. tree[firstpartip].append({'first':lfirst,'last':llast,'id':count, 'firma':firma,'rango':ipmask})
  57. if(llast-lfirst<0):
  58. print("ESTE ES NEGATIVOOOO")
  59. print(firma)
  60. print("EL SEGUNDO "+str(llast))
  61. print("EL PRIMER "+str(lfirst))
  62. print("IP primera "+str(ip))
  63. print("IP ultima "+str(last))
  64. print("++++++++++++++++++++++++")
  65. firmas[firma]['RangoFirmas'].append(ipmask)
  66. firmas[firma]['TotalRangoIps'] += llast - lfirst
  67.  
  68. except Exception, e:
  69. #print "ERROR: " + str(e)
  70. #print row
  71. #print ipmask
  72. #print "\n-------------\n"
  73. continue
  74.  
  75. arrTempRet = [tree,firmas]
  76. return arrTempRet
  77.  
  78. finally:
  79. f.close()
  80.  
  81. def get_last_IP_From_CIDR(cidr):
  82. first = unicode(cidr.split('/')[0])
  83. mask = cidr.split('/')[1]
  84.  
  85. num = 0
  86.  
  87. for i in range(0,int(mask)):
  88. num = num + 2**(31-i)
  89.  
  90. fmask = ipmanager.int2ip(num)
  91.  
  92. lastip = ipmanager.get_last_rang(first,fmask)
  93.  
  94. return lastip
  95.  
  96.  
  97. def get_last_IP_From_CIDR_ipmask(first,mask):
  98. num = 0
  99.  
  100. for i in range(0,int(mask)):
  101. num = num + 2**(31-i)
  102.  
  103. fmask = ipmanager.int2ip(num)
  104. lastip = ipmanager.get_last_rang(first,fmask)
  105.  
  106. return lastip
  107.  
  108.  
  109. def calculate_ip(tree,ip):
  110. #print "IP a analizar: {0}".format(ip)
  111. lIP = ""
  112. llIP = ""
  113. if '/' in ip:
  114. lIP = ipmanager.IPtoLong(ip.split('/')[0])
  115. llIP = ipmanager.IPtoLong(get_last_IP_From_CIDR(ip))
  116. else:
  117. lIP = ipmanager.IPtoLong(ip)
  118. llIP = lIP
  119.  
  120. fpart = ip.split('.')[0]
  121.  
  122. if fpart in tree:
  123. iprangs = tree[fpart]
  124. maxRang = -1
  125. lastGoodRang = {}
  126. for iprang in iprangs:
  127. if iprang['first'] <= lIP and iprang['last'] >= llIP:
  128. if maxRang < 0 or (iprang['last'] - iprang['first']) < maxRang:
  129. maxRang = iprang['last'] - iprang['first']
  130. lastGoodRang = iprang
  131.  
  132. if maxRang != -1:
  133. #print "- IP " + ip + ":\n\t- firma:\t" + str(lastGoodRang['firma'])\n\t- Rango:\t" + ipmanager.int2ip(lastGoodRang['first']) + " - " + ipmanager.int2ip(lastGoodRang['last'])
  134. #comprobacion para rangos
  135. return str(lastGoodRang['firma'])
  136. else:
  137. #print "No se ha encontrado la IP " + ip + " en los direccionamientos del excel."
  138. return False
  139. else:
  140. #print "La IP " + ip + " no esta en el rango de IPs del excel."
  141. return False
  142.  
  143.  
  144.  
  145.  
  146.  
  147.  
  148.  
  149. def introduce_IP():
  150. print "\n- Introduce the new IP or the CIDR: (Press '0' to exit) \n"
  151.  
  152. def matchIP(IP,tree):
  153. newIP = IP
  154. try:
  155. b = True
  156. if '/' in newIP:
  157. cip = newIP.split('/')[0]
  158. b = ipmanager.check_IP_Mask(newIP)
  159. else: cip = newIP
  160. if ipmanager.isGoodIP(cip) and b:
  161. firma = calculate_ip(tree,newIP)
  162. return firma
  163. else:
  164. print "\n- Wrong IP format: {0}".format(newIP)
  165. if not b: print "- Wrong Mask!"
  166.  
  167. # print ipmanager.to_ip(get_last_IP_From_CIDR(newIP))
  168. except Exception, e:
  169. print "- Wrong IP Format: {0}".format(newIP)
  170. print e
  171. pass
  172. return False
  173.  
  174. def update(d1,d2):
  175. d3 = {k: (d1[k], v) for k, v in d2.iteritems() if k in d1}
  176. return d3
  177. def getTotalIps(primero,ultimo):
  178. numero1 = primero.split('.')
  179. numero2 = ultimo.split('.')
  180. total = int(numero2[len(numero2)-1])-int(numero1[len(numero1)-1])
  181. return total
  182.  
  183.  
  184. def get_scan_data(firmas,nombretemp,firma,IP,lastIP=None,iprank=None):
  185. if nombretemp not in firmas[firma]['Scans']:
  186. firmas[firma]['Scans'][nombretemp] = {}
  187. firmas[firma]['Scans'][nombretemp]['ips'] = []
  188. firmas[firma]['Scans'][nombretemp]['totalIpsScan'] = 0
  189. if not iprank: iprank = IP
  190. firmas[firma]['Scans'][nombretemp]['ips'].append(iprank)
  191. totalIps = 1
  192. if lastIP: totalIps = getTotalIps(IP, lastIP)
  193. firmas[firma]['Scans'][nombretemp]['totalIpsScan'] += totalIps
  194. firmas[firma]['TotalScansIps'] += totalIps
  195. return firmas
  196.  
  197.  
  198. def makeDic(ip,nombretemp,tree,tree2,firmas,firmas2,malasIps):
  199. firmas = firmas
  200. if '-' in ip:
  201. #print ip
  202. #POR CADA IP QUE HAYA, EN COMAS
  203. iptemp = ip.split('-')
  204. firma = matchIP(iptemp[0],tree)
  205. firmal = matchIP(iptemp[len(iptemp) - 1], tree)
  206. if firma and firmal:
  207. if firmal != firma: print "Rango raro...\nrango:\t{0}\nFirma1:\t{1}\nFirma1:\t{2}\nScan:\t{0}\n".format(ip,firma,firmal,nombretemp)
  208. else: firmas = get_scan_data(firmas,nombretemp, firma, iptemp[0],iptemp[len(iptemp)-1],ip)
  209. else:
  210. firma = matchIP(iptemp[0], tree2)
  211. firmal = matchIP(iptemp[len(iptemp) - 1], tree2)
  212. if firma and firmal:
  213. if firmal != firma:
  214. print "Rango raro...\nrango:\t{0}\nFirma1:\t{1}\nFirma1:\t{2}\nScan:\t{0}\n".format(ip,firma,firmal,nombretemp)
  215. else:
  216. firmas2 = get_scan_data(firmas2, nombretemp, firma, iptemp[0], iptemp[len(iptemp) - 1],ip)
  217. else:
  218. if nombretemp not in malasIps:
  219. malasIps[nombretemp] = []
  220. malasIps[nombretemp].append(ip)
  221.  
  222. else:
  223. firma = matchIP(ip,tree)
  224. if firma:
  225. firmas = get_scan_data(firmas, nombretemp, firma, ip)
  226. else:
  227. firma = matchIP(ip, tree2)
  228. if firma: firmas2 = get_scan_data(firmas2, nombretemp, firma, ip)
  229. else:
  230. if nombretemp not in malasIps:
  231. malasIps[nombretemp] = []
  232. malasIps[nombretemp].append(ip)
  233.  
  234. return firmas,firmas2,malasIps
  235.  
  236.  
  237. def create_EXCEL(filename,firmas):
  238. workbook = xlsxwriter.Workbook(filename)
  239. bold = workbook.add_format({'bold': 1})
  240.  
  241. worksheetS = workbook.add_worksheet('Scans')
  242. header = ["Firma","RangosFirma","#IPsRango","ScanName","Rangos Scan","#IPsScan"]
  243. worksheetS.write_row(0,0,header,bold)
  244.  
  245. worksheetF = workbook.add_worksheet('Firmas')
  246. header = ["Firma","RangosFirma","#IPsRango","#IPsScans"]
  247. worksheetF.write_row(0,0,header,bold)
  248. rowS = 1
  249. rowF = 1
  250.  
  251. for firma in firmas:
  252. firnamn = unicode(firma,errors='replace')#.encode('utf-8',errors='replace')
  253. datosf = firmas[firma]
  254. ipsRangos = datosf['TotalRangoIps']
  255. ipsScans = datosf['TotalScansIps']
  256. rangoFirma = ';'.join(datosf['RangoFirmas'])
  257. #rangoFirma = rangoFirma.encode('utf-8',errors='replace')
  258. scans = datosf['Scans']
  259. worksheetF.write_row(rowF,0, [firnamn,rangoFirma,ipsRangos,ipsScans])
  260.  
  261. for scan in scans:
  262. scann = unicode(scan,errors='replace')#.encode('utf-8',errors='replace')
  263. rangoScan = ';'.join(scans[scan]['ips'])
  264. #rangoScan = rangoScan.encode('utf-8',errors='replace')
  265. ipsScan = scans[scan]['totalIpsScan']
  266. worksheetS.write_row(rowS,0,[firnamn,rangoFirma,ipsRangos,scann,rangoScan,ipsScan])
  267.  
  268. rowS += 1
  269. rowF += 1
  270. workbook.close()
  271.  
  272.  
  273. def main():
  274. dic = {}
  275. path2 = "Data/RangosPorMemberFirmPrivada.csv"
  276. path1 = "Data/RangosPorMemberFirmPublica.csv"
  277.  
  278. print "Creando arboles de decision:"
  279.  
  280. valueTempArr = read_csv(path1)
  281. valueTempArr2 = read_csv(path2)
  282. tree = valueTempArr[0]
  283. tree2 = valueTempArr2[0]
  284. firmas = valueTempArr[1]
  285. firmas2 = valueTempArr2[1]
  286.  
  287.  
  288. f = open('treePrivado.json', 'w')
  289. f.write(json.dumps(tree, indent=2))
  290. f.close()
  291.  
  292. f = open('treePublico.json', 'w')
  293. f.write(json.dumps(tree2, indent=2))
  294. f.close()
  295.  
  296.  
  297. print "Arboles creados. Empieza la clasificacion:"
  298.  
  299. malasIps = {}
  300.  
  301.  
  302.  
  303. for q in range(sheet.nrows):
  304. temp = sheet.cell_value(q,2)
  305. nombretemp = sheet.cell_value(q,1).encode('utf-8',errors='replace')
  306. temp = temp.replace(" ","")
  307. if ',' in temp: #SI TIENE COMAS Y POR LO TANTO MAS DE UNA IP
  308. for k in temp.split(','):
  309. if len(k) < 5: continue
  310. elif 'ranges' in k: continue
  311. firmas,firmas2,malasIps = makeDic(k,nombretemp,tree,tree2,firmas,firmas2,malasIps)
  312. #scans = firmas["scans"]
  313. else: #ELSE DE SI NO TIENE COMAS Y ES UNA SOLA IP O RANGO
  314. firmas,firmas2,malasIps = makeDic(temp,nombretemp,tree,tree2,firmas,firmas2,malasIps)
  315. #scans = firmas["scans"]
  316.  
  317. f = open('firmasPrivado.json', 'w')
  318. f.write(json.dumps(firmas, indent=2))
  319. f.close()
  320.  
  321. f = open('firmasPublico.json', 'w')
  322. f.write(json.dumps(firmas2, indent=2))
  323. f.close()
  324.  
  325. f = open('RangosMalos.json','w')
  326. f.write(json.dumps(malasIps,indent=2))
  327. f.close()
  328.  
  329. #create_EXCEL('FirmasPrivadas.xlsx', firmas)
  330. #create_EXCEL('FirmasPublicas.xlsx', firmas2)
  331.  
  332.  
  333.  
  334.  
  335.  
  336. if __name__ == "__main__":
  337. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement