使用SSHTunnelForwarder的HandlerSSHTunnelForwarderError

时间:2016-06-23 20:14:47

标签: postgresql ssh sqlalchemy paramiko ssh-tunnel

我正在尝试连接到我的远程postgres数据库,如下所示:

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

with SSHTunnelForwarder(
    ('10.160.1.24', 22), #Remote server IP and SSH port
    ssh_username = "<usr>",
    ssh_password = "<pwd>",
    remote_bind_address=('10.160.1.24', 5432),
    local_bind_address=('127.0.0.1', 3334)
    ) as server:

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

    #connect to PostgreSQL
    local_port = str(server.local_bind_port)
    engine = create_engine('postgresql://<db_user>:<db_pwd>@127.0.0.1:' + local_port +'/<db_name>')

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

    print 'Database session created'

    #test data retrieval
    test = session.execute("SELECT * FROM <table_name>")

这是我看到的输出:

File "/Library/Python/2.7/site-packages/sshtunnel.py", line 299, in handle
raise HandlerSSHTunnelForwarderError(msg)
HandlerSSHTunnelForwarderError: In #1 <-- ('127.0.0.1', 54265) to ('10.160.1.24', 5432) failed: ChannelException(2, 'Connect failed')

知道我做错了什么吗?我可以通过在单独的终端中运行命令ssh -L 3334:localhost:5432 Administrator@10.160.1.24然后连接到localhost:3334上的db来连接到postgresdb。

1 个答案:

答案 0 :(得分:0)

发现我的错误!

remote_bind_address=('10.160.1.24', 5432)应为remote_bind_address=('127.0.0.1', 5432),