Python code for port scan

Jun 2, 2020
23
8
1,356
#!/usr/bin/env python
import sys
from socket import *
from datetime import datetime

START_PORT = 1
END_PORT = 1025

target = raw_input(">>> Enter target's IP address: ")

start_time = datetime.now().replace(microsecond=0)
print "\nScan started at %s \n" % (start_time)

def scan_target(target, port):
try:
return_code = 1

s = socket(AF_INET, SOCK_STREAM)

err_code = s.connect_ex((target, port))

if err_code == 0:
return_code = err_code

s.close()

except:
print "Error: Could not establish connection!"
sys.exit(0)

return return_code

for port in range(START_PORT, END_PORT):
return_code = scan_target(target, port)

if return_code == 0:
print "*** Port %d: OPEN" % (port)

end_time = datetime.now().replace(microsecond=0)
duration = end_time - start_time
print "\nScan finished in %s" % (duration)