之前使用sshtunnel的SSHTunnelForwarder方法建立隧道,建立了telnet、redis通讯。如果通过该方法建立SSH连接,应该怎么实现呢?
import paramiko
import sshtunnel
# 本地登录跳板机的秘钥
rsaKey = paramiko.RSAKey.from_private_key_file("private")
# 跳板机登录服务器的秘钥
Key = paramiko.RSAKey.from_private_key_file('id_rsa.txt')
# 建立本地与服务器隧道
with sshtunnel.open_tunnel(
('47.96.134.12', 6553),
ssh_username="jump",
ssh_pkey=rsaKey,
remote_bind_address=('192.168.80.101', 22),
local_bind_address=('0.0.0.0', 10022)
) as tunnel:
# 建立SSH连接
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 因为我的环境中免密登陆方式是在跳板机上生成跳板机自己的密钥,并发送至后端服务器进行认证,所以这里使用了跳板记得秘钥
client.connect('127.0.0.1',tunnel.local_bind_port, 'jump', pkey = Key )
#执行命令
stdin, stdout, stderr = client.exec_command("ps aux | grep 'nginx'")
print stdout.read()
client.close()
执行结果:
总结:
由于建立ssh连接需要有身份认证,而在需要环境中做了免密登陆的配置。如果环境中免密登陆的配置和我的环境一样,采用的是跳板机秘钥认证,则可以使用上面的代码实现建立ssh连接。附SSHClient.connect方法参数: