Penetration tests often need to be performed on the target host IP Scan the port of each host in the address segment , Then output the open port status of the target host . Current use nmap-python Module to write a scanning script program . The code is as follows :
# Import nmap modular
import nmap
# Definition findTgts function , Parameter is subNet( Target subnet ), portLst( Target port list )
def findTgts(subNet, portLst):
# Instantiation nmap object
nmScan = nmap.PortScanner()
# Traverse target port
for port in portLst:
nmScan.scan(subNet, str(port))
# Create an empty list of target hosts
tgtHosts = []
for host in nmScan.all_hosts():
if nmScan[host].has_tcp(port):
# Get the target host tcp Status of the target port of the protocol
state = nmScan[host]['tcp'][port]['state']
# Determine whether the port status is open
if state == 'open':
print('[+] Found Target Host: ' + host + ' ' + 'port: ' + str(port) + ' open')
tgtHosts.append(host)
return tgtHosts
if __name__ == '__main__':
portLst = [21, 22, 25, 445]
tgthosts = findTgts('192.168.31.33-240', portLst)
print(tgthosts)
Target IP Address segment (192.168.31.33-240) port (21,22, 25, 445) scan , The results are shown below :
[+] Found Target Host: 192.168.31.82 port: 21 open
[+] Found Target Host: 192.168.31.82 port: 22 open
[+] Found Target Host: 192.168.31.113 port: 445 open
[+] Found Target Host: 192.168.31.192 port: 445 open
['192.168.31.82', '192.168.31.113', '192.168.31.192']
Process finished with exit code 0