Python Connect over HTTP proxy with pysftp

后端 未结 3 1896
太阳男子
太阳男子 2020-12-18 07:12

Currently, I am doing SFTP transfer using Python subprocess.POPEN and PuTTY psftp.exe.

It is working, but not really clean nor transportabl

3条回答
  •  攒了一身酷
    2020-12-18 07:34

    try this:

    import paramiko
    
    use_proxy = True
    
    # PROXY
    host_proxy = ''
    port_proxy = ''
    
    # SFTP
    host = ''
    port = 22
    username = ''
    password = ''
    
    try:
        client = paramiko.SSHClient()
        client.load_system_host_keys()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        
        if host_proxy and use_proxy:
        # find the path to nc on the command line: "which nc"
            proxy = paramiko.ProxyCommand(f"/bin/nc --proxy {host_proxy}:{port_proxy} {host} {port}") 
            trans = paramiko.Transport(proxy)
        else:
            trans = paramiko.Transport((host, port))
        trans.connect(username=username, password=password)
        sftp = paramiko.SFTPClient.from_transport(trans)
    except Exception as e:
        print(e)
    
    
    sftp.listdir('.')
    
    sftp.close()
    trans.close()
    

    Remember to install ncat if you run in docker, in debian. Not install netcat, it's the older version and does not work well.

    apt-get -y update && apt-get -y install ncat
    

提交回复
热议问题