Once connected, the most common task is executing shell commands on the remote server. The exec_command() method is used for this. It returns three file-like objects: stdin, stdout, and stderr, which correspond to the standard input, output, and error streams of the command you executed.
This script connects to a server, executes the ls -l command, and prints the standard output and any potential errors.
import paramiko
import getpass
# --- Connection Details (replace with yours) ---
hostname = 'your_server_ip_or_hostname'
username = 'your_username'
password = getpass.getpass()
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(hostname=hostname, username=username, password=password)
# --- Execute a Command ---
command = 'ls -l /home'
print(f"\nExecuting command: '{command}'")
stdin, stdout, stderr = client.exec_command(command)
# Read and print the output
output = stdout.read().decode('utf-8')
print("\n--- Command Output (stdout) ---")
if output:
print(output)
else:
print("No output.")
# Read and print any errors
error = stderr.read().decode('utf-8')
print("\n--- Command Error (stderr) ---")
if error:
print(error)
else:
print("No errors.")
# Get the exit status of the command
exit_status = stdout.channel.recv_exit_status()
print(f"\nExit Status: {exit_status}")
except Exception as e:
print(f"❌ An error occurred: {e}")
finally:
client.close()Write a script that executes two commands:
uname -ato get the system's kernel information and print it.- A deliberately incorrect command, like
list_files, to see howstderrcaptures the "command not found" error. Print the error message.