如何使用Python设置与ssh命令匹配的隧道(用于堡垒)?

时间:2018-10-02 17:29:31

标签: python ssh

我如何使用可以代替此命令的Python代码设置隧道?

  

ssh -N -L 3307:xxxxxx.rds.amazonaws.com:3306 ec2-user@XX.XXX.XX.XX -i   〜/ .ssh / bastion_key.pem

1 个答案:

答案 0 :(得分:1)

您可以使用sshtunnel库。

例如:

from sshtunnel import SSHTunnelForwarder

with SSHTunnelForwarder(
    ('XX.XXX.XX.XX', 22),
    ssh_username='ec2-user',
    ssh_pkey='~/.ssh/bastion_key.pem',
    remote_bind_address=('xxxxxx.rds.amazonaws.com', 3306),
    local_bind_address=('0.0.0.0', 3307)
) as tunnel:
    # do stuff with tunnel