Python -- realize efficient port scanning

Keywords: Python crontab network

Please indicate the source of Reprint:
This paper is based on< Python -- Python nmap installation and common method description >To build an efficient port scanner case, please read the blog first< Python -- Python nmap installation and common method description>,
Here, we use Python nmap to realize an efficient port scanning tool, which can help us to discover the abnormally open high-risk ports in time by combining crontab and email alarm. Of course, the tool can also be used as the availability detection of business service port, for example, scanning whether the Web service port 80s of network segment is in the open state. The scan method parameters we used here are - v -PE -p + port, - v indicates that the detail mode is enabled and the list of non up state hosts can be returned, - PE indicates that the TCP syn mode is used, - p specifies the scan port range. The output part of the program uses three for loops, the first layer traverses the scanning host, the second layer traverses the protocol, the third layer traverses the port, and finally outputs the host state.

The specific script port? is as follows:

# -*- coding:UTF-8 -*-
Created on 2018 January 7, 2006

@author: liuyazhuang
import sys
import nmap

scan_row = []
input_data = raw_input('Please input hosts and port: ')
#Space separated
scan_row = input_data.split(' ')

if len(scan_row) != 2:
    print "Input errors, example \" 80,443,22 \""
#Host receiving user input
hosts = scan_row[0]
#Port to receive user revenue
port = scan_row[1]

    #Create port scan object
    nm = nmap.PortScanner()
except nmap.PortScannerError:
    print 'Nmap not found', sys.exc_info()[0]
except Exception, e:
    print "Unexpected error:", sys.exc_info()[0]
    print str(e)
    #Call the scan method, specify the hosts of the scan host and the arguments of the nmap scan command line
    nm.scan(hosts=hosts, arguments=' -v -sS -p ' + port)
except Exception, e:
    print "Scan error:" + str(e)

for host in nm.all_hosts():
    print '---------------------------------------------------------------------'
    #Output host and host name
    print 'Host : %s (%s)' % (host, nm[host].hostname())
    #Output host status, such as up and down
    print 'State : %s' % nm[host].state()
    #Traversal scanning protocol, tcp, udp
    for proto in nm[host].all_protocols():
        print '--------------'
        #Output protocol name
        print 'Protocol : %s' % proto
        #Get all scan ports of the protocol
        lport = nm[host][proto].keys()
        #Port list sort
        #Traverse port output port and status
        for port in lport:
            print 'port %s\tstate : %s' % (port, nm[host][proto][port]['state'])    

Posted by jesirose on Sat, 02 May 2020 14:55:33 -0700