Hello,
Today's tip is regarding a topic that made me stuck for a while : how to connect to a server through another server, and all infrastructure uses public key to authenticate ?
I tried playing with ssh_agent and key forwarding, but I couldn't make it work. Then a suggestion was made to use port forwarding, which is much more straitforward and simple to handle/understand.
Here is a piece of code that should work for you :
#!/usr/bin/python
#
# Paramiko
#
import paramiko
import sys
import subprocess
#
# we instantiate a new object referencing paramiko's SSHClient class
#
vm = paramiko.SSHClient()
vm.set_missing_host_key_policy(paramiko.AutoAddPolicy())
k = paramiko.RSAKey.from_private_key_file("/path/to/the/key",password='private_key_password')
vm.connect('jump_server', username='login', pkey = k)
#
vmtransport = vm.get_transport()
dest_addr = ('dst_server', 22)
local_addr = ('jump_server', 22)
vmchannel = vmtransport.open_channel("direct-tcpip", dest_addr, local_addr)
#
jhost = paramiko.SSHClient()
jhost.set_missing_host_key_policy(paramiko.AutoAddPolicy())
jhost.connect('dst_server', username='login', password='xxxx', sock=vmchannel)
#we send a simple command
stdin, stdout, stderr = jhost.exec_command("hostname")
#we read the return from the dst_server
print stdout.read()
#we don't forget to close the SSH session
jhost.close()
vm.close()
# End
If you are using simple password, replace pkey by password.
Enjoy !

No comments:
Post a Comment