You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python无需PuTTY建立SSH隧道失败,求技术解决方案

用Python替代PuTTY建立SSH隧道连接Redshift(Windows环境)

问题背景

原本手动通过PuTTY建立SSH隧道,将本地5534端口绑定到Redshift主机的5534端口,再通过psycopg2查询数据。现需用Python的SSHTunnelForwarder实现自动化,已将PuTTY的.ppk密钥转换为.pem格式,但隧道建立失败。

修正后的完整实现代码

先确保安装依赖:

pip install sshtunnel paramiko psycopg2-binary pandas

以下是包含隧道建立、Redshift数据提取的完整代码:

from sshtunnel import SSHTunnelForwarder
import paramiko
import psycopg2
import pandas as pd

# --------------------------
# 配置参数(替换为你的实际值)
# --------------------------
# SSH跳板机参数
ssh_host = "<remote_host>"
ssh_port = 22  # 替换为实际SSH端口,通常是22
ssh_user = "<username>"
ssh_key_path = "ssh_key_redshift.pem"
ssh_key_passphrase = "<your_key_password>"  # 密钥有密码则填,无则注释

# Redshift参数
redshift_host = "<redshift_host>"
redshift_port = 5534
redshift_user = "<sql_username>"
redshift_password = "<sql_password>"
redshift_db = "<database_name>"
target_query = "SELECT * FROM your_target_table LIMIT 100;"  # 替换为你的查询语句

# 加载PEM密钥
private_key = paramiko.RSAKey.from_private_key_file(ssh_key_path, password=ssh_key_passphrase)

# 建立SSH隧道并提取数据
with SSHTunnelForwarder(
    (ssh_host, ssh_port),
    ssh_username=ssh_user,
    ssh_pkey=private_key,
    # 如果SSH跳板机需要用户密码而非密钥密码,取消下面注释并注释ssh_pkey参数
    # ssh_password="<ssh_user_login_password>",
    remote_bind_address=(redshift_host, redshift_port),
    local_bind_address=("localhost", 5534),
    debug_level="DEBUG"  # 开启调试日志,方便排查问题
) as tunnel:
    print(f"SSH隧道已成功建立,本地绑定端口: {tunnel.local_bind_port}")
    
    # 连接Redshift
    conn = psycopg2.connect(
        user=redshift_user,
        password=redshift_password,
        host="localhost",
        port=tunnel.local_bind_port,
        database=redshift_db
    )
    
    # 执行查询并转为DataFrame
    df = pd.read_sql(target_query, conn)
    
    # 保存数据(示例为CSV,可按需修改格式)
    df.to_csv("redshift_extracted_data.csv", index=False)
    print(f"数据提取完成,共{len(df)}条记录,已保存到redshift_extracted_data.csv")
    
    # 关闭数据库连接
    conn.close()

常见故障排查要点

  • 密钥权限问题:Windows下需限制pem文件的访问权限,仅当前用户可读。操作步骤:右键pem文件→属性→安全→高级→禁用继承→删除所有非当前用户的权限条目,仅保留当前用户的读取权限。
  • 端口占用:用命令netstat -ano | findstr :5534检查本地5534端口是否被占用,若占用可更换本地端口(修改local_bind_address的端口值)或杀掉占用进程。
  • 密码混淆:ssh_password是SSH跳板机的用户登录密码,ssh_private_key_password是PEM密钥的保护密码,不要混淆使用。
  • 网络/安全组限制:确认:
    • 本地Windows防火墙允许Python程序访问网络
    • SSH跳板机的安全组允许你的Windows机器访问对应SSH端口
    • Redshift集群的安全组允许SSH跳板机访问5534端口
  • 调试日志分析:开启debug_level="DEBUG"后,查看控制台输出的错误信息,定位具体失败原因(如密钥验证失败、连接超时等)。

内容的提问来源于stack exchange,提问作者R_Student

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 18:23:31