How to perform different commands over ssh with Python?



When we want to remotely access and execute commands on another machine then we use the paramiko library in Python.

Paramiko is a third-party library that is used to connect and communicate securely with remote machines using the SSH, i.e., 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 in our local system using the below command -

pip install paramiko

Example

Following is the example, in which we connect to a remote server via SSH and perform multiple shell commands such as listing files, checking the current user, and displaying the present working directory -

import paramiko

# Replace these with your actual server details
hostname = '127.0.0.1'      # 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']

   for command in commands:
      print(f"\nRunning command: {command}")
      stdin, stdout, stderr = client.exec_command(command)
      print("Output:\n", stdout.read().decode())
      error = stderr.read().decode()
      if error:
         print("Error:\n", error)

except Exception as e:
   print(f"Connection failed: {e}")

finally:
   # Always close the connection
   client.close()

Here is a sample output of the above program -

Output of 'whoami':
Niharikaa

Output of 'pwd':
/home/your_username

Output of 'ls -l':
total 4
-rw-r--r-- 1 user user  56 Jun 12  server.log
drwxr-xr-x 2 user user 4096 Jun 10  scripts

Note:

  • Make sure the SSH server is running and reachable.
  • Use a key-based authentication method for better security in production environments.
  • Paramiko also supports executing commands using private keys instead of passwords.
Updated on: 2025-06-20T19:15:44+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements