Setup a Static IP for Python SFTP using Paramiko & SOCKS

Learn how to route Python SFTP file transfers through a QuotaGuard Static IP using Paramiko and a SOCKS proxy.

Prerequisites

pip install paramiko PySocks

Instructions

Run example
QUOTAGUARDSTATIC_URL=... python app.py

Be sure to set QUOTAGUARDSTATIC_URL to your proxy URL from the QuotaGuard Dashboard. Either the HTTP or the SOCKS URL will work because the program will convert to the right port number.

Test in Docker
docker build -t qg-static-python-sftp-paramiko-example .
docker run -e QUOTAGUARDSTATIC_URL=... qg-static-python-sftp-paramiko-example

Code Samples

app.py
#/usr/bin/env python
import os
import paramiko
import socks

from urllib.parse import urlparse

if __name__ == '__main__':
    proxy = urlparse(os.environ['QUOTAGUARDSTATIC_URL'])
    sock=socks.socksocket()
    sock.set_proxy(
        proxy_type=socks.SOCKS5,
        addr=proxy.hostname,
        port=1080,
        username=proxy.username,
        password=proxy.password,
    )
    sock.connect(('test.rebex.net', 22))

    tport = paramiko.Transport(sock)
    tport.connect(username='demo',password='password')

    sftp = paramiko.SFTPClient.from_transport(tport)

    sftp.get('readme.txt','readme.txt')

    sftp.close()
    tport.close()

    #print the contents of the file downloaded
    f = open('readme.txt', 'r')
    file_contents = f.read()
    print(file_contents)
    f.close()

Docker File
FROM python:latest

#install paramiko
RUN pip install -U pip && \
    pip install paramiko PySocks

WORKDIR /app

COPY app.py app.py

ENTRYPOINT [ "python", "app.py" ]