python 通过SSHTunnelForwarder隧道连接redis

背景:我司Redis服务器使用的亚马逊服务,本地需要通过跳板机,然后才有权限访问Redis服务。

两种思路:

1、通过SSHTunnelForwarder,paramiko模块,先ssh到跳板机,然后在跳板机上(或者内部服务器上),获取到权限,然后远程Redis。

思路一:

private_key_path = /Users/xxx/.ssh/id_rsa
rsaKey = paramiko.RSAKey.from_private_key_file(private_key_path)

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(跳板机或者内网服务器IP或者域名, 22, username, rsaKey)
stdin, stdout, stderr = ssh.exec_command(redis-cli -h {} -p {} -n {} {}.format(host, port, db, script))
result = stdout.read(), stderr.read()
for out in result:  # 需要通过循环拿到stdout,否则为空值
    if out:
        return out

类似:

import paramiko
from sshtunnel import SSHTunnelForwarder

with SSHTunnelForwarder(
    (REMOTE_SERVER_IP, 443),
    ssh_username="",
    ssh_pkey="/var/ssh/rsa_key",
    ssh_private_key_password="secret",
    remote_bind_address=(PRIVATE_SERVER_IP, 22),
    local_bind_address=(0.0.0.0, 10022)
) as tunnel:
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(127.0.0.1, 10022)
    # do some operations with client session
    client.close()

print(FINISH!)

方法二:

Advice:

一般跳板机是个干净的机器,公司内网服务器大部分不会给权限或者有redis-client客户端,因此推荐使用方法2。

SSHTunnelForwarder使用:

经验分享 程序员 微信小程序 职场和发展