Learning Python Network Programming

(Sean Pound) #1

Programming with Sockets


TCP port forwarding


One of the interesting experiments we can do with TCP socket programming is to set
up a TCP port forwarding. This has very good use cases. Say, for example, if you are
running an insecure program like FTP in a public server that doesn't have any SSL
capability to do secure communication (FTP passwords can be seen clear-text over
the wires). Since this server is accessible from Internet, you must not login with your
password to the server without ensuring that the passwords are encrypted. One way
of doing this is to use Secure FTP or SFTP. We can use a simple SSH tunnel in order
to show how this approach works. So, any communication between your local FTP
client and remote FTP server will happen via this encrypted channel.


Let us run the FTP program to the same SSH server host. But create an SSH tunnel
from your local machine that will give you a local port number and will directly
connect you to the remote FTP server daemon.


Python has a third party sshtunnel module that is a wrapper around the Paramiko's
SSH library. The following is a code snippet of TCP port forwarding that shows how
the concept can be realized:


import sshtunnel
from getpass import getpass

ssh_host = '192.168.56.101'
ssh_port = 22
ssh_user = 'YOUR_SSH_USERNAME'

REMOTE_HOST = '192.168.56.101'
REMOTE_PORT = 21

from sshtunnel import SSHTunnelForwarder
ssh_password = getpass('Enter YOUR_SSH_PASSWORD: ')

server = SSHTunnelForwarder(
ssh_address=(ssh_host, ssh_port),
ssh_username=ssh_user,
ssh_password=ssh_password,
Free download pdf