需要用到的模块:sshtunnel,paramiko
通过sshtunnel建立客户端与跳板机的隧道,然后再通过paramiko链接服务器即可
常见配置如下:
import paramiko
from sshtunnel import SSHTunnelForwarder
with SSHTunnelForwarder (
('跳板机IP',port1),
ssh_username=username,
ssh_pkey='/home/username/.ssh/xx',
remote_bind_address=('你需要连接的服务器IP', port2),
local_bind_address=('客户端IP', port3)
) as server:
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy()
client.connect('客户端IP', port3, username)
stdin, stdout, stderr = client.exec_command(command)
print stdout.read()
client.close()
port1,port2为服务器开放端口,port3是自己定义的端口
参考:https://github.com/pahaz/sshtunnel