Home > Net >  Stop a code if a nmap port is opened in python
Stop a code if a nmap port is opened in python

Time:01-06

I got this code that executes a nmap port scan:

#iimport nmap library
import nmap

#create scanner
scanner = nmap.PortScanner()

#scan ip and ports 111, 2049
scanner.scan('10.129.223.105', '111,2049')

#print port 111 status
print('Port 111 Status:', scanner[10.129.223.105]['tcp'][111]['state'])

#print port 2049 status
print('Port 2049 Status:', scanner[10.129.223.105]['tcp'][2049]['state'])

It returns :

Port 111 Status: open
Port 2049 Status: open

How do i do to if show "filtered" or "closed" the script stops? If not, continue?

CodePudding user response:

Use the any() function to test if any of the ports are closed

if any(port['state'] in ('filtered', 'closed') for port in scanner['10.129.223.105']['tcp']):
    print("Some ports are not open")
    sys.exit()
  • Related