2016-01-23 178 views
0

我試圖連接到遠程連接到服務器,然後訪問它與蟒蛇本地數據庫。我成功地連接到服務器,但我似乎無法連接到服務器上的數據庫。我的代碼如下:通過SSH隧道連接到PostgreSQL數據庫的Python

import psycopg2 
from sshtunnel import SSHTunnelForwarder 

try: 

    with SSHTunnelForwarder(
     ('<server ip address>', 22), 
     ssh_private_key="</path/to/private/ssh/key>", 
     ssh_username="<server username>", 
     remote_bind_address=('localhost', 5432)) as server: 

     print "server connected" 

     conn = psycopg2.connect(database="<dbname>",port=server.local_bind_port) 
     curs = conn.cursor() 
     print "database connected 

except: 
    print "Connection Failed" 

這是我在互聯網上找到的一些代碼示例。我也曾嘗試下面的連接語句來代替那些連接上面的:

params = { 
    'database': '<dbname>', 
    'user': '<dbusername>', 
    'password': '<dbuserpass>', 
    'host': 'localhost', 
    'port': 5432 
} 
conn = psycopg2.connect(**params) 

我知道我可以連接到數據庫,因爲我的機器上;我能夠使用sqlectron隧道並連接正確。

爲防萬一還不清楚上面要做什麼,我需要在我的計算機上使用專用ssh密鑰(正常工作)將隧道連接到遠程服務器,然後我需要連接到PostgreSQL數據庫是在localhost在端口5432

我目前獲取當前的錯誤消息的嘗試連接兩種方式:

2016-01-23 11:16:10,978 | ERROR | Tunnel: 0.0.0.0:49386 <> localhost:5432 error: (9, 'Bad file descriptor') 

回答

1

我不知道這可能是有益的,但我不得不通過SSH隧道來連接到PostgreSQL數據庫以及。我succeded使用你的代碼進行一些修改連接:

import psycopg2 
from sshtunnel import SSHTunnelForwarder 

try: 

    with SSHTunnelForwarder(
     ('<server ip address>', 22), 
     #ssh_private_key="</path/to/private/ssh/key>", 
     ### in my case, I used a password instead of a private key 
     ssh_username="<server username>", 
     ssh_password="<mypasswd>", 
     remote_bind_address=('localhost', 5432)) as server: 

     server.start() 
     print "server connected" 

     params = { 
      'database': '<dbname>', 
      'user': '<dbusername>', 
      'password': '<dbuserpass>', 
      'host': 'localhost', 
      'port': local_bind_port 
      } 

     conn = psycopg2.connect(**params) 
     curs = conn.cursor() 
     print "database connected" 

except: 
    print "Connection Failed" 

加入server.start()後,代碼工作很好。此外,在「連接數據庫」後,引號丟失。 我希望這可能對您有所幫助,感謝分享你的代碼!

+0

我試圖上面的代碼,但我看到以下錯誤'HandlerSSHTunnelForwarderError:在#1 < - ( '127.0.0.1',53281)至('10 .160.1.24' ,5432)失敗:ChannelException( 2,'連接失敗')'。任何想法我可能做錯了什麼? –

0

兩個例子是非常有益的。我有一個在db連接中手動綁定本地端口的問題。我猜我們的服務器上有一個動態端口?我結合了這兩個例子的元素。使用sever.local_bind_port可能是一個更健壯和動態的解決方案。

from sshtunnel import SSHTunnelForwarder #Run pip install sshtunnel 
from sqlalchemy.orm import sessionmaker #Run pip install sqlalchemy 

with SSHTunnelForwarder(
    ('<remote server ip>', 22), #Remote server IP and SSH port 
    ssh_username = "<username>", 
    ssh_password = "<password>", 
    remote_bind_address=('<local server ip>', 5432)) as server: #PostgreSQL server IP and sever port on remote machine 

    server.start() #start ssh sever 
    print 'Server connected via SSH' 

    #connect to PostgreSQL 
    local_port = str(server.local_bind_port) 
    engine = create_engine('postgresql://<username>:<password>@127.0.0.1:' + local_port +'/database_name') 

    Session = sessionmaker(bind=engine) 
    session = Session() 

    print 'Database session created' 

    #test data retrieval 
    test = session.execute("SELECT * FROM database_table") 
    for row in test: 
     print row['id'] 

    session.close()