124

How can I know if a certain port is open/closed on linux ubuntu, not a remote system, using python? How can I list these open ports in python?

  • Netstat: Is there a way to integrate netstat output with python?
0

13 Answers 13

187

You can using the socket module to simply check if a port is open or not.

It would look something like this.

import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex(('127.0.0.1',80))
if result == 0:
   print "Port is open"
else:
   print "Port is not open"
sock.close()
17
  • 21
    This has obvious drawbacks that shall be noted: simply attempt to check connection could 1) fail due to firewall or temporary overflow, 2) trigger an unwanted reaction to connect attempt in case of any active protection, 3) simply spoil logs and statistics... Checking using specially dedicated tools as netstat is commonly preferred.
    – Netch
    Dec 22, 2013 at 7:56
  • 8
    @Netch -- this is really handy when you are on a box you don't want to install extra tools on and need to check if a remote port is open . . . Dec 15, 2014 at 20:13
  • @WyattBarnett netstat is not an extra tool (at least on *nix) :)
    – Pitto
    Sep 17, 2015 at 9:46
  • I published another answer with a quick jot of how I'd handle the temporary overflow issue, @Netch :)
    – Pitto
    Dec 17, 2015 at 14:45
  • 3
    Works on Windows, too.
    – maciek
    May 6, 2016 at 9:04
150

If you want to use this in a more general context, you should make sure, that the socket that you open also gets closed. So the check should be more like this:

import socket
from contextlib import closing
   
def check_socket(host, port):
    with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
        if sock.connect_ex((host, port)) == 0:
            print("Port is open")
        else:
            print("Port is not open")
4
  • 16
    Upvoted for mentioning Automatic Resource Management. More people need to see this!
    – Blockost
    Mar 15, 2018 at 15:49
  • 1
    Hey Michael, thanks for the reply; a question, why would you use connect_ex instead of bind. Every attempt of mine to use connect or connect_ex on py3 and mac is failing with error 61 and then auto assigns a port to my socket followed by err 22. On the contrary, bind, does what I expect it to do, return if the port is open, throw if it is in use. Am I missing something? Feb 25, 2020 at 20:11
  • 5
    @plumSemPy My answer was written for python2. In python3 socket already works as a context manager. So if bind works for you, perfect.
    – Michael
    Feb 25, 2020 at 21:40
  • @Michael I know this is much later than original post, but I have a problem perhaps you could provide context to.. I tried your solution using (host='127.0.0.1', port=8080) but it always says the port is not open. The thing is though, it most certainly is open because I can initiate my port-forward command on the same host and port immediately after doing the check. I'm even checking in terminal to see the ports using this command sudo lsof -iTCP -sTCP:LISTEN -n -P | grep -i --color 8080 and it confirms the port is open. Mar 8, 2022 at 12:30
53

For me the examples above would hang if the port wasn't open. Line 4 shows use of settimeout to prevent hanging

import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(2)                                      #2 Second Timeout
result = sock.connect_ex(('127.0.0.1',80))
if result == 0:
  print 'port OPEN'
else:
  print 'port CLOSED, connect_ex returned: '+str(result)
0
26

If you only care about the local machine, you can rely on the psutil package. You can either:

  1. Check all ports used by a specific pid:

    proc = psutil.Process(pid)
    print proc.connections()
    
  2. Check all ports used on the local machine:

    print psutil.net_connections()
    

It works on Windows too.

https://github.com/giampaolo/psutil

3
  • 3
    I usually avoid non-stdlib solutions, but gdi, psutil should just be in the stdlib, its too dang essential. Mar 13, 2016 at 20:55
  • Part 2 is exactly what I was looking for, but psutil doesn't have a net_connections() function. Is this not available in Python 2? I'm in ubuntu.
    – qwerty9967
    Mar 13, 2017 at 19:49
  • @qwerty9967 no idea, I guess you should check if you can upgrade (both python if you have a pre-2.7 or the psutil package itself, preferably using pip and not apt-get/yum)
    – Joe
    Mar 27, 2017 at 0:16
9

I found multiple solutions in this post. But some solutions have a hanging issue or takeing too much time in case of the port is not opened.Try below solution :

import socket 

def port_check(HOST):
   s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   s.settimeout(2) #Timeout in case of port not open
   try:
      s.connect((HOST, 22)) #Port ,Here 22 is port 
      return True
   except:
      return False

port_check("127.0.1.1")
8

Here's a fast multi-threaded port scanner:

from time import sleep
import socket, ipaddress, threading

max_threads = 50
final = {}
def check_port(ip, port):
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # TCP
        #sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
        socket.setdefaulttimeout(2.0) # seconds (float)
        result = sock.connect_ex((ip,port))
        if result == 0:
            # print ("Port is open")
            final[ip] = "OPEN"
        else:
            # print ("Port is closed/filtered")
            final[ip] = "CLOSED"
        sock.close()
    except:
        final[ip] = "EXCEPTION"
        
port = 22
for ip in ipaddress.IPv4Network('95.217.210.0/24'): 
    threading.Thread(target=check_port, args=[str(ip), port]).start()
    #sleep(0.1)

    # limit the number of threads.
    while threading.active_count() > max_threads :
        sleep(1)


sorted_ips = dict(sorted(final.items(), key=lambda item: tuple(map(int, item[0].split('.')))))

for ip, state in sorted_ips.items():
    print(ip, state)

Live Demo

6

Just added to mrjandro's solution some improvements like automatic resource management (making sure that the opened socket also gets closed), handling timeouts, getting rid of simple connection errors / timeouts and printing out results:

import socket
from contextlib import closing

hosts = ["host1", "host2", "host3"]
port = 22
timeout_in_seconds = 2

hosts_with_opened_port = []
hosts_with_closed_port = []
hosts_with_errors = []


def check_port(host, port, timeout_in_seconds):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(timeout_in_seconds)
    with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
        try:
            result = sock.connect_ex((host, port))
            if result == 0:
                print("Port {} is *** OPEN *** on host: {}".format(port, host))
                hosts_with_opened_port.append(host)
            else:
                print("Port {} is not open on host: {}".format(port, host))
                hosts_with_closed_port.append(host)
        except socket.gaierror:
            print("Port {} check returns a network *** ERROR *** on host: {}".format(port, host))
            hosts_with_errors.append(host)


for host in hosts:
    check_port(host, port, timeout_in_seconds)

print("\nHosts with opened port:")
print(hosts_with_opened_port)
print("\nHosts with closed port:")
print(hosts_with_closed_port)
print("\nHosts with errors:")
print(hosts_with_errors)
1
  • Hi there! You just need some minor changes to the print functions in there... Check the new version I pasted :) You can easily change it to not save data to a log file, for example.
    – Pitto
    Jan 12, 2016 at 2:01
5

In case when you probing TCP ports with intention to listen on it, it’s better to actually call listen. The approach with tring to connect don’t 'see' client ports of established connections, because nobody listen on its. But these ports cannot be used to listen on its.

import socket


def check_port(port, rais=True):
    """ True -- it's possible to listen on this port for TCP/IPv4 or TCP/IPv6
    connections. False -- otherwise.
    """
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.bind(('127.0.0.1', port))
        sock.listen(5)
        sock.close()
        sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
        sock.bind(('::1', port))
        sock.listen(5)
        sock.close()
    except socket.error as e:
        return False
        if rais:
            raise RuntimeError(
                "The server is already running on port {0}".format(port))
    return True
2
  • 2
    Using "magic numbers" like 5 without comment is bad practice. According to docs, this argument socket.socket.listen(backlog) is the "number of unaccepted connections the system will allow". It is unclear why your solution would not work with a backlog of '0', simply to test if a socket can be used for a listen endpoint. (P.S. I like your solution better than the one that actually tries a connection)
    – Marvin
    Mar 4, 2019 at 15:31
  • This was what I was looking for. But if someone is just looking for any open port, perhaps binding to port 0 as shown in stackoverflow.com/a/45690594/101923 is more appropriate.
    – Tim Swast
    Apr 22, 2020 at 16:29
5

Building upon the psutil solution mentioned by Joe (only works for checking local ports):

import psutil
1111 in [i.laddr.port for i in psutil.net_connections()]

returns True if port 1111 currently used.

psutil is not part of python stdlib, so you'd need to pip install psutil first. It also needs python headers to be available, so you need something like python-devel

1
  • Does not seem to be working in MacOS with Operation not permitted error. Strange as other psutil functions are working just fine Oct 28, 2022 at 14:24
4

Agree with Sachin. Just one improvement, use connect_ex instead of connect, which can avoid try except

>>> def port_check(ip_port):
...     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
...     s.settimeout(1)
...     return s.connect_ex(ip_port) == 0
... 
>>> port_check(loc)
True
>>> port_check(loc_x)
False
>>> loc
('10.3.157.24', 6443)
>>> 
3

Netstat tool simply parses some /proc files like /proc/net/tcp and combines it with other files contents. Yep, it's highly platform specific, but for Linux-only solution you can stick with it. Linux kernel documentation describes these files in details so you can find there how to read them.

Please also notice your question is too ambiguous because "port" could also mean serial port (/dev/ttyS* and analogs), parallel port, etc.; I've reused understanding from another answer this is network port but I'd ask you to formulate your questions more accurately.

2

Please check Michael answer and vote for it. It is the right way to check open ports. Netstat and other tools are not any use if you are developing services or daemons. For instance, I am crating modbus TCP server and client services for an industrial network. The services can listen to any port, but the question is whether that port is open? The program is going to be used in different places, and I cannot check them all manually, so this is what I did:

from contextlib import closing
import socket
class example:
    def __init__():

       self.machine_ip = socket.gethostbyname(socket.gethostname())
       self.ready:bool = self.check_socket()

    def check_socket(self)->bool:
        result:bool = True
        with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
        modbus_tcp_port:int = 502
        if not sock.connect_ex((self.machine_ip, modbus_tcp_port)) == 0:
            result = False
        return result
0

This will find a random port in the given range:

import socket
import random 
from typing import Tuple

def find_listening_port(
    port_range:Tuple[int,int]=None, 
    host='', 
    socket_type='tcp', 
    default:int=None
) -> int:
    """Find an available listening port
    
    Arguments:
        port_range: Optional tuple of ports to randomly search, ``[min_port, max_port]``
            If omitted, then randomly search between ``[6000, 65534]``
        host: Host interface to search, if omitted then bind to all interfaces
        socket_type: The socket type, this should be ``tcp`` or ``udp``
        default: The port to try first before randomly searching the port range

    Returns:
        Available port for listening
    """
    def _test_port(host, port, socket_protocol):
        with socket.socket(socket.AF_INET, socket_protocol) as sock:
            try:
                sock.bind((host, port))
                if socket_type == 'tcp':
                    sock.listen(1)
                return port
            except:
                pass 

        return -1

    if port_range is None:
        port_range = (6000,65534)

    if socket_type == 'tcp':
        socket_protocol = socket.SOCK_STREAM
    elif socket_type == 'udp':
        socket_protocol = socket.SOCK_DGRAM
    else:
        raise Exception('Invalid socket_type argument, must be: tcp or udp')

    searched_ports = []
    if default is not None:
        port = _test_port(host, default, socket_protocol)
        if port != -1:
            return port
        searched_ports.append(default)

    for _ in range(100):
        port = random.randint(port_range[0], port_range[1])
        if port in searched_ports:
            continue 

        port = _test_port(host, port, socket_protocol)
        if port != -1:
            return port

        searched_ports.append(port)

    raise Exception(f'Failed to find {socket_type} listening port for host={host}')

Example usage:

# Find a TCP port,
# first check if port 80 is availble
port = find_listening_port(
    port_range=(4000, 60000),
    host='',
    socket_type='tcp',
    default=80
)
print(f'Available TCP port: {port}')

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.