Stop a code if a nmap port is opened in python

Question:

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?

Asked By: Chead1988

||

Answers:

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()
Answered By: Barmar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.