Python sshtunnel-如何验证SSH连接?

时间:2018-08-29 06:02:59

标签: python python-3.x ssh ssh-tunnel

使用Python,如何在执行以下操作后验证SSH连接是否成功:

server = SSHTunnelForwarder(
    (host_or_ip, 22),
    ssh_username = "ssh_username",
    ssh_private_key = path_to_key,
    remote_bind_address = (another_host_or_ip, 5432)
)

server.start()

2 个答案:

答案 0 :(得分:1)

我用它来查看隧道是否打开:

server.skip_tunnel_checkup = False
server.start()
server.check_tunnels()
print(server.tunnel_is_up, flush=True)

在日志中,您将看到:

{('0.0.0.0', 44004): True}  # this tunnel is up
{('0.0.0.0', 44004): False}  # this tunnel is not up

答案 1 :(得分:0)

您可以使用try-except块来做到这一点。

ssh_address_or_host = ...    
ssh_username = ... 
ssh_password = ... 
remote_bind_address = ... 

try:
    with SSHTunnelForwarder(
        ssh_address_or_host = ssh_address_or_host,
        ssh_username = ssh_username,
        ssh_password = ssh_password,
        remote_bind_address = remote_bind_address
        ) as server:
        print("connected")

except Exception as e:
    print("Non connected because: " + e)