Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a network port is open?

How can I know if a certain port is open/closed on linux ubuntu, not a remote system, using python? How can I list these open ports in python?

  • Netstat: Is there a way to integrate netstat output with python?
like image 463
Fatima Avatar asked Oct 05 '13 09:10

Fatima


People also ask

How do I check what ports I have open?

Answer: Open the Run command and type cmd to open the command prompt. Type: “netstat –na” and hit enter. Find port 445 under the Local Address and check the State. If it says Listening, your port is open.

How do I check if a port is open Windows 10?

Type netstat -ab and press Enter. You'll see a long list of results, depending on what's currently connecting to the network. You'll see a list of running processes. The open port numbers will be after the last colon on the local IP address (the one on the left).


2 Answers

You can using the socket module to simply check if a port is open or not.

It would look something like this.

import socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = sock.connect_ex(('127.0.0.1',80)) if result == 0:    print "Port is open" else:    print "Port is not open" sock.close() 
like image 117
mrjandro Avatar answered Sep 22 '22 03:09

mrjandro


If you want to use this in a more general context, you should make sure, that the socket that you open also gets closed. So the check should be more like this:

import socket from contextlib import closing     def check_socket(host, port):     with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:         if sock.connect_ex((host, port)) == 0:             print("Port is open")         else:             print("Port is not open") 
like image 25
Michael Avatar answered Sep 24 '22 03:09

Michael