Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to perform different commands over ssh with Python?
When we want to remotely access and execute commands on another machine, we use the paramiko library in Python. Paramiko is a third-party library that enables secure communication with remote machines using the SSH (Secure Shell) protocol.
It allows us to execute commands, transfer files, and perform other remote tasks programmatically. To use the Paramiko library, first we need to install it ?
pip install paramiko
Basic SSH Connection and Command Execution
Here's how to connect to a remote server via SSH and execute multiple shell commands ?
import paramiko
# Replace these with your actual server details
hostname = '192.168.1.100' # Use IP address or domain name
port = 22
username = 'your_username' # Replace with actual username
password = 'your_password' # Replace with actual password
# Create an SSH client instance
client = paramiko.SSHClient()
# Automatically add host keys from the server (for first-time connection)
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
# Connect to the SSH server
client.connect(hostname=hostname, port=port, username=username, password=password)
# Run basic commands
commands = ['whoami', 'pwd', 'ls -la']
for command in commands:
print(f"\nRunning command: {command}")
stdin, stdout, stderr = client.exec_command(command)
# Read output and errors
output = stdout.read().decode().strip()
error = stderr.read().decode().strip()
if output:
print("Output:", output)
if error:
print("Error:", error)
except Exception as e:
print(f"Connection failed: {e}")
finally:
# Always close the connection
client.close()
The output of the above code is ?
Running command: whoami Output: ubuntu Running command: pwd Output: /home/ubuntu Running command: ls -la Output: total 24 drwxr-xr-x 3 ubuntu ubuntu 4096 Dec 15 10:30 . drwxr-xr-x 3 root root 4096 Dec 10 09:15 .. -rw-r--r-- 1 ubuntu ubuntu 220 Dec 10 09:15 .bash_logout -rw-r--r-- 1 ubuntu ubuntu 3771 Dec 10 09:15 .bashrc drwxr-xr-x 2 ubuntu ubuntu 4096 Dec 15 10:30 scripts
Using SSH Key Authentication
For better security, use SSH key authentication instead of passwords ?
import paramiko
hostname = '192.168.1.100'
username = 'your_username'
private_key_path = '/path/to/your/private_key'
# Create SSH client
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
# Load private key
private_key = paramiko.RSAKey.from_private_key_file(private_key_path)
# Connect using key authentication
client.connect(hostname=hostname, username=username, pkey=private_key)
# Execute command
stdin, stdout, stderr = client.exec_command('uname -a')
print("System info:", stdout.read().decode().strip())
except Exception as e:
print(f"Connection failed: {e}")
finally:
client.close()
Running Multiple Commands Efficiently
You can execute multiple commands in a single session or chain commands together ?
import paramiko
def run_ssh_commands(hostname, username, password, commands):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(hostname=hostname, username=username, password=password)
# Execute chained commands
chained_command = " && ".join(commands)
stdin, stdout, stderr = client.exec_command(chained_command)
return stdout.read().decode(), stderr.read().decode()
except Exception as e:
return None, str(e)
finally:
client.close()
# Example usage
hostname = '192.168.1.100'
username = 'your_username'
password = 'your_password'
commands = ['cd /tmp', 'touch test_file.txt', 'ls -la test_file.txt']
output, error = run_ssh_commands(hostname, username, password, commands)
if output:
print("Command output:", output)
if error:
print("Error:", error)
Important Security Considerations
Best Practices:
- Always use SSH key authentication instead of passwords in production
- Verify host keys to prevent man-in-the-middle attacks
- Use
client.close()in a finally block to ensure connections are closed - Handle exceptions properly to avoid connection leaks
- Never hardcode credentials in your source code
Conclusion
Paramiko provides a secure way to execute remote commands via SSH in Python. Use key-based authentication for production environments and always handle connections and exceptions properly for robust remote operations.
