Saturday, January 3, 2015

Python socksipy: SFTP with Paramiko via SOCKS proxy

I use Paramiko library to access SFTP servers in Python. Paramiko is easy to use, provides programmer with rich functionality, but it does not support proxy servers out of the box. There is a small library socksipy that can be easily integrated with Paramiko.



Setting up a connection with Paramiko


The following source code sets up connection to remote SFTP server:
import paramiko

try:
  ssh = paramiko.SSHClient()
  logger.debug('Attempting SFTP connection')
  ssh.connect(hostname='sftp.example.com')
  sftp = ssh.open_sftp()
  logger.debug('Connected to SFTP')
except Exception as e:
  logger.error('Connection failed: %s', str(e))
  sys.exit('Could not connect') 

Configuring SOCKS proxy


Socksipy can be downloaded from http://socksipy.sourceforge.net

The following is the socksipy proxy object configuration:
import socks

socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, 'socks.example.com')

Syntax: setdefaultproxy(proxytype, addr[, port[, rdns[, username[, password]]]])


Setup Paramiko to communicate via SOCKS proxy


We should replace paramiko socket with socksipy object:
import paramiko
import socks
            
logger.debug('Using SOCKS proxy')
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, 'socks.example.com')
paramiko.client.socket.socket = socks.socksocket

try:
  ssh = paramiko.SSHClient()
  logger.debug('Attempting SFTP connection')
  ssh.connect(hostname='sftp.example.com')
  sftp = ssh.open_sftp()
  logger.debug('Connected to SFTP')
except Exception as e:
  logger.error('Connection failed: %s', str(e))
  sys.exit('Could not connect')


More info about socksipy can be found here: http://socksipy.sourceforge.net/readme.txt


No comments:

Post a Comment