Udp port scanning for basic python tutorials

  • 2020-04-02 13:24:28
  • OfStack

An overview,
Task description:
Develop a program to get the list of host IP addresses on the LAN where SNMP service is enabled, and write the corresponding file for other programs to use.
Background:
SNMP is based on UDP, and the standard SNMP service USES ports 161 and 162.
Ideas:
1. Get the list of local online hosts;
2. Get the open status of SNMP port (such as 161) of each host;
Write to a specific file in a specific format.
Only the first two steps are implemented here.

Two, nmap implementation
1. Install nmap
Linux platform (CentOS for example) :

Yum install nmap - y        
Widows platform (download address) :
http://nmap.org/download.html#windows

2. Get the list of online hosts
Take the network segment 192.168.1.0/24 as an example:

Nmap - sn 192.168.1.0/24    
Or specify IP range to scan:

Nmap - sn 192.168.1.1-254    
Parameter explanation:
-sn: Ping scan, only for host discovery, no port scan.

3. Get the opening status of the host port
192.168.1.100, for example

Nmap-p 161-su 192.168.1.100    
Parameter explanation:

-p 161: scan port 161    
- sU       : UDP scanning      
Nmap returns the result:

The open                       :     open
closed                   :     Shut down
filtered               :     The port is masked by firewall IDS/IPS and its status cannot be determined
unfiltered           :     The port is not blocked, but whether it is open requires further confirmation
The open | filtered     :     Ports are open or blocked
Closed | filtered:     Ports are closed or blocked
4. Nmap shortcuts

Port 161 of the network segment 192.168.1.0/24 is scanned as follows:  
Nmap-p 161-su 192.168.1.0/24    
3. Python implementation (with python-nmap)
The return value of nmap has a lot of data, which needs to be analyzed by a program written by ourselves. For example, the scan result of port 161 of 192.168.1.100:

Nmap scan report for 192.168.1.100
Host is up (0.00024s latency).
The PORT       The STATE   The SERVICE
The 161 / udp closed SNMP
MAC Address: 10: BF: 5 a, 6 a: BA: 48 (Unknown)
Here is a python developed nmap parsing library, the principle is to call the nmap command, and its results are parsed, return python can recognize the data structure:
Name: python - nmap
Url: http://xael.org/norman/python/python-nmap/python-nmap-0.1.4.tar.gz

Example (scan the SNMP service status of each host on the LAN) :


#! /usr/bin/python
import nmap 
nm = nmap.PortScanner()
nm.scan(hosts='192.168.1.0/24', arguments='-p 161 -sU ')
hosts_list = [(x, nm[x][u'udp'][161]['state']) for x in nm.all_hosts()]
for host, status in hosts_list:
    print('{0}:{1}'.format(host, status))


Related articles: