SSH连接服务器PG数据库并提取数据

本文介绍如何使用Python通过SSH连接到远程服务器的PostgreSQL(PG)数据库,检索数据并将其导出为Excel文件,实现远程数据处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

利用SSH连接服务器并从服务器上的PG数据库提取数据,保存为excel文件。

Python代码如下:

## connectted to postgresql DB in the local PC
import psycopg2
import paramiko
from sshtunnel import SSHTunnelForwarder
import xlsxwriter


#获取密钥
private_key=paramiko.RSAKey.from_private_key_file('privacy_key_filepath\\id_rsa') #私钥路径

with SSHTunnelForwarder(
        ssh_address_or_host=('192.168.2.9',22), #ssh主机IP+端口,本例局域网
        ssh_pkey=private_key,  
        ssh_username='hrm',  #服务器用户名        
        remote_bind_address=('127.0.0.1',5432)) as server:  #数据库服务器地址及端口
#    server.start() #start ssh sever
    conn=psycopg2.connect(database="test_db",
                          user="tester",
                          password="test_user",
                          host="127.0.0.1",
                          port=server.local_bind_port) 
    print('connected to the DB successfully')    
    cur=conn.cursor()
    L=['title','content','url','user_name'] #列标题
    with xlsxwrit
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值