Python:如何检查networking端口是否在Linux上打开?
我怎么能知道某个端口是开放/closures在Linux Ubuntu的,而不是远程系统,使用Python? 我怎样才能列出这些打开的端口在Python?
- Netstat:有没有办法整合netstat输出与python?
您可以使用套接字模块简单地检查一个端口是否打开。
它看起来像这样。
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"
如果你只关心本地机器,你可以依赖于psutil包。 你可以:
-
检查特定pid使用的所有端口:
proc = psutil.Process(pid) print proc.connections()
-
检查本地机器上使用的所有端口:
print psutil.net_connections()
它也适用于Windows。
如果你想在更一般的上下文中使用它,你应该确保你打开的套接字也被closures。 所以检查应该更像这样:
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"
对于我来说,如果端口没有打开,上面的例子就会挂起。 第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)
Netstat工具简单地parsing/ proc / net / tcp等一些/ proc文件,并将其与其他文件内容结合起来。 是的,这是高度平台特定的,但只有Linux的解决scheme,你可以坚持下去。 Linux内核文档详细描述这些文件,所以你可以在那里find如何阅读它们。
请注意你的问题太模棱两可了,因为“port”也可能意味着串口(/ dev / ttyS *和analogs),并行端口等。 我已经从另一个答案重用了理解这是networking端口,但我会问你更准确地制定你的问题。
刚刚添加到mrjandro的解决scheme一个简单的黑客来摆脱简单的连接错误/超时。
您可以调整阈值更改max_error_countvariables值并添加任何types的通知。
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()
在这里你find一个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()
如果您在探测TCP端口时试图侦听,最好实际调用listen。 tring连接的方法不会'看见'build立的连接的客户端口,因为没有人听它的。 但是这些端口不能用来听它的。
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