3
\$\begingroup\$

I am looking for a way to speed up my basic IP scanner/port scanner in Python 3.8. My IP portion works, the port scan work, I just want to speed it up, in a format that someone learning python would understand.

#testing scanner.py 
import socket
import subprocess
import sys
from datetime import datetime
def scan():
    # Ask for the IP address to scan, for this its a single IP
    remoteServer = input("Enter a Starting IP: ")
    remoteServerend = input("Enter the Ending IP: ")
    print ("Starting Scan at: ",remoteServer)
    print ("Ending Scan at: ",remoteServerend)
    # change DNS to IPmail
    #remoteServerIP = socket.gethostbyname(remoteServer)
    #print ("remoteServerIP is ",remoteServerIP)
    # Ask for starting port
    startport = int(input("What port number do you want to start with? "))
    # Ask for ending port
    endport = int(input("What is the ending port number? "))
    # Print 50 *'s to make a top border
    print ("-" * 50)
    # print wait here is the IP we are scanning
    print ("Please wait, scanning remote host", remoteServer)
    # print the bottom border
    print ("-" * 50)
    # Check what time the scan started
    t1 = datetime.now()
    # lets try the try statment for some error handeling and see if it can help?
    try:
    # trying our 1st port to our last port and replying if it is open, we don't care about closed ports
        for port in range(startport,endport):
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            result = sock.connect_ex((remoteServer, port))
            if result == 0:
                print ("Port {}:     Open".format(port))
            sock.close()
    # you got tied of waiting and quit
    except KeyboardInterrupt:
        print( "You pressed Ctrl+C")
        sys.exit()
    # failed DNS lookup
    except socket.gaierror:
        print( 'Hostname could not be resolved. Exiting')
        sys.exit()
    # no route to server?
    except socket.error:
        print( "Couldn't connect to server")
        sys.exit()
    # get ending time
    t2 = datetime.now()
    # calculate how long did the script run?
    total =  t2 - t1
    # Printing the information to screen
    print( 'Scanning Completed in: ', total)



scan()
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

IP range

for this its a single IP

It is? Then why do you ask for a range? Your 'end' is not used, so just delete it.

Fail-safe scanning

Consider rearranging this:

try:
    for port in range(startport,endport):

to:

for port in range(startport,endport):
    try:

In other words, some ports may fail and others may succeed.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.