使用Python识别监听端口 [英] Identifying listening ports using Python

查看:592
本文介绍了使用Python识别监听端口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在翻译bash中的某些脚本时,我遇到了netstat -an的许多用法,以发现我们的服务之一是否正在监听.虽然我知道我可以只使用subprocess.call或其他甚至popen的方法,但我宁愿使用pythonic解决方案,因此我不会利用我们正在操作的unix环境.

In translating some scripts from bash, I am encountering many uses of netstat -an to find if one of our services is listening. While I know I can just use subprocess.call or other even popen I would rather use a pythonic solution so I am not leveraging the unix environment we are operating in.

从我读过的内容来看,套接字模块应该有一些东西,但是我没有看到任何检查监听端口的东西.可能是我不了解一个简单的技巧,但是到目前为止,我知道如何连接到套接字,并且编写了一些可以让我知道该连接何时失败的内容.但是不一定我找到了专门检查端口以查看其是否在监听的东西.

From what I have read the socket module should have something but I haven't seen anything that checks for listening ports. It could be me not understanding a simple trick, but so far I know how to connect to a socket, and write something that lets me know when that connection failed. But not necessarily have I found something that specifically checks the port to see if its listening.

有什么想法吗?

推荐答案

如何尝试连接...

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = s.connect_ex(('127.0.0.1', 3306))

if result == 0:
    print('socket is open')
s.close()

这篇关于使用Python识别监听端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆