如何使用python知道linux ubuntu上的某个端口是打开/关闭的,而不是远程系统? 如何在python中列出这些开放端口?
答案 0 :(得分:102)
您可以使用socket module来检查端口是否打开。
它看起来像这样。
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()
答案 1 :(得分:58)
如果要在更一般的上下文中使用它,则应确保打开的套接字也会关闭。所以检查应该更像这样:
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"
答案 2 :(得分:28)
对我来说,如果端口未打开,上面的示例将会挂起。第4行显示使用 settimeout 来防止挂起
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)
答案 3 :(得分:16)
如果您只关心本地计算机,则可以依赖psutil包。你可以:
检查特定pid使用的所有端口:
proc = psutil.Process(pid)
print proc.connections()
检查本地计算机上使用的所有端口:
print psutil.net_connections()
它也适用于Windows。
答案 4 :(得分:2)
Netstat工具只需解析一些/ proc文件,如/ proc / net / tcp,并将其与其他文件内容相结合。是的,它是高度平台特定的,但对于Linux专用解决方案,你可以坚持下去。 Linux内核文档详细描述了这些文件,因此您可以在那里找到如何阅读它们。
请注意你的问题太模糊了,因为“port”也可能意味着串口(/ dev / ttyS *和类似物),并口等等;我重新使用了另一个答案的理解,这是网络端口,但我会要求你更准确地提出你的问题。
答案 5 :(得分:2)
如果您在探测有意监听的TCP端口时,最好实际调用listen。使用连接的方法不会“看到”已建立连接的客户端端口,因为没有人会监听它。但是这些端口不能用来监听它。
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
答案 6 :(得分:1)
刚刚添加到mrjandro的解决方案快速破解简单的连接错误/超时。
您可以调整阈值更改max_error_count变量值并添加任何类型的通知。
import socket
max_error_count = 10
def increase_error_count():
# Quick hack to handle false Port not open errors
with open('ErrorCount.log') as f:
for line in f:
error_count = line
error_count = int(error_count)
print "Error counter: " + str(error_count)
file = open('ErrorCount.log', 'w')
file.write(str(error_count + 1))
file.close()
if error_count == max_error_count:
# Send email, pushover, slack or do any other fancy stuff
print "Sending out notification"
# Reset error counter so it won't flood you with notifications
file = open('ErrorCount.log', 'w')
file.write('0')
file.close()
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(2)
result = sock.connect_ex(('127.0.0.1',80))
if result == 0:
print "Port is open"
else:
print "Port is not open"
increase_error_count()
在这里你可以找到兼容Python 3的版本(只是修复了打印语法):
import socket
max_error_count = 10
def increase_error_count():
# Quick hack to handle false Port not open errors
with open('ErrorCount.log') as f:
for line in f:
error_count = line
error_count = int(error_count)
print ("Error counter: " + str(error_count))
file = open('ErrorCount.log', 'w')
file.write(str(error_count + 1))
file.close()
if error_count == max_error_count:
# Send email, pushover, slack or do any other fancy stuff
print ("Sending out notification")
# Reset error counter so it won't flood you with notifications
file = open('ErrorCount.log', 'w')
file.write('0')
file.close()
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(2)
result = sock.connect_ex(('127.0.0.1',80))
if result == 0:
print ("Port is open")
else:
print ("Port is not open")
increase_error_count()
答案 7 :(得分:1)
请检查迈克尔的答案并投票。这是检查打开的端口的正确方法。如果您正在开发服务或守护程序,则Netstat和其他工具将无用。例如,我正在为工业网络创建modbus TCP服务器和客户端服务。服务可以监听任何端口,但问题是该端口是否打开?该程序将在不同的地方使用,我无法手动检查它们,所以这就是我所做的:
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
答案 8 :(得分:0)
根据接受的答案,这是一个多线程端口扫描程序:
from time import sleep
import socket, ipaddress, threading
final = {}
def check_port(ip):
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,80)) # SIP port
if result == 0:
# print ("Port is open")
final[ip] = "OPEN"
else:
# print ("Port is closed/filtered")
final[ip] = "CLOSED"
sock.close()
except:
pass
for ip in ipaddress.IPv4Network('192.168.1.0/24'): # o
threading.Thread(target=check_port, args=[str(ip)]).start()
#sleep(0.1)
# the code below, can also be used on the above to limit the number of threads.
while threading.active_count() > 1:
sleep(1)
print(final)
答案 9 :(得分:0)
基于Joe提到的psutil
解决方案(仅适用于检查本地端口):
import psutil
1111 in [i.laddr.port for i in psutil.net_connections()]
如果当前使用端口1111,则返回True
。
psutil
不是python stdlib的一部分,因此您首先需要pip install psutil
。它还需要python标头可用,因此您需要类似python-devel
答案 10 :(得分:0)
在上面,我找到了多个解决方案。但是有些解决方案存在挂起问题,或者在打开端口时花费很多时间。下面的解决方案对我有用:
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")
答案 11 :(得分:0)
同意Sachin。只是一项改进,请使用connect_ex而不是connect,这样可以避免尝试
>>> def port_check(ip_port):
... s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
... s.settimeout(1)
... r = s.connect_ex(ip_port)
... return r == 0
...
>>> port_check(loc)
True
>>> port_check(loc_x)
False
>>> loc
('10.3.157.24', 6443)
>>>