简体   繁体   English

检查Socket是否在python中使用

[英]Check if socket is in use in python

I am running a script that telnets to a terminal server . 我正在运行一个远程登录到terminal server的脚本。 Occasionally the script is launched while one instance is already running, which causes the already running script to fail with 有时在一个实例已经运行的情况下启动脚本,这会导致已经运行的脚本失败,并导致

EOFError: telnet connection closed

Is there a quick and easy and pythonic way to check if the required socket is already in use on the client computer before I try to open a connection with telnetlib ? 在尝试打开与telnetlib的连接之前,是否有一种快速,简便且pythonic方法来检查客户端计算机上是否已在使用所需的套接字?

SOLUTION: 解:

I wanted to avoid making a subprocess call but since I do not control software on the client computers, and other programs may be using the same socket, the file lock suggestion below (a good idea) wouldn't work for me. 我想避免进行子流程调用,但是由于我不控制客户端计算机上的软件,并且其他程序可能使用相同的套接字,因此下面的文件锁定建议(一个好主意)对我不起作用。 I ended up using SSutrave's suggestion. 我最终使用了SSutrave的建议。 Here is my working code that uses netstat in Windows 7: 这是我在Windows 7中使用netstat的工作代码:

# make sure the socket is not already in use
try:
    netstat = subprocess.Popen(['netstat','-nao'],stdout=subprocess.PIPE)
except:
    raise ValueError("couldn't launch netstat to check sockets. exiting")
ports = netstat.communicate()[0]
if (ip + ':' + port) in ports:
    print 'socket ' + ip + ':' + port + ' in use on this computer already. exiting'
    return

You can check for open ports by running the following linux command netstat | grep 'port number' | wc -l 您可以通过运行以下linux命令netstat | grep 'port number' | wc -l来检查打开的端口netstat | grep 'port number' | wc -l netstat | grep 'port number' | wc -l netstat | grep 'port number' | wc -l by importing subprocess library in python. netstat | grep 'port number' | wc -l通过在python中导入subprocess库。

There is not a standard way to know if a server has other opened connections before you attempt to connect to it. 在尝试连接服务器之前,没有一种标准的方法可以知道服务器是否具有其他打开的连接。 You must ask it either connecting to another service in the server that checks it, or by asking the other clients, if you know all of them. 您必须询问它是否连接到检查它的服务器中的另一个服务,或者询问其他客户端(如果您知道所有客户端)。

That said, telnet servers should be able to handle more than one connection at a time, so it should not matter if there are more clients connected. 话虽如此,telnet服务器应该一次能够处理多个连接,因此,是否有更多的客户端连接都没有关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM