In translating some scripts from bash, I am encountering many uses of netstat -an to find if one of our services is listening. While I know I can just use subprocess.call or other even popen I would rather use a pythonic solution so I am not leveraging the unix environment we are operating in.
From what I have read the socket module should have something but I haven't seen anything that checks for listening ports. It could be me not understanding a simple trick, but so far I know how to connect to a socket, and write something that lets me know when that connection failed. But not necessarily have I found something that specifically checks the port to see if its listening.
Any ideas?
You can use Netstat -b -a -o. This tool provides a list of all open ports and their associated processes. The -o shows the process id, which you can look up in your task manager or processes tab.
Are you running it on Windows? If yes, try: p = Popen(['runas', '/noprofile', '/user:Administrator', 'netstat','nb'],stdin=PIPE, stdout= PIPE) p. stdin. write('password') stdout, stderr = p.
How about trying to connect...
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = s.connect_ex(('127.0.0.1', 3306))
if result == 0:
print('socket is open')
s.close()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With