How to check if a network port is open? - python

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?

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

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

For me the examples above would hang if the port wasn't open. Line 4 shows use of settimeout to prevent hanging
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(2) #2 Second Timeout
result = sock.connect_ex(('127.0.0.1',80))
if result == 0:
print 'port OPEN'
else:
print 'port CLOSED, connect_ex returned: '+str(result)

If you only care about the local machine, you can rely on the psutil package. You can either:
Check all ports used by a specific pid:
proc = psutil.Process(pid)
print proc.connections()
Check all ports used on the local machine:
print psutil.net_connections()
It works on Windows too.
https://github.com/giampaolo/psutil

Here's a fast multi-threaded port scanner:
from time import sleep
import socket, ipaddress, threading
max_threads = 50
final = {}
def check_port(ip, port):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # TCP
#sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
socket.setdefaulttimeout(2.0) # seconds (float)
result = sock.connect_ex((ip,port))
if result == 0:
# print ("Port is open")
final[ip] = "OPEN"
else:
# print ("Port is closed/filtered")
final[ip] = "CLOSED"
sock.close()
except:
pass
port = 80
for ip in ipaddress.IPv4Network('192.168.1.0/24'):
threading.Thread(target=check_port, args=[str(ip), port]).start()
#sleep(0.1)
# limit the number of threads.
while threading.active_count() > max_threads :
sleep(1)
print(final)
Live Demo

I found multiple solutions in this post. But some solutions have a hanging issue or takeing too much time in case of the port is not opened.Try below solution :
import socket
def port_check(HOST):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2) #Timeout in case of port not open
try:
s.connect((HOST, 22)) #Port ,Here 22 is port
return True
except:
return False
port_check("127.0.1.1")

In case when you probing TCP ports with intention to listen on it, it’s better to actually call listen. The approach with tring to connect don’t 'see' client ports of established connections, because nobody listen on its. But these ports cannot be used to listen on its.
import socket
def check_port(port, rais=True):
""" True -- it's possible to listen on this port for TCP/IPv4 or TCP/IPv6
connections. False -- otherwise.
"""
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('127.0.0.1', port))
sock.listen(5)
sock.close()
sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
sock.bind(('::1', port))
sock.listen(5)
sock.close()
except socket.error as e:
return False
if rais:
raise RuntimeError(
"The server is already running on port {0}".format(port))
return True

Building upon the psutil solution mentioned by Joe (only works for checking local ports):
import psutil
1111 in [i.laddr.port for i in psutil.net_connections()]
returns True if port 1111 currently used.
psutil is not part of python stdlib, so you'd need to pip install psutil first. It also needs python headers to be available, so you need something like python-devel

Agree with Sachin. Just one improvement, use connect_ex instead of connect, which can avoid try except
>>> def port_check(ip_port):
... s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
... s.settimeout(1)
... return s.connect_ex(ip_port) == 0
...
>>> port_check(loc)
True
>>> port_check(loc_x)
False
>>> loc
('10.3.157.24', 6443)
>>>

Just added to mrjandro's solution some improvements like automatic resource management (making sure that the opened socket also gets closed), handling timeouts, getting rid of simple connection errors / timeouts and printing out results:
import socket
from contextlib import closing
hosts = ["host1", "host2", "host3"]
port = 22
timeout_in_seconds = 2
hosts_with_opened_port = []
hosts_with_closed_port = []
hosts_with_errors = []
def check_port(host, port, timeout_in_seconds):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout_in_seconds)
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
try:
result = sock.connect_ex((host, port))
if result == 0:
print("Port {} is *** OPEN *** on host: {}".format(port, host))
hosts_with_opened_port.append(host)
else:
print("Port {} is not open on host: {}".format(port, host))
hosts_with_closed_port.append(host)
except socket.gaierror:
print("Port {} check returns a network *** ERROR *** on host: {}".format(port, host))
hosts_with_errors.append(host)
for host in hosts:
check_port(host, port, timeout_in_seconds)
print("\nHosts with opened port:")
print(hosts_with_opened_port)
print("\nHosts with closed port:")
print(hosts_with_closed_port)
print("\nHosts with errors:")
print(hosts_with_errors)

Netstat tool simply parses some /proc files like /proc/net/tcp and combines it with other files contents. Yep, it's highly platform specific, but for Linux-only solution you can stick with it. Linux kernel documentation describes these files in details so you can find there how to read them.
Please also notice your question is too ambiguous because "port" could also mean serial port (/dev/ttyS* and analogs), parallel port, etc.; I've reused understanding from another answer this is network port but I'd ask you to formulate your questions more accurately.

Please check Michael answer and vote for it. It is the right way to check open ports. Netstat and other tools are not any use if you are developing services or daemons. For instance, I am crating modbus TCP server and client services for an industrial network. The services can listen to any port, but the question is whether that port is open? The program is going to be used in different places, and I cannot check them all manually, so this is what I did:
from contextlib import closing
import socket
class example:
def __init__():
self.machine_ip = socket.gethostbyname(socket.gethostname())
self.ready:bool = self.check_socket()
def check_socket(self)->bool:
result:bool = True
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
modbus_tcp_port:int = 502
if not sock.connect_ex((self.machine_ip, modbus_tcp_port)) == 0:
result = False
return result

This will find a random port in the given range:
import socket
import random
from typing import Tuple
def find_listening_port(
port_range:Tuple[int,int]=None,
host='',
socket_type='tcp',
default:int=None
) -> int:
"""Find an available listening port
Arguments:
port_range: Optional tuple of ports to randomly search, ``[min_port, max_port]``
If omitted, then randomly search between ``[6000, 65534]``
host: Host interface to search, if omitted then bind to all interfaces
socket_type: The socket type, this should be ``tcp`` or ``udp``
default: The port to try first before randomly searching the port range
Returns:
Available port for listening
"""
def _test_port(host, port, socket_protocol):
with socket.socket(socket.AF_INET, socket_protocol) as sock:
try:
sock.bind((host, port))
if socket_type == 'tcp':
sock.listen(1)
return port
except:
pass
return -1
if port_range is None:
port_range = (6000,65534)
if socket_type == 'tcp':
socket_protocol = socket.SOCK_STREAM
elif socket_type == 'udp':
socket_protocol = socket.SOCK_DGRAM
else:
raise Exception('Invalid socket_type argument, must be: tcp or udp')
searched_ports = []
if default is not None:
port = _test_port(host, default, socket_protocol)
if port != -1:
return port
searched_ports.append(default)
for _ in range(100):
port = random.randint(port_range[0], port_range[1])
if port in searched_ports:
continue
port = _test_port(host, port, socket_protocol)
if port != -1:
return port
searched_ports.append(port)
raise Exception(f'Failed to find {socket_type} listening port for host={host}')
Example usage:
# Find a TCP port,
# first check if port 80 is availble
port = find_listening_port(
port_range=(4000, 60000),
host='',
socket_type='tcp',
default=80
)
print(f'Available TCP port: {port}')

Related

Check If Port is Open in Python3?

In python 3 Given an IP address, I want to check if a specefic port is open for TCP Connection. How can I do that?
Please Note, I don't want to wait at all. If no response was recieved immediately then just report it's closed.
This is a Python3 example I got from https://www.kite.com/python/answers/how-to-check-if-a-network-port-is-open-in-python
import socket
a_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 8080
location = ("127.0.0.1", port)
check = a_socket.connect_ex(location)
if check == 0:
print("Port is open")
else:
print("Port is not open")
You can use simple script
#!/usr/bin/python
import socket
host = "127.0.0.1"
port = 9003
# try to connect to a bind shell
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
print(f"Port {port} is open")
s.close()
except socket.error:
print(f"Port {port} closed.")
Constant socket.SOCK_STREAM here response for TCP connection.
You can do something like this to check if a port is taken or if it's open:
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
location = ("127.0.0.1", 80)
result = sock.connect_ex(location)
if result == 0:
print("Port is open")
else:
print("Port is closed")
In this, the socket.AF_INET specifies the IP address family (IPv4) and socket.SOCK_STREAM specifies the socket type (TCP).

How can you make a Client-Server with 2 different computers in the lan?

It just times out for me , even if I use the gethostbyname method or gethostname for the private ip address....
Code:
def connect(self):
nm = nmap.PortScanner()
nm.scan(hosts = '192.168.1.0/24', arguments = '-n -sP -PE -PA21,23,80,3389')
devices = []
hosts_list = [(x,nm[x]['status']['state']) for x in nm.all_hosts()]
for ip,state in hosts_list:
devices.append(ip)
for ip in devices:
print(ip, type(ip))
try:
client_socket = socket.socket()
client_socket.settimeout(2)
try:
client_socket.connect((ip, self.port))
if type(client_socket) != None:
client_socket.send('hi'.encode())
client_socket.settimeout(None)
return client_socket
except Exception as e:
print(e)
except socket.error:
pass
When it gets to the correct Ip, it just... times out. Thought I had a problem with the function, but it appeared to not be the case.
TLDR- made a LAN automatic connecting using Nmap, the only thing it's connecting to is timeouts and my sadness D:
Edit: lemme show you the errors which occur when I run this function:
server:
server_socket = socket.socket()
hostname = socket.gethostname()
local_ip = socket.gethostbyname(hostname)
server_socket.bind((local_ip,self.port))
both sides decide the port which they want to use, i use socket.gethostbyname for server ip.

How do I get free ports in the specific range in python

I can use python to get free ports, but I want to get a specific range of free ports.
I try to get it using a while loop, but I can't get the vaule I wanted, maybe take a long time
import socket
SO_BINDTODEVICE=25
def get_free_port(iface=None):
s = socket.socket()
if iface:
s.setsockopt(socket.SOL_SOCKET, SO_BINDTODEVICE, bytes(iface,'utf8'))
s.bind(('',0))
port = 0
while(port<60100 or port>60300):
ip = s.getsockname()[0]
port = s.getsockname()[1]
s.close()
return ip,port
print(get_free_port())
I hope to get the port I want in a short time
def next_free_port( port=1024, max_port=65535 ):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
while port <= max_port:
try:
sock.bind(('', port))
sock.close()
return port
except OSError:
port += 1
raise IOError('no free ports')

Send string from mac to raspberry pi wirelessly [duplicate]

This question already has answers here:
Utilising bluetooth on Mac with Python
(2 answers)
Closed 4 years ago.
I am using a mac to try and send a string wirelessly to a raspberry pi using Bluetooth with python. However, I was not able to find an API that works with mac. I have tried options like pybluez and lightblue, but it seems like they don't work with mac. Is there a solution available for this? Bluetooth communication would be preferable, but I am open to other suggestions. Thanks in advance
Updated Answer
Still using netcat approach as below, but this is the sender implemented in Python adapted from this answer and works with the receiver below:
#!/usr/local/bin/python3
import socket
def netcat(host, port, content):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, int(port)))
s.sendall(content.encode())
s.shutdown(socket.SHUT_WR)
while True:
data = s.recv(4096)
if not data:
break
print(repr(data))
s.close()
netcat('192.168.0.131', 40000, 'Hi')
Here is a matching listener/server as implemented here that works with the sender above or the simple netcat sender from the command line.
#!/usr/bin/env python
import socket
import select
class SocketServer:
""" Simple socket server that listens to one single client. """
def __init__(self, host = '0.0.0.0', port = 2010):
""" Initialize the server with a host and port to listen to. """
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.host = host
self.port = port
self.sock.bind((host, port))
self.sock.listen(1)
def close(self):
""" Close the server socket. """
print('Closing server socket (host {}, port {})'.format(self.host, self.port))
if self.sock:
self.sock.close()
self.sock = None
def run_server(self):
""" Accept and handle an incoming connection. """
print('Starting socket server (host {}, port {})'.format(self.host, self.port))
client_sock, client_addr = self.sock.accept()
print('Client {} connected'.format(client_addr))
stop = False
while not stop:
if client_sock:
# Check if the client is still connected and if data is available:
try:
rdy_read, rdy_write, sock_err = select.select([client_sock,], [], [])
except select.error:
print('Select() failed on socket with {}'.format(client_addr))
return 1
if len(rdy_read) > 0:
read_data = client_sock.recv(255)
# Check if socket has been closed
if len(read_data) == 0:
print('{} closed the socket.'.format(client_addr))
stop = True
else:
print('>>> Received: {}'.format(read_data.rstrip()))
if read_data.rstrip() == 'quit':
stop = True
else:
client_sock.send(read_data)
else:
print("No client is connected, SocketServer can't receive data")
stop = True
# Close socket
print('Closing connection with {}'.format(client_addr))
client_sock.close()
return 0
def main():
server = SocketServer(port=40000)
server.run_server()
print('Exiting')
if __name__ == "__main__":
main()
Original Answer
Try using netcat or nc.
On RaspberryPi, listen on port 40,000 using TCP:
nc -l 40000
On Mac, assuming RaspberryPi has IP address of 192.168.0.131:
echo "hi" | /usr/bin/nc 192.168.0.131 40000
RaspberryPi shows:
hi

Implementation of Port scan in Python

I have a program that scans for open ports on remote host.
It will take long time to complete the scan.I want to make it work fast.
Here's my code:
Port Scan
import socket
import subprocess
host = input("Enter a remote host to scan: ")
hostIP = socket.gethostbyname(host)
print("Please wait, scanning remote host", hostIP)
try:
for port in range(1,1024):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((hostIP, port))
if result == 0:
print("Port: \t Open".format(port))
sock.close()
Could one of you Python wizards help me with this.
Advance Thanks.
You can set a timeout on the socket so it wont spend to much time on a closed port. I would also use threads and allow the user to specify how many threads they want to run. here is a link to some code you could adapt to implement threading with the threading module Python Network Programming.
#!/usr/bin/env python
'''
A simple port scanner.
'''
import socket
def scan_host(host, **options):
'''
Scan a host for open ports.
'''
options.setdefault('timeout', 0.30)
options.setdefault('port_range', (1, 1024))
timeout = options.get('timeout')
port_range = options.get('port_range')
host_ip = socket.gethostbyname(host)
print("Please wait, scanning remote host {} : {}".format(host, host_ip))
for port in xrange(*port_range):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
result = sock.connect_ex((host_ip, port))
if result == 0:
print "Port: {} Open".format(port)
sock.close()
if __name__ == '__main__':
scan_host('www.google.com', timeout=0.30, port_range=(1, 8000))
This program became too simple. It monitors only one port at once and it takes long time on one port to see if it is listening. So try reducing the time to listen, if it can't connect, deem it to be closed by setting a recursion limit for that number under the "expect:" in run().
As in like this,
try:
# connect to the given host:port
result = sock.connect_ex((hostIP, port))
if result == 0:
print "%s:%d Open" % (hostIP, port)
sock.close()
except: #pass
sock.recurse += 1
if sock.recurse < sock.limit:
sock.run()
else:
print "%s:%d Closed" % (hostIP, port)
There is other way to make it much more efficient by importing threading() module which can be used to keep an eye on a large number of sockets at once.
Here's the document on threading.
Refer this,
https://docs.python.org/2/library/threading.html#
Hope that helped you.
All the best.

Categories

Resources