Python实现端口扫描

  

误删了之前的shell脚本,之前的shell脚本因为扩展性不强,就打算用python来重新实现。

端口扫描的方法特别多,我这里是把结果处理成json格式,交给后端django的来处理。


# !/usr/bin/env  python   #,- *安康;编码:utf-8  - * -      “““   日期:2018-05-14   作者:鲍勃   描述:Processing  nmap  scan 结果   “““      import 操作系统   import 时间   import  json   import 请求   import 子流程   得到xml.etree  import  ElementTree  as 等         时间=url  & # 39; http://10.200.56.80:8000/端口搜索/portScanInterface/& # 39;      def  remove_file (del_file):   ,,,if  os.path.exists (del_file):   ,,,,,,,os.remove (del_file)   ,,,return  del_file      def  alive_ip ():   ,,,#,Detecting  live  ip   ,,,with 开放(& # 39;ip_subnet.txt& # 39;,, & # 39; " # 39;), as  f:   ,,,,,,,for  ip  f:拷贝   ,,,,,,,,,,,ip =, ip.strip ()   ,,,,,,,,,,,cmd =, & # 39;/usr/bin/nmap  -sP  -PI  -PT  % s 在祝辞,alive_ip.txt& # 39; % ip   ,,,,,,,,,,,p =, subprocess.Popen (cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)   ,,,,,,,,,,,print  p.stdout.read (),      ,,,#,Scan  live  ip   ,,,ips =, []   ,,,with 开放(& # 39;alive_ip.txt& # 39;,, & # 39; " # 39;), as  f:   ,,,,,,,for  lines  f:拷贝   ,,,,,,,,,,,if  lines.startswith (& # 39; Nmap 扫描# 39;):   ,,,,,,,,,,,,,,,ip =, lines.split (& # 39;, & # 39;)   ,,,,,,,,,,,,,,,ip =, ip [4] .strip ()   ,,,,,,,,,,,,,,,ips.append (ip)   ,,,ip_str =, & # 39; . join (ips), & # 39;   ,,,nmap_scan =, & # 39;/usr/bin/nmap  -sV  -oX  nmap_scan_output.xml  % s 祝辞,/dev/null  2祝辞,1 & # 39;% ip_str   ,,,p =, subprocess.Popen (nmap_scan, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)   ,,,print  p.stdout.read (),      def  deal_scan_xml (xml_file):   ,,,#,Processing  nmap  scan 结果   ,,,bd =,开放(xml_file, & # 39; " # 39;) .read ()   ,,,root =, ET.fromstring (bd)      ,,,data =, []   ,,,for  host 拷贝root.findall(& # 39;主机# 39;):   ,,,,,,,#,Print 从而number  of  child  elements 拷贝,host 标记   ,,,,,,,#,print  len(主机)      ,,,,,,,#,Get  ip 地址   ,,,,,,,ip_ =,主机[1]. get (& # 39; addr # 39;)   ,,,,,,,#,Get 端口,协议,以及other 信息   ,,,,,,,if  len(主机),==,5:   ,,,,,,,,,,,for  port 拷贝主机[3][0:]:   ,,,,,,,,,,,,,,,#,print 港口   ,,,,,,,,,,,,,,,port_ =, str (port.get (& # 39; portid& # 39;))   ,,,,,,,,,,,,,,,protocol_ =, str (port.get(& # 39;协议# 39;))   ,,,,,,,,,,,,,,,if 港口[0].tag ==, & # 39; extrareasons& # 39;:   ,,,,,,,,,,,,,,,,,,,继续   ,,,,,,,,,,,,,,,state_ =,端口[0]. get(& # 39;国家# 39;)   ,,,,,,,,,,,,,,,service_ =, str(端口[1]. get(& # 39;名字# 39;))   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null

Python实现端口扫描