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

3

5

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?

Equerry answered 3/9, 2015 at 15:47 Comment(2)
Selenium tests. I want to make sure that the app is running properly and api is loaded before going through tests and get false negatives. @AliSAIDOMAREquerry
So consider the use of supervisord with priority parameter. #23245454Dail
E
19

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)
Equerry answered 3/9, 2015 at 18:5 Comment(1)
One might consider wrapping the try in a with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: statement so that it closes automatically after completion.Innocent
D
1

You can also use supervisord with priority parameter. Group all the applications in a group. That way will ensure you that all you applications are running.

Dail answered 3/9, 2015 at 16:3 Comment(0)
C
0

You could get the output of that command and parse it manually if you want.

To get the output you should do something like this:

proc = subprocess.Popen(['lsof', '-iTCP', -'sTCP:LISTEN', '-n' ,'-P'], stdout=subprocess.PIPE)
tmp = proc.stdout.read()
Contiguity answered 3/9, 2015 at 16:0 Comment(1)
Parsing the output of a command (especially one not guaranteed to be stable!) is probably not going to give the best answers long term.Thunderpeal

© 2022 - 2025 — McMap. All rights reserved.