How to check if a specific port is listening using Python script?

Mahsa Mortazavi picture Mahsa Mortazavi · Sep 3, 2015 · Viewed 21.6k times · Source

I want to check if api and app are running before running tests on them. I know I can get a list of open ports in CLI using

sudo lsof -iTCP -sTCP:LISTEN -n -P

But I want to write a python script to do so. Any ideas on what library should I use or how should I do that?

Answer

Mahsa Mortazavi picture Mahsa Mortazavi · Sep 3, 2015

I found a port checker using socket here and it works.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import socket
import re
import sys
def check_server(address, port):
    # Create a TCP socket
    s = socket.socket()
    print "Attempting to connect to %s on port %s" % (address, port)
    try:
        s.connect((address, port))
        print "Connected to %s on port %s" % (address, port)
        return True
    except socket.error, e:
        print "Connection to %s on port %s failed: %s" % (address, port, e)
        return False
    finally:
        s.close()

if __name__ == '__main__':
    from optparse import OptionParser
    parser = OptionParser()

    parser.add_option("-a", "--address", dest="address", default='localhost', help="ADDRESS for server", metavar="ADDRESS")

    parser.add_option("-p", "--port", dest="port", type="int", default=80, help="PORT for server", metavar="PORT")

    (options, args) = parser.parse_args()
    print 'options: %s, args: %s' % (options, args)
    check = check_server(options.address, options.port)
    print 'check_server returned %s' % check

    sys.exit(not check)