#coding:utf-8 import sys,os,time,subprocess import MySQLdb import re,urllib2 import ConfigParser from IPy import IP import xml.etree.ElementTree as ET nowtime = time.strftime('%Y-%m-%d',time.localtime(time.time())) configpath=r'c:\portscan\config.ini' #传入api接口主路径,遍历获取所有的ip列表,用IPy模块格式成127.0.0.1/24的格式 def getiplist(ipinf): serverarea=['tj101','tj103','dh','dx'] iplist=[] for area in serverarea: ipapi=urllib2.urlopen(ipinf+area).read() for ip in ipapi.split('\n'): #判断如果ip列表不为空,转换成ip/网关格式,再格式化成ip/24的格式 if ip: ip=ip.replace('_','/') ip=(IP(ip)) iplist.append(str(ip)) ipscan(iplist,nmapathx) #传递ip地址文件和nmap路径 def ipscan(iplist,nmapath): #古老的去重,对ip文件中的ip地址进行去重 newiplist=[] scaniplist=[] for ip in iplist: if ip not in newiplist: newiplist.append(ip) #遍历所有ip段,批量扫描,生成xml格式报告 for ip in newiplist: filename=nowtime+ip.split('/')[0]+'.xml' filepath=r"c:\portscan\scanres\\" nmapcmd=nmapath+' -PT '+ip.strip('\r\n')+' -oX '+filepath+filename os.system(nmapcmd) scaniplist.append(ip) writeinmysql(scaniplist) #入库模块是某大婶发写好的给我 我只是简单修改了哈,主要是xml.etree.ElementTree模块。 def writeinmysql(scaniplist): filepath=r"c:\portscan\scanres" for ip in scaniplist: xmlfile=filepath+'\\'+ip+'.xml' root=ET.parse(xmlfile).getroot() allhost=root.findall('host') conn=MySQLdb.connect(host='10.1.11.11',user='nxadmin',passwd='nxadmin.com',port=3306,db='scandatabase',charset='utf8') cur= conn.cursor() for host in allhost: address = host.find('address') #首先判断端口是不是open的,如果是再进行入库 for port in host.find('ports').findall('port'): if port.find('state').attrib['state']=="open": ip=address.attrib['addr'] portval=port.attrib['portid'] state=port.find('state').attrib['state'] sql = "INSERT INTO portscan (ip,port,state) VALUES(%s,%s,%s)" params=[ip,portval,state] cur.execute(sql,params) conn.commit() cur.close() conn.close() if __name__=="__main__": #读取配置文件中要扫描的IP apiurl和nmap安装文件路径 config=ConfigParser.ConfigParser() config.readfp(open(configpath,'rb')) nmapathx=config.get('nmap','nmapath') ipinf=config.get('ip','ipinf') getiplist(ipinf) |