Python 中无法建立 SSH 隧道(不使用 Putty)

问题描述 投票:0回答:1

大家好,节日快乐!

我希望你们一切都好。我正在尝试使用 Python 自动化连接到 Redshift 服务器的过程,而不依赖 PuTTY。目前,我使用的是 Windows 计算机,我需要从 Redshift 服务器上的 PostgreSQL 中提取数据。然而,为了实现这一目标,我必须:

  1. 打开 PuTTY .exe

  2. 在 PuTTY 中输入此命令:

    "Putty -P <port_number> -noagent -N -L 5534:<redshift_host>:5534 <username>@<remote_host> -i <private_key_file> -pw <password>"

  3. 等待几秒钟,直到 PuTTY 显示隧道已打开

  4. 打开我的 Jupyter Python Notebook 并最终执行我的查询:

    cxn= psycopg2.connect(user="sql_username", 密码=“sql_password”, 主机=“主机IP”, 端口=5534, 数据库=“database_name”)

提取数据并将其存储为数据框。 由于这是一个相当手动且效率不高的过程,因此我一直在网上搜索以完全停止使用 PuTTY,并找到一种创建隧道并提取数据的新方法。我什至将 .ppk 密钥转换为 .pem 格式,以便与其他库一起使用。我正在使用 paramiko 和 SSHTunnelForwarder,但我并没有成功地实际正确连接到我的隧道。这是我的代码:

from sshtunnel import SSHTunnelForwarder


ssh_host = <remote_host>
ssh_port = <port_number>
ssh_user = <username>
ssh_key_path = 'ssh_key_redshift.pem'  
ssh_password = <password>

redshift_host = <redshift_host>
redshift_port = 5534
redshift_user = <username>


# Create an SSH tunnel
with SSHTunnelForwarder(
    (ssh_host, ssh_port),
    ssh_username=ssh_user,
    ssh_pkey=ssh_key_path,
    ssh_password=ssh_password,
    remote_bind_address=(redshift_host, redshift_port),
    local_bind_address=('localhost', 5534)
) as tunnel:
    print("SSH Tunnel established successfully.")
    input("Press Enter to close the tunnel...") 

但不幸的是,当我使用 shhtunnel 时,无法打开和连接隧道

我听说过 paramiko 图书馆,如果有人能帮助我,我会很高兴。本质上,我需要做的是使用

<port_number>
建立 SSH 隧道,将本地端口 5534 绑定到 Redshift 主机的端口 5534,使用凭据和我已转换为 .pem 的密钥文件。

我是一个非常细心和活跃的用户,我将阅读您所有的评论和建议,以选择可以让我结束这种嘘痛苦的答案

python ssh paramiko openssh ssh-tunnel
1个回答
0
投票

我不知道 redshift,但适应了我为 postgres 或 mariadb 所做的事情:

from sshtunnel import SSHTunnelForwarder
import redshift_connector


ssh_host = <remote_host>
ssh_port = <port_number>
ssh_user = <username>
ssh_key_path = 'ssh_key_redshift.pem'  
ssh_password = <password>

redshift_host = <redshift_host> # localhost
redshift_port = 5534 # ! default redshift port is 5539 !
redshift_user = <username>


# Create an SSH tunnel
with SSHTunnelForwarder (
    ssh_address_or_host=ssh_host,
    ssh_port=ssh_port,
    ssh_username=ssh_user,
    ssh_pkey=ssh_key_path,
    ssh_private_key_password=ssh_password,
    remote_bind_address=(redshift_host, redshift_port)
) as tunnel:
    print("SSH Tunnel established successfully.")


    with redshift_connector.connect(
        host=redshift_host,
        port=tunnel.local_bind_port,
        user=redshift_user,
        # database=?
     ) as conn:
        
        # do your stuff
© www.soinside.com 2019 - 2024. All rights reserved.