Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identifying listening ports using Python

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?

like image 686
Malforus Avatar asked Sep 15 '11 20:09

Malforus


People also ask

What tool can be used to identify listening ports and bindings?

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.

How do I run a netstat command in Python?

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.


1 Answers

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()
like image 75
sberry Avatar answered Sep 20 '22 01:09

sberry