Intro to Python SSH Client Paramiko

Lehlogonolo Masubelele
3 min readMar 25, 2022

--

Photo by David Clode on Unsplash

What is Pramiko?

Paramiko is a one of many python modules that implements the SSHv2 protocol. With paramiko you can perform various remote tasks like running commands on remote server, copying files to and from a remote server to your local machine just to mention a few. To get a full list of all the functions read more on the SFTP client object.

Prerequisites

Fork & clone the code to your local machine.

Let’s have look at our code:

docker-compose.yml

This container will be running an sshd server where we will be testing our pyhton script against.

---
version: "3"
services:
openssh-server:
image: lscr.io/linuxserver/openssh-server
container_name: lab
environment:
- PUID=1000
- PGID=1000
- TZ=Africa/Johannesburg
- USER_PASSWORD=passw0rd
- USER_NAME=codesenju
- PASSWORD_ACCESS=true
- HOSTNAME=lab
ports:
- 2222:2222
restart: unless-stopped

main.py:

First we import the paramiko module on the first line. Secondly define our constant variables: hostname, username, paswword, PORT and ssh Client Object.

import paramikohostname = 'localhost'
username = 'codesenju'
password = 'passw0rd'
PORT = '2222'
ssh = paramiko.SSHClient()

execRemoteCommand(cmd_, client) Function:

We define a function that will take in the command and ssh client object as parameters. This function uses the exec_command() method which will execute a command on the remote SSH server. The command’s output streams are returned representing stdout, and stderr.

def execRemoteCommand(cmd_, client):
print(cmd_)
stdin, stdout, stderr = client.exec_command(cmd_)
output = stderr.readlines()
output_line = ''.join(output)
print(output_line)
output = stdout.readlines()
output_line = ''.join(output)
print(output_line)

Open connection:

Here we will try to open a remote session with the lab container. Our sftp_client & ssh_client objects will be used to perform remote tasks.

if __name__ == "__main__":try:
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname=hostname, username=username, password=password, port=PORT)
sftp_client = ssh_client.open_sftp()

reference: https://docs.paramiko.org/en/stable/api/client.html

Change path of SFTP session:

chdir() method will change the “current directory” of this SFTP session. Once you use this method to set a working directory, all operations on this SFTPClient object will be relative to that path. Next the getcwd() method will return the “current working directory” of the SFTP session on the remote server.

        # 1. CHANGE PATH ON THE REMOTE SERVER
print("##########-1.-CHANGE-PATH-##########")
sftp_client.chdir("/tmp")
print(sftp_client.getcwd())

Run command remotely:

This will call the executeRemoteCommand() we created earlier.

        # 2. RUN COMMAND ON REMOTE SERVER
print("##########-2.-REMOTE-COMMAND-##########")
execRemoteCommand("ls -l /tmp", ssh_client)

Copy file to remote host:

put(local file, remote file) method copies a local file to the SFTP server as remote file.

        # 3. COPY FILE TO REMOTE SERVER
print("##########-3.-REMOTE-COMMAND-##########")
sftp_client.put("README.md", "README.md")
execRemoteCommand("stat /tmp/README.md", ssh_client)

Download file from remote host to local machine:

get(remote file, local file) copies remote file from the SFTP server to the local host.

         # 4. DOWNLOAD FILE FROM REMOTE SERVER
print("##########-4.-DOWNLOAD-FILE-##########")
sftp_client.get("/tmp/remote_file.txt","remote_file.txt")

Handling errors and close sftp, ssh client objects:

except Exception as err:
print("SSH CLIENT ERROR: {}".format(err))
finally:
sftp_client.close()
ssh_client.close()

Our main.py script will look like this:

Tutorial

In this example we will be using paramiko to perform 4 tasks:

  1. Change paths on remote server and return the current path.
  2. Run any shell commands on a remote server.
  3. Copy a file to remote server.
  4. Download a file from a remote server to our local machine.

a) Let’s start our remote server container called lab.

docker-compose up -d

Let’s create a file on the remote server that we will be using later:

docker exec -ti lab bash -c 'echo "Hello from $HOSTNAME | $TZ" > /tmp/remote_file.txt'

check if the file is there:

docker exec -ti lab bash -c 'stat  /tmp/remote_file.txt'

b) Run the script

Before running the script we need to make sure we have the python paramiko module installed:

pip3 install paramiko

Execute script:

python3 main.py

Video:

References

--

--