正在检查ip:远程主机上的端口已打开

2024-05-29 02:23:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个服务器和ip:端口(外部地址)的列表,我需要检查每个服务器是否可以连接到这些地址

在文件中循环并尝试打开一个sshtunnel,然后按如下所示进行连接

tunnel=sshtunnel.SSHTunnelForwarder(
                                    ssh_host=host,
                                    ssh_port=22,
                                    ssh_username=ssh_username, 
                                    ssh_pkey=privkey,
                                    remote_bind_address=(addr_ip, int(addr_port)),
                                    local_bind_address=('0.0.0.0', 10022)
                                    #,logger=sshtunnel.create_logger(loglevel=10)        
                                )     
tunnel.start()
# use socket
try:

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    res = s.connect(('localhost', 10022))
    print(res)
    #s.connect((addr_ip, int(addr_port)))
    s.close()
except socket.error as err:
    print('socket err:')
    print(err)
finally:
    s.close()

time.sleep(2)
tunnel.stop()

但在执行此操作时,响应始终为0(即sock可以连接到本地绑定),即使远程绑定不正确-但是sshtunnelforwarder抛出

ERROR   | Secsh channel 0 open FAILED: Network is unreachable: Connect failed
ERROR   | Could not establish connection from ('127.0.0.1', 10022) to remote side of the tunnel

如何使套接字命令检查远程绑定地址是否可用

我试图使用telnetlib,但遇到了类似的问题

代码实际上与替换为的套接字块相同

tn=telnetlib.Telnet()
tn.open('localhost',10022)
tn.close()

我对这一切都比较陌生,所以还在学习。如果有更好的方法来实现我需要做的事情,请让我知道

谢谢


Tags: ip服务器hostcloseport地址usernamesocket
2条回答

我没有尝试过,但是SSH隧道类有^{}属性,根据文档:

Describe whether or not the other side of the tunnel was reported to be up (and we must close it) or not (skip shutting down that tunnel)

内容示例(它是一本字典):

{('127.0.0.1', 55550): True,  # this tunnel is up
('127.0.0.1', 55551): False}  # this one isn't

所以你不需要自己建立明确的联系

注意:在设置隧道之前,您可能需要首先将属性^{}设置为False(默认情况下为向后兼容True),否则tunnel_is_up可能总是报告True

When skip_tunnel_checkup is disabled or the local bind is a UNIX socket, the value will always be True

因此,代码可能如下所示:

tunnel=sshtunnel.SSHTunnelForwarder(
    # ...
)
tunnel.skip_tunnel_checkup = False
tunnel.start()

# tunnel.tunnel_is_up should be populated with actual tunnel status(es) now

在您发布的代码中,您正在设置一个隧道,然后只需打开一个到隧道的本地端点的套接字,无论隧道处于何种状态,该端点显然都是打开的,因此它总是成功连接

另一种方法是实际尝试通过隧道建立SSH连接,但我想这就是您在评论中提到的paramiko.SSHclient替代方法

将属性^{}设置为False以启用对远程端可用性的检查(默认情况下为向后兼容性禁用):

tunnel.skip_tunnel_checkup = False

在启动隧道之前添加此选项将检查远程端在启动时是否启动,并引发可以处理的异常

删除了我的套接字代码

相关问题 更多 >

    热门问题