Port scan and grab banners in Python

Just a simple port scanner and banner grabber written in Python. I made it because I didn’t have admin privs to install nmap at the time because I was a new employee < 90 days and I wanted to sharpen my Python skills and find out if that port was open.

The instructions are simple. Just run “python simpleportscanner.py” and it will prompt for an IP address. It scans for specific tcp ports as is. Edit the code to scan the ports you desire or enter ports on the cli.

#!/usr/bin/env python
import socket
from multiprocessing.dummy import Pool as ThreadPool
import sys
from datetime import datetime

# Clear the screen
# subprocess.call('cls', shell=True)

# Ask for input
remoteServer = raw_input("Enter a remote host to scan: ")
remoteServerIP = socket.gethostbyname(remoteServer)

# Print a nice banner with information on which host we are about to scan
print "-" * 60
print "Please wait, scanning remote host", remoteServerIP
print "-" * 60

# Check what time the scan started
t1 = datetime.now()

def scan(ports):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    result = sock.connect_ex((remoteServerIP, ports))
    if result == 0:
        byte = str.encode("Server:\r\n")
        sock.send(byte)
        banner = sock.recv(1024)
        print "Port {}: Open".format(ports), " - ", banner
    sock.close()

# function to be mapped over
def scanParallel(ports, threads=4):
    pool = ThreadPool(threads)
    results = pool.map(scan, ports)
    pool.close()
    pool.join()
    return results

if __name__ == "__main__":
    ports =(20,21,22,23,53,69,80,88,110,123,135,137,138,139,143,161,389,443,445,464,512,513,631,860,1080,1433,1434,3124,3128,3306,3389,5800,5900,8080,10000)
    results = scanParallel(ports, 4)

   # Checking the time again
   t2 = datetime.now()

   # Calculates the difference of time, to see how long it took to run the  script
   total = t2 - t1

   # Printing the information to screen
   print 'Scanning Completed in: ', total

Get the code: https://raw.githubusercontent.com/sdcampbell/simpleportscanner/master/simpleportscanner.py

(Visited 1,136 times, 1 visits today)

5 thoughts on “Port scan and grab banners in Python”

  1. You use the tuple because you don’t want the port values to change? Is that correct?
    Also, what’s the purpose of
    byte = str.encode(“Server:\r\n”)
    sock.send(byte)

    Thanks

    1. I could have used a list, but since the port values don’t need to be changed and I don’t need list functions I chose to use a tuple. The purpose of that “byte=…” is when you connect to a port you need to send it something to get a response back. If you used netcat to connect to a port, it won’t respond until you send it some data.

Leave a Reply

Your email address will not be published. Required fields are marked *