Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

python - Nested SSH with Paramiko and RSA key file

I am trying to nested SSH using Paramiko where I will connect to Server X from my local machine and from there I will connect to Server Y. Here to connect to Server X I am using username, password authentication and to connect to Server Y using username and RSA key. The thing is that the RSA key is hosted in System X which is used to connect Server Y. I was able to run the script successfully if I hosted the keyfile in my local PC and gave the local pc directory path to Paramiko SSH client. But I want to read key file from Server X directly. How can I do that please help me.

Server X key file = "/home/test/keys/id_rsa"

import time
import paramiko,io
import csv
import sys
import subprocess

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect('X',22, username='subhash', password='mit@12345')

vmtransport = ssh.get_transport()
dest_addr = ('Y', 22)
local_addr = ('X', 22)
vmchannel = vmtransport.open_channel("direct-tcpip", dest_addr, local_addr)

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

remote_file = paramiko.RSAKey.from_private_key_file('C:/Users/test/Documents/hindi/id_rsa')
client.connect('Y', username='root',pkey=remote_file,sock=vmchannel)

client_stdin ,client_stdout, client_stderr = client.exec_command("pwd")
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You cannot use port forwarding to implement the jump, if you need to use a private key stored on the jump server.

  • Either download the key to the local machine. If you do not want to physically store the key on the local machine, you can download it to memory in your Python code only. See Loading key from an SSH jumphost using Paramiko.

  • Otherwise you would have to implement the jump by running ssh client on the jump server, which will pick up the private key stored there (what is normally a lame solution):

    ssh.exec_command("ssh root@Y pwd")
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...