Robert Alexander
Robert Alexander

Reputation: 1151

Finding on which port a given server is running within python program

I am developing a python 3.11 program which will run on a few different servers and needs to connect to the local Redis server. On each machine the latter might run on a different port, sometimes the default 6379 but not always.

On the commandline I can issue the following command which on both my Linux and MacOS servers works well:

(base) bob@Roberts-Mac-mini ~ % sudo lsof -n -i -P | grep LISTEN | grep IPv4 | grep redis
redis-ser 60014            bob    8u  IPv4 0x84cd01f56bf0ee21      0t0    TCP *:9001 (LISTEN)

What's the better way to get the running port using python functions/libraries?

Upvotes: 0

Views: 110

Answers (1)

Kulasangar
Kulasangar

Reputation: 9434

What if you run your commands within a py script using the os library:

import os
cmd = 'ls -l' <-- change the command you want to run
os.system(cmd) 

or else you could also use subprocess library as well:

import subprocess
print(subprocess.check_output(['ls', '-l']))

Upvotes: 1

Related Questions