You can probably save yourself some time using nmap
pip install python-nmap
Then your python script is simply:
import nmap
scan = nmap.Portscanner()
scan.scan('127.0.0.1', '21-443') # Returns scan on ports from 21-433
If you are scanning something you want to be careful with consider using proxychains which is a tor based service using SOCKS5. You can use variations such as -O -I
to identify the operating systems the IP address is using and some information as to which sockets are open or closed.
There are a lot of helpful methods such as:
>>> scan.scaninfo()
{'tcp': {'services': '22-443', 'method': 'connect'}}
>>> scan.all_hosts()
['127.0.0.1']
>>> scan['127.0.0.1'].hostname()
'localhost'
>>> scan['127.0.0.1'].state()
'up'
>>> scan['127.0.0.1'].all_protocols()
['tcp']
>>> scan['127.0.0.1']['tcp'].keys()
[80, 25, 443, 22, 111]
>>> scan['127.0.0.1'].has_tcp(22)
True
>>> scan['127.0.0.1'].has_tcp(23)
False
>>> scan['127.0.0.1']['tcp'][22]
{'state': 'open', 'reason': 'syn-ack', 'name': 'ssh'}
>>> scan['127.0.0.1'].tcp(22)
{'state': 'open', 'reason': 'syn-ack', 'name': 'ssh'}