我可以使用以下命令从一台服务器到另一台服务器:
# ssh root@1.2.4.148
以下代码以pythonic方式执行相同的操作:
import paraminko
#paramiko.util.log_to_file('ssh.log') # sets up logging
client = paramiko.SSHClient()
client.load_system_host_keys()
client.connect('1.2.4.148')
stdin, stdout, stderr = client.exec_command('ls -l')
但如果我需要从第二台服务器连接到第三台服务器,我可以这样做:
# ssh -t root@1.2.4.148 ssh root@1.2.4.149
如何在python中完成? 我当前的服务器(250)使用148服务器保存的密码少,便于访问。但是如果重要的话,从148连接149将需要密码。
答案 0 :(得分:2)
此python函数将首先连接到middle_server,然后连接到last_server。它将执行命令" mycommand"在last_server上并返回它的输出。
def myconnect():
middle_server='1.2.3.4'
middle_port=3232
middle_user='shantanu'
middle_key_filename='/root/.ssh/id_rsa.pub'
last_server='6.7.8.9'
last_port=1224
last_user='root'
last_password='xxxxx'
mycommand='pwd'
import paramiko
proxy_client = paramiko.SSHClient()
proxy_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
proxy_client.connect(middle_server, port=middle_port, username=middle_user, key_filename=middle_key_filename)
transport = proxy_client.get_transport()
dest_addr = (last_server, last_port)
local_addr = ('127.0.0.1', 1234)
channel = transport.open_channel("direct-tcpip", dest_addr, local_addr)
remote_client = paramiko.SSHClient()
remote_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
remote_client.connect('localhost', port=last_port, username=last_user, password=last_password, sock=channel)
(sshin1, sshout1, ssherr1) = remote_client.exec_command(mycommand)
print sshout1.read()
except:
print "error"
return 0