Using Paramiko for SSH Connections, Command Execution, and File Operations in Python
This guide demonstrates how to use the Python Paramiko library to establish SSH connections to remote servers via password or key authentication, execute commands, and perform file operations such as uploading, downloading, creating, editing, and deleting files, with example code snippets and security tips.
Connecting to a remote server is typically done via the SSH (Secure Shell) protocol, and the Python library paramiko provides a convenient way to perform secure remote command execution and file transfer.
Password authentication example:
import paramiko
# Create an SSH client object
ssh = paramiko.SSHClient()
# Automatically add unknown host keys
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# Connect to the remote server
ssh.connect(hostname='your_server_ip', port=22, username='username', password='password')
# Execute a remote command
stdin, stdout, stderr = ssh.exec_command('ls -l')
stdout_result = stdout.read().decode()
stderr_result = stderr.read().decode() if stderr.channel.recv_exit_status() != 0 else ""
print(f"Standard output: {stdout_result}")
print(f"Error output: {stderr_result}")
# Close the connection
ssh.close()Public‑key (private‑key) authentication example:
# Load a local private key file
private_key = paramiko.RSAKey.from_private_key_file('/path/to/your/private_key.pem')
# Connect using the private key
ssh.connect(hostname='your_server_ip', port=22, username='username', pkey=private_key)
# Subsequent operations are the same as aboveFile operation example (create, upload, download, edit, delete):
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname='your_server_ip', port=22, username='username', password='password')
# Create a new file on the remote server
ssh.exec_command("touch /path/to/newfile.txt")
# Upload a local file to the remote server
sftp = ssh.open_sftp()
local_file_path = '/path/to/localfile.txt'
remote_file_path = '/path/to/remotefile.txt'
sftp.put(local_file_path, remote_file_path)
# Download the file back
sftp.get(remote_file_path, local_file_path)
# Edit the remote file (example: write a line)
ssh.exec_command('echo "Hello World" > /path/to/remotefile.txt')
# Delete the remote file
ssh.exec_command("rm /path/to/remotefile.txt")
# Close SFTP and SSH connections
sftp.close()
ssh.close()Replace placeholder values such as server IP, usernames, passwords, and file paths with actual data; consider storing sensitive credentials in environment variables or secure vaults, and prefer key‑based authentication for better security.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.