How to check if a network port is open on linux?

Fatima picture Fatima · Oct 5, 2013 · Viewed 118.9k times · Source

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?

Answer

mrjandro picture mrjandro · Oct 5, 2013

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()