Operation Python (i) Nmap scan port

Source: Internet
Author: User
Tags ack

Introduced

Python-nmap is a port scanning tool based on the system Nmap command, which is simple and convenient to use.

Recently, in order to enhance server security and supervision, it is necessary to keep the company server open port scan records every day, once there is an increase in the decrease can be found.

Previously wrote a https://github.com/bashhu/monitor-shell/blob/master/python-script/scan_port.sh with the shell.


Recently, we are going to improve our operation and maintenance platform, rewrite the script, and make the platform easy to call.

https://github.com/bashhu/monitor-shell/blob/master/python-script/scan_port.py

                                  In [17]:  Import nmap the port scanning method of Nmap module to instantiate In [18]: s=nmap. Portscanner () uses the scan (' 192.168.0.0/16 ', port= ' 0-65536 ', ' SV ') method, which is the network segment, the port range, the parameters of Nmap In [19]: result  = s.scan (' 192.168.199.211 ',  ' 20-443 ', ') here result is the output of the execution in [20]: print result{' Nmap ':  {' scanstats ':  {' uphosts ':  ' 1 ',  ' timestr ':  ' sat dec 17 16:24:11  2016 ',  ' downhosts ':  ' 0 ',  ' totalhosts ':  ' 1 ',  ' elapsed ':  ' 0.11 '},  ' Scaninfo ':  {' tcp ':  {' services ':  ' 20-443 ',  ' method ':  ' syn '}},  ' command_line ':   ' nmap -ox - -p 20-443 192.168.199.211 '},  ' scan ':  {' 192.168.199.211 ':  {' status ':  {' state ':  ' up ',  ' reason ':  ' Localhost-respoNSE '},  ' hostnames ':  [{' type ':  ' PTR ',  ' name ':  ' Salt '}],  ' Vendor ': {},  ' Addresses ':  {' IPv4 ':  ' 192.168.199.211 '},  ' tcp ':  {80: {' product ':  ',  ' state ':  ' open ',  ' version ':  ',  ' name ':  ' http ',  ' conf ':  ' 3 ',  ' extrainfo ':   ',  ' reason ':  ' syn-ack ',  ' CPE ':  '}, 443: {' product ':  ',  ' state ':  ' open ',  ' version ':  ',  ' name ':  ' https ',  ' conf ':  ' 3 ',  ' extrainfo ':   ',  ' reason ':  ' syn-ack ',  ' CPE ':  '}, 22: {' product ':  ',  ' state ' :  ' Open ',  ' version ':  ',  ' name ':  ' ssh ',  ' conf ':  ' 3 ',  ' extrainfo ':   ',  ' reason ':  ' syn-ack ',  ' CPE ':  '}}}} Initializes an instance of the following method in [21]: s.             s.all_hosts              s.csv                    s.listscan               s.scaninfo                           s.analyse_nmap_xml_scan  s.get_nmap_last_output  s.nmap_version           s.scanstats                          s.command_line           s.has_host               s.scan              scan all hosts in [21]:  s.all_hosts () out[21]: [List of information under ' 192.168.199.211 ']   host    in [23]: s[' 192.168.199.211 '].keys () out[23]:  [' status ',  ' hostnames ',  ' Vendor ',  ' addresses ',  ' TCP ']   ' TCP port list under host     in [26]: s[' 192.168.199.211 ' [' TCP '].keys () out[26]: [80, 443, 22] View 22 Port Details in [30]: s[' 192.168.199.211 ' [' TCP '][22]out[30]: {' conf ':  ' 3 ',  ' CPE ':   ',  ' extrainfo ':  ',  ' name ':  ' ssh ',  ' product ':  ',  ' reason ':  ' Syn-ack ',  ' state ':  ' open ',  ' version ':  '}

By the above you can see S=nmap. After Portscanner () is instantiated, the information is stored in the "s", and "s" can be as super convenient as fetching data from JSON.


Here is the script principle, welcome everyone to shoot bricks, to make better comments:

    1. Relies on the Python-nmap module to sweep the surface segment or specify an IP port

    2. Compare the port collection of this IP in Redis yesterday to get the cross-set record to text

    3. Delete yesterday's port sweep record, the Today's information IP is the key port for the collection recorded to Redis



#!/bin/bash ' author: baishaohuadate: 20161215 ' host= ' 192.168.1.224 ' port= ' 6379 ' import  Nmapimport redisimport timectime = time.strftime ('%y_%m_%d ') R = redis. Strictredis (host,port=port,db=12) def get_info (IP):         "' Get Collection and converts the collection element to an integer ' A=[]for i in r.smembers (IP): a.append (int (i)) Return adef set_info (IP,  port_list): R.delete (IP) #删除昨日的端口记录, the following traversal writes to today's Port Try:for port in port_list:r.sadd (ip,  Port) except:print  "Set redis err" Def r_log (msg):f_path =  "/tmp/report_%s.txt"  % ctimef = open (f_path,  ' A + ') f.write (msg) f.close () Def scan_port (My_ip,port_ Range): ' tow parameter: ip,port. will return a port list  ' s =  nmap. Portscanner () Result = s.scan (My_ip,port_range, ') return s[my_ip][' TCP '].keys () def scan_ips (ip_range,port_range):          '         tow parameter : ip,port. will return a port list           '         s = nmap. Portscanner ()         result = s.scan (Ip_range,port_range, ") report_key =  "report_%s"  % ctimea  = {}b  = {}for i  in s.all_hosts (): A[i] = set (Get_info (i)) B[i] = set (s[i][' TCP '].keys ()) if  R.exists (i): Less_port = a[i].difference (B[i]) add_port = b[i].difference (A[i]) If len ( Add_port) >0 and len (less_port) >0:msg =  "%s port %s new open  \t   %s have close\n " %  (i, add_port, less_port) print  Msgr_log (msg) Elif len (add_port) >0:msg =  " %s port %s new open \n " %  (i, add_port) print msgr_log (msg) elif  len (Less_port) >0:msg =  "%s port %s close \n"  %  (I, less_ Port) Print msgr_log (msg) else:print  "%s port no change: %s , %s"  %   (I, a[i], b[i]) set_info (i, s[i][' TCP '].keys ()) else:msg =  "new host: % S port %s  open\n " %  (i, s[i][' TCP '].keys ()) Print msgr_log (msg) set_ Info (i,s[i][' TCP '].keys ()) def __main__ ():     scan_ips (' 192.168.1.211/28 ', ' 20-8080 ')


This article is from the "Nginxs Small white" blog, please be sure to keep this source http://nginxs.blog.51cto.com/4676810/1883593

Operation Python (i) Nmap scan port

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.