Loading key from an SSH jumphost using Paramiko

梦想的初衷 提交于 2021-02-08 07:22:11

问题


I am connecting from host1 to host3 using a middle host2.

host1 --> host2 --> host3

Here is my code that is working fine:

# SSH to host2
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host2, username=host2_username)

# SSH to host3
vmtransport = ssh.get_transport()
dest_addr = (host3, 22)
local_addr = (host2, 22)
vmchannel = vmtransport.open_channel("direct-tcpip", dest_addr=dest_addr, src_addr=local_addr)
ssh3 = paramiko.SSHClient()
ssh3.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh3.connect(host3, username=host3_username, sock=vmchannel)

Now from host3 I want to SSH to the fourth host:

# SSH to host4
vmtransport = ssh3.get_transport()
dest_addr = (host4, 22)
local_addr = (host3, 22)
vmchannel = vmtransport.open_channel("direct-tcpip", dest_addr=dest_addr, src_addr=local_addr)

ssh4 = paramiko.SSHClient()
ssh4.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh4.connect(host4, username=host4_username, sock=vmchannel)

The last SSH fails because of authentication error. When I manually SSH to host3 from host4, it is working fine. I noticed that host3 has public key stored under .ssh folder. How can I let paramiko know to use the public key on host3 to SSH to host4.

In other words, does paramiko relies on the public keys under host1 to perform the nested SSH all the way to host4? If the answer is yes, do I need to store the public key of host4 on host1 too?


回答1:


Yes. You have to have all credentials locally. The port forwarding alone does not make credentials stored on the intermediate hosts available for authentication.

Of course, you can use SFTP to access/download the files/keys, like:

sftp3 = ssh3.open_sftp()

with sftp3.open(".ssh/id_rsa") as key_file:
    pkey = RSAKey.from_private_key(key_file)

ssh4.connect(host4, username=host4_username, sock=vmchannel, pkey=pkey)


来源:https://stackoverflow.com/questions/64328473/loading-key-from-an-ssh-jumphost-using-paramiko

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!