在Python中尝试使用sshtunnel

2024-06-17 07:49:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个shell脚本,我想用python脚本替换它。脚本正在初始化SSH隧道以公开TCP流。。。 我想用python做同样的事情,但是我总是有一个错误。你知道吗

shell中的命令行如下所示:

ssh -l monlogin -i /home/toto/.ssh/test/id_dsa -L 10205:127.0.0.1:10205  IP

在这个命令之后,我可以在10205上执行telnet并查看数据流。你知道吗

在python中:

import time
from sshtunnel import open_tunnel
import socket

if __name__ == '__main__':

    with open_tunnel(
    ('IP', 22),
    ssh_username="monlogin",
    ssh_pkey='/home/toto/.ssh/test/id_dsa',
    ssh_private_key_password=None,
    remote_bind_address=('127.0.0.1', 10205),
    local_bind_address=('127.0.0.1', 10205),
    debug_level=10,
    #threaded=False,
    ) as server:
        time.sleep(10)
        print(server.local_bind_port)
        while True:
            # # Create a TCP/IP socket
            # sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            # # Connect the socket to the port where the server is listening
            # server_address = ('127.0.0.1', 10205)
            # sock.connect(server_address)
            # #sock.settimeout(0)
            # while True:
            #     data = sock.recv(4096).decode('ascii')
            #     if data:
            #         print(data)
            #     time.sleep(0.01)
            time.sleep(1)

    print('FINISH!')

我可以执行它,它将打印local_bind_port,但是,当我执行“telnet localhost 10205”时,我有以下错误:

2019-10-07 09:55:16,906| WAR | MainThrea/0966@sshtunnel | Could not read SSH configuration file: ~/.ssh/config
2019-10-07 09:55:16,907| INF | MainThrea/0992@sshtunnel | 0 keys loaded from agent
2019-10-07 09:55:16,907| INF | MainThrea/1041@sshtunnel | 0 keys loaded from host directory
2019-10-07 09:55:16,912| DEB | MainThrea/1239@sshtunnel | Private key file (/home/toto/.ssh/test/id_dsa) could not be loaded as type <class 'paramiko.rsakey.RSAKey'> or bad password
2019-10-07 09:55:16,914| DEB | MainThrea/1228@sshtunnel | Private key file (/home/toto/.ssh/test/id_dsa, <class 'paramiko.dsskey.DSSKey'>) successfully loaded
2019-10-07 09:55:16,914| INF | MainThrea/0913@sshtunnel | Connecting to gateway: IP:22 as user 'monlogin'
2019-10-07 09:55:16,915| DEB | MainThrea/0916@sshtunnel | Concurrent connections allowed: True
2019-10-07 09:55:16,915| DEB | MainThrea/1354@sshtunnel | Trying to log in with key: b'...................'
2019-10-07 09:55:18,480| INF | Srv-10205/1388@sshtunnel | Opening tunnel: 127.0.0.1:10205 <> 127.0.0.1:10205
10205
2019-10-07 09:55:31,698| ERR |  Thread-1/1819@transport | Secsh channel 0 open FAILED: Connection refused: Connect failed
2019-10-07 09:55:31,699| ERR |  Thread-3/0385@sshtunnel | Could not establish connection from ('127.0.0.1', 10205) to remote side of the tunnel

我无法访问远程服务器。但有点不对劲。你知道吗?你知道吗


Tags: keyfromtestipidhomeservertime