我有服务器和ip:ports(外部地址)的列表,我需要检查每个服务器是否可以连接到那些地址。
浏览文件并尝试打开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(即,袜子可以连接到本地绑定-但是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
如何使我的套接字命令检查remote_bind_address是否可用?
我尝试使用telnetlib,但出现类似问题
代码与用socket块替换的代码实际上是相同的
tn=telnetlib.Telnet()
tn.open('localhost',10022)
tn.close()
我对所有这一切都比较陌生,所以仍要学习。如果有更好的方法来实现我的需要,请告诉我。
谢谢
我还没有尝试过,但是有SSH隧道类的tunnel_is_up
属性,根据文档所述:
描述是否已报告隧道另一端(我们必须将其关闭)(跳过以关闭该隧道)
其内容示例(是字典):
tunnel_is_up
因此您不必自己进行显式连接。
在您发布的代码中,您正在建立一个隧道,然后只是打开到隧道本地端点的套接字,无论隧道处于什么状态,它显然都是打开的,因此它总是可以成功连接。
[另一种方法实际上是尝试通过隧道建立SSH连接,但这是您在评论中提到的{('127.0.0.1', 55550): True, # this tunnel is up
('127.0.0.1', 55551): False} # this one isn't
替代方案。
tunnel.skip_tunnel_checkup = False
在启动隧道之前添加此内容会检查远程端是否已启动,并抛出可以处理的异常。
已删除我的套接字代码。