2 min read

Python Paramiko Module

Paramiko is a Python implementation of the SSHv2 protocol, providing both client and server functionality. It allows you to connect to remote servers, execute commands, and transfer files via SFTP.

Installation

pip install paramiko

Importing the Module

import paramiko

SSH Client

To connect to a server and run commands, use the SSHClient.

Connecting

import paramiko

client = paramiko.SSHClient()

# Automatically add the server's host key (not recommended for production, but useful for testing)
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# Connect to the server
client.connect('hostname', username='user', password='password')

Executing Commands

exec_command() returns three file-like objects: standard input, standard output, and standard error.

stdin, stdout, stderr = client.exec_command('ls -l')

# Read the output
print(stdout.read().decode())

# Check for errors
err = stderr.read().decode()
if err:
    print(f"Error: {err}")

Closing Connection

client.close()

SFTP Client (File Transfer)

Paramiko supports SFTP (Secure File Transfer Protocol) for uploading and downloading files.

# Open an SFTP session from an existing SSH client
sftp = client.open_sftp()

# Upload a file
sftp.put('local_file.txt', '/remote/path/remote_file.txt')

# Download a file
sftp.get('/remote/path/remote_file.txt', 'local_file.txt')

sftp.close()

Key-Based Authentication

Instead of a password, you can use a private key file.

k = paramiko.RSAKey.from_private_key_file("/path/to/private_key.pem")
client.connect('hostname', username='user', pkey=k)

programming/python/python