0

我在设置 SSH 连接后尝试登录到远程服务器。我可以让 SSH 隧道工作,但从那里我很难过如何登录。

我目前正在使用 Python 的 sshtunnel 扩展,它成功地将我连接到我需要的地方。现在我需要能够登录,我通常会通过终端使用命令“ssh remotepc-ssh”(我将所有信息存储在 /.ssh/config 文件中)

我已经尝试过 paramiko,但它不断地给我错误或最终不会加载。我还尝试了 pysftp,这就是我在下面的代码中显示的内容,但是当我尝试获取我的 known_hosts 时,它告诉我它没有找到任何已知的主机,并且当我尝试将主机设置为无时,系统不会连接。

from sshtunnel import SSHTunnelForwarder
#import paramiko
import pprint
import pysftp

# create SSH tunnel

SERVER_HOST = "hostname"
SERVER_PASS = "********"

LOGIN_HOST = "loginUsername"
LOGIN_PASS = "*********" 


server = SSHTunnelForwarder(
    SERVER_HOST,
    ssh_password = SERVER_PASS,
    remote_bind_address=('127.0.0.1', 8080)
)

try:
    server.start()

    print("Connected to SSH Tunnel with local bind port %s" %server.local_bind_port)

    ###################################
    # BROKEN PART BELOW

    # establish remote connection
    try:

        print("\nEstablishing connection to %s" %LOGIN_HOST)

        cnopts = pysftp.CnOpts()
        cnopts.hostkeys.load = ("known_hosts")
        with pysftp.Connection(LOGIN_HOST, password = LOGIN_PASS, cnopts = cnopts) as sftp:
             print("CONNECTED")

    except:
        print("Unable to connect")
        pass

    ##################################

    server.stop()
    print("\nServer stopped. Goodbye")

except:
    print("Could not connect")
    pass
4

1 回答 1

1

我刚来并解决了同样的问题,所以让我分享一下我的工作示例:

with SSHTunnelForwarder(
    ("SSH_HOST",22),
    ssh_username="SSH_USERNAME",
    ssh_pkey="SSH_KEY",
    remote_bind_address=("SFTP_HOST", 22),
) as tunnel:
    # do some operations with client session
    with pysftp.Connection(host='127.0.0.1', port=server.local_bind_port, username="SFTP_USERNAME",
                           private_key="SFTP_KEY", cnopts=cnopts) as sftp:
        print("Connection succesfully stablished ... ")
        print(sftp.listdir('public'))
print('FINISH!')
于 2020-01-14T15:22:47.507 回答