Top 5 Scripts 2022: Advanced Python Port Scanner

What is a Port?

1. A python port scanner is a computer program that scans network ports for open network connections. They are commonly used for network troubleshooting and security auditing. There are many tools out there for port scanning, but not all of them are as accurate as others. There are a few basic types of port scanners, every scanning tool has a different purpose.

2. Python Port scanner are tools that are used to identify the type of service that is running on a network, or whether it is accessible. The port scanner will send a packet of information to the device in order to see if the device is running a service.

3. A port scanner is a tool used to scan the network for listening services on a certain port. This tool can be used by administrators and users to troubleshoot connectivity issues, identify what devices are running on the network and identify potential attack points. There are many tools that can be used for port scanning, but the most common is nmap.

4. The python Port scanner are a valuable tool for diagnosing network and connectivity issues. However, port scanners are also a tool that’s used by attackers to detect possible access points for infiltration and to identify what kind of devices you are running on the network, like firewalls, proxy servers or VPN servers. The best way to ensure your network is secure is to use port scanners to test for issues. However, the use of port scanners is not without its challenges. You must ensure that you understand the types of port scanners available and the way they are used to keep your network secure.

 

TOP 5 PYTHON PORT SCANNER

 

#1 Simple PortScanner

import argparse
import socket # for connecting
from colorama import init, Fore

from threading import Thread, Lock
from queue import Queue

# some colors
init()
GREEN = Fore.GREEN
RESET = Fore.RESET
GRAY = Fore.LIGHTBLACK_EX

# number of threads, feel free to tune this parameter as you wish
N_THREADS = 200
# thread queue
q = Queue()
print_lock = Lock()

def port_scan(port):
    """
    Scan a port on the global variable `host`
    """
    try:
        s = socket.socket()
        s.connect((host, port))
    except:
        with print_lock:
            print(f"{GRAY}{host:15}:{port:5} is closed  {RESET}", end='\r')
    else:
        with print_lock:
            print(f"{GREEN}{host:15}:{port:5} is open    {RESET}")
    finally:
        s.close()


def scan_thread():
    global q
    while True:
        # get the port number from the queue
        worker = q.get()
        # scan that port number
        port_scan(worker)
        # tells the queue that the scanning for that port 
        # is done
        q.task_done()


def main(host, ports):
    global q
    for t in range(N_THREADS):
        # for each thread, start it
        t = Thread(target=scan_thread)
        # when we set daemon to true, that thread will end when the main thread ends
        t.daemon = True
        # start the daemon thread
        t.start()

    for worker in ports:
        # for each port, put that port into the queue
        # to start scanning
        q.put(worker)
    
    # wait the threads ( port scanners ) to finish
    q.join()


if __name__ == "__main__":
    # parse some parameters passed
    parser = argparse.ArgumentParser(description="Simple port scanner")
    parser.add_argument("host", help="Host to scan.")
    parser.add_argument("--ports", "-p", dest="port_range", default="1-65535", help="Port range to scan, default is 1-65535 (all ports)")
    args = parser.parse_args()
    host, port_range = args.host, args.port_range

    start_port, end_port = port_range.split("-")
    start_port, end_port = int(start_port), int(end_port)

    ports = [ p for p in range(start_port, end_port)]

    main(host, ports)

 

 

#2 Simple PortScanner with Socket and Threading

from queue import Queue
from datetime import datetime
import socket
import threading
import sys

queue = Queue()
port_list = []


def scan(port):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        sock.connect((target, port))
        return True
    except:
        return False

def worker():
    while not queue.empty():
        port = queue.get()
        if scan(port):
            print("Port {}: Open".format(port))
            port_list.append(port)

def run(thread_number):

    for port in range(1, 1024):
        queue.put(port)

    threads = []

    for t in range(thread_number):
        thread = threading.Thread(target=worker)
        threads.append(thread)

    for thread in threads:
        thread.start()

    for thread in threads:
        thread.join()

    print("Open ports are:", port_list)
    t2 = datetime.now()
    print("-" * 50)
    print("Scan time:", (t2-t1))



if len(sys.argv) == 2:
    target = socket.gethostbyname(sys.argv[1])
else:
    print("Invalid amount of Argument")

print("-" * 50)
print("Scanning Target: " + target)
t1 = datetime.now()
print("Scanning started at:" + str(t1))
print("-" * 50)

run(100)

 

How it Works?

1. Port scanners are invaluable tools for diagnosing network and connectivity issues. Port scanners can detect misconfigured devices, such as firewalls, proxy servers, or VPN servers, or identify what kind of devices you run in your network, like servers, routers, switches and printers. If you are unsure of the type of devices you have, a port scanner can help. This blog will explore some of the tools that can help you find what devices you’re running and see what ports are open.

2. Python Port scanners are an important tool in diagnosing network issues and are also used by attackers to identify what kinds of devices are running on your network. It is important not to be complacent when you have port scanners running on your network. Even if they are not running on your network, they can be used by malicious actors to detect possible avenues for intrusion. They can also identify the kind of firewall, proxy servers, or VPN servers you are running. Make sure you have the right tools in place to protect your sensitive information.

3. Python Port scanners are valuable tools in diagnosing network and connectivity issues. However, attackers use port scanners to detect possible access points for infiltration and to identify what kinds of devices you are running on the network, like firewalls, proxy servers or VPN servers. This blog post will go over the types of scans, what they are good for, and how you should react to them.

4. Port scanners are some of the most popular tools in the cyber world. Port scanners allow users to identify what types of devices are connected to the network and can diagnose network and connectivity issues. However, attackers use port scanners to detect possible access points for infiltration and to identify what kinds of devices you are running on the network, like firewalls, proxy servers or VPN servers. This blog will look at how port scanners can be used to identify how secure your network is.

 

#3 PortScanner with PyQt5

rom PyQt5 import QtCore, QtGui, QtWidgets
import socket


class Ui_MainWindow(object):


    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(705, 600)
        font = QtGui.QFont()
        font.setFamily("aakar")
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(50)
        MainWindow.setFont(font)
        MainWindow.setStyleSheet("")
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.b1 = QtWidgets.QPushButton(self.centralwidget)
        self.b1.setGeometry(QtCore.QRect(440, 180, 131, 41))
        self.b1.setStyleSheet("color :rgb(173, 127, 168);")
        self.b1.setObjectName("b1")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(200, 10, 371, 91))
        font = QtGui.QFont()
        font.setFamily("Padauk")
        font.setPointSize(11)
        font.setBold(False)
        font.setItalic(True)
        font.setWeight(50)
        self.label.setFont(font)
        self.label.setAcceptDrops(False)
        self.label.setScaledContents(False)
        self.label.setWordWrap(False)
        self.label.setOpenExternalLinks(False)
        self.label.setObjectName("label")
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QtCore.QRect(140, 140, 431, 31))
        self.lineEdit.setStyleSheet("")
        self.lineEdit.setObjectName("lineEdit")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(140, 120, 91, 17))
        self.label_2.setObjectName("label_2")
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(210, 300, 341, 201))
        self.label_3.setStyleSheet("background-color: rgb(211, 215, 207);")
        self.label_3.setObjectName("label_3")
        self.label_4 = QtWidgets.QLabel(self.centralwidget)
        self.label_4.setGeometry(QtCore.QRect(210, 280, 91, 17))
        self.label_4.setObjectName("label_4")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 705, 22))
        self.menubar.setObjectName("menubar")
        self.menuPort_Scanner_webapp = QtWidgets.QMenu(self.menubar)
        font = QtGui.QFont()
        font.setFamily("Noto Sans CJK KR")
        self.menuPort_Scanner_webapp.setFont(font)
        self.menuPort_Scanner_webapp.setFocusPolicy(QtCore.Qt.ClickFocus)
        self.menuPort_Scanner_webapp.setObjectName("menuPort_Scanner_webapp")
        self.menuPort_Scanner_API = QtWidgets.QMenu(self.menubar)
        self.menuPort_Scanner_API.setObjectName("menuPort_Scanner_API")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        font = QtGui.QFont()
        font.setFamily("Sans")
        font.setBold(False)
        font.setItalic(True)
        font.setWeight(50)
        self.statusbar.setFont(font)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.menubar.addAction(self.menuPort_Scanner_webapp.menuAction())
        self.menubar.addAction(self.menuPort_Scanner_API.menuAction())

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
        self.b1.clicked.connect(lambda: self.on_click())
    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Port Scanner"))
        MainWindow.setWhatsThis(_translate("MainWindow", "<html><head/><body><p>ip</p></body></html>"))
        self.b1.setText(_translate("MainWindow", "Scan"))
        self.label.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" font-size:36pt; color:#ad7fa8;\">Port Scanner</span></p></body></html>"))
        self.lineEdit.setToolTip(_translate("MainWindow", "<html><head/><body><p><br/></p></body></html>"))
        self.lineEdit.setText(_translate("MainWindow", "127.0.0.1"))
        self.label_2.setText(_translate("MainWindow", "IP Address:"))
        self.label_3.setText(_translate("MainWindow", "."))
        self.label_4.setText(_translate("MainWindow", "Open Ports:"))
        
        
    def on_click(self):
        ports = [443, 80, 8080, 8000, 3000, 445, 9050, 123, 21, 19, 23, 22, 8081]
        open_ports = []
        ip = self.lineEdit.text()
        open_ports.clear()
        for port in ports:
            try:
                with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
                    s.settimeout(0.5)
                    s.connect((ip, port))
                    open_ports.append(port)
            except:
                pass
        
        if len(open_ports) == 0:
            self.label_3.setText('All ports are closed :(')
        else:
            print(open_ports)
            self.label_3.setText(f'{open_ports}')

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

 

#4 PortScanner

import pyfiglet
import sys
import socket


class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKCYAN = '\033[96m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

class config:
    timeout = 0.9


openport = []

print(bcolors.WARNING + pyfiglet.figlet_format("Port Scanner v1.1", font="rectangles") + bcolors.ENDC)

while True:
    print(bcolors.OKBLUE + "[ NEW SCAN ]\n" + bcolors.ENDC)
    target = input(bcolors.WARNING + "> " + bcolors.ENDC + "Enter ip address: ").strip()


    def targetIP():
        global target

    try:
        hostname = socket.gethostbyaddr(str(target))

        print(
            bcolors.OKBLUE + "\n[ 1 ]" + bcolors.ENDC + " Scan single port\n" +
            bcolors.OKBLUE + "[ 2 ]" + bcolors.ENDC + " Scan multiple port\n" +
            bcolors.OKBLUE + "[ 3 ]" + bcolors.ENDC + " Scan most used ports\n"
        )
        type = int(input(bcolors.WARNING + "> " + bcolors.ENDC + "Select scan type: "))

        if type == 1:
            port = int(input(bcolors.WARNING + "> " + bcolors.ENDC + "Select port: "))
        elif type == 2:
            start = int(input(bcolors.WARNING + "> " + bcolors.ENDC + "Select start port: "))
            end = int(input(bcolors.WARNING + "> " + bcolors.ENDC + "Select end port: "))
        elif type == 3:
            port = (21, 22, 23, 25, 53, 80, 110, 139, 143, 443, 445, 1433, 1521, 2082, 2083, 2086, 2087, 2222, 3306, 3389, 7080, 8083, 8090, 8443, 8447, 8880, 10000)
        else:
            print(bcolors.FAIL + "Type is not selected, program exited." + bcolors.ENDC)
            sys.exit()

        targetIP()
        print("▬" * 20)
        print(bcolors.OKBLUE + "[ PORT SCAN INFO ]\n" + bcolors.ENDC)
        if type == 1:
            print(bcolors.WARNING + "[ " + str(port) + " ]" + bcolors.ENDC + " selected port.")
        elif type == 2:
            print(bcolors.WARNING + "[ " + str(start) + "-" + str(end) + " ]" + bcolors.ENDC + " selected ports.")
        else:
            print(bcolors.WARNING + "[ 21, 22, 23, 25, 53, 80, 110, 139, 143, 443, 445, 1433, 1521, 2082, 2083, 2086, 2087, 2222, 3306, 3389, 7080, 8083, 8090, 8443, 8447, 8880, 10000 ]" + bcolors.ENDC + " selected ports.")
        print(bcolors.WARNING + "[ " + str(target) + " ] " + bcolors.ENDC + "selected ip.")
        print(bcolors.WARNING + "[ " + str(hostname[0]) + " ] " + bcolors.ENDC + "hostname.")
        print("▬" * 20)
        print(bcolors.OKBLUE + "[ PORT SCAN RESULT ]\n" + bcolors.ENDC)

        if type == 1:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            socket.setdefaulttimeout(config.timeout)
            result = s.connect_ex((target, port))
            if result == 0:
                print(bcolors.OKGREEN + "Port {} is open".format(port) + bcolors.ENDC)
            elif result != 0:
                print(bcolors.FAIL + "Port {} is closed".format(port) + bcolors.ENDC)
            s.close()
        elif type == 2:
            for port in range(int(start), int(end)):
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                socket.setdefaulttimeout(config.timeout)

                result = s.connect_ex((target, port))
                if result == 0:
                    openport.append(port)
                s.close()
            if len(openport) != 0:
                print("Total " + bcolors.OKBLUE + str(
                    len(openport)) + bcolors.ENDC + " ports open.\nPorts: " + bcolors.OKGREEN + str(
                    openport) + bcolors.ENDC)
            else:
                print(bcolors.FAIL + "All ports closed" + bcolors.ENDC)
        else:
            for ports in port:
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                socket.setdefaulttimeout(config.timeout)

                result = s.connect_ex((target, ports))
                if result == 0:
                    openport.append(ports)
                s.close()
            if len(openport) != 0:
                print("Total " + bcolors.OKBLUE + str(
                    len(openport)) + bcolors.ENDC + " ports open.\nPorts: " + bcolors.OKGREEN + str(
                    openport) + bcolors.ENDC)
            else:
                print(bcolors.FAIL + "All ports closed" + bcolors.ENDC)

    except socket.gaierror:
        print(bcolors.FAIL + "Hostname could not be resolved!" + bcolors.ENDC)
    except socket.error:
        print(bcolors.FAIL + "Server not responding!" + bcolors.ENDC)
    except ValueError:
        print(bcolors.FAIL + "Error!" + bcolors.ENDC)
    print("▬" * 50)

 

 

#5 Async PortScanner

import socket
from IPy import IP


def scan(target, port_num, timeout):
    converted_ip = check_ip(target)
    print('\n' + '[-_0 Scanning Target]' + str(target))
    for port in range(1,port_num):
        scan_port(converted_ip, port, float(timeout))


def check_ip(ip):
    try:
        IP(ip)
        return(ip)
    except ValueError:
        return socket.gethostbyname(ip)

def get_banner(s):
    return s.recv(1024)

def scan_port(ipaddress, port, timeout):
    try:
        sock = socket.socket()
        sock.settimeout(timeout)
        sock.connect((ipaddress, port))
        try:
            banner = get_banner(sock)
            print('[+] Open Port' + str(port) + ' : ' + str(banner.decode().strip('\n')))
        except:
            print('[+] Open Port' + str(port))
    except:
        # print('[-] Port '+ str(port) +' is Closed')
        pass

if __name__ == "__main__":
    targets = input('[+] Enter Target/s to Scan: (split multiple targets with ,): ')
    port_num = input('Enter Number of Ports That You Want To Scan: ')
    timeout = input('Enter timeout in seconds: ')
    if ',' in targets:
        for ip_add in targets.split(','):
            scan(ip_add.strip(' '),int(port_num),float(timeout))
    else:
        scan(targets, int(port_num), float(timeout))

CONCLUSION

1. We hope you enjoyed our blog post about python port scanners. We are here to connect you to this topic so you can stay protected. When you are using a port scanner, you are basically looking for devices and access points that your network may be using to connect to the internet. If you’re unsure about how to ensure your network is properly secured. We hope you enjoyed our blog post on port scanners. If you are looking for a way to troubleshoot connectivity and identify what devices are on your network, please consider using a port scanner. Just remember to use them in a responsible manner and never perform any illegal activities. If you would like to learn more about how to use a port scanner.It’s important to have a port scanner installed to help with diagnosing network and connectivity issues. Thank you for reading, we hope you learned something new about port scanners!Python Port scanners are a valuable tool to diagnose network and connectivity issues or to see what kind of devices you are running on your network. When used maliciously, port scanners are used to identify possible access points for infiltration and to identify vulnerable equipment on the network. This is an important point for organizations to be aware of as attackers use port scanners to detect potential access points.