Multiple Commands With SSH Using Python Subprocess [Solved]

To execute multiple SSH commands using Python’s subprocess module, you can use the subprocess.run() function with the ssh command to connect to a remote server and run commands on it.

Here’s an example of how you can do this:

Step 1: Import the subprocess module.

import subprocessCode language: Python (python)

Step 2: Define the SSH command to connect to the remote server.

Replace "user@remote_server_ip" with your SSH username and the remote server’s IP or hostname.

ssh_command = "ssh user@remote_server_ip"
Code language: Python (python)

Step 3: Create a list of commands you want to execute on the remote server.

remote_commands = [
    "echo 'Hello, World'",
    "ls -l",
    "uptime"
]Code language: Python (python)

Step 4: Join the remote commands into a single string, separated by semicolons.

remote_commands_str = ";".join(remote_commands)Code language: Python (python)

Step 5: Combine the SSH command and the remote commands.

full_command = f"{ssh_command} '{remote_commands_str}'"
Code language: Python (python)

Step 6: Execute the combined command using subprocess.run().

result = subprocess.run(full_command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
Code language: Python (python)

Step 7: Check the result and print the output.

if result.returncode == 0:
    print("Command executed successfully.")
    print("Output:")
    print(result.stdout)
else:
    print("Error executing the command:")
    print(result.stderr)
Code language: Python (python)

That’s it! This code will allow you to connect to a remote server via SSH and run the specified commands sequentially. Make sure to replace "user@remote_server_ip" with your actual SSH username and server details.

Combined code;

import subprocess

# Define the SSH command to connect to the remote server
ssh_command = "ssh user@remote_server_ip"

# List of commands you want to execute on the remote server
remote_commands = [
    "echo 'Hello, World'",
    "ls -l",
    "uptime"
]

# Join the remote commands into a single string
remote_commands_str = ";".join(remote_commands)

# Combine the SSH command and the remote commands
full_command = f"{ssh_command} '{remote_commands_str}'"

# Execute the combined command
result = subprocess.run(full_command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

# Check the result
if result.returncode == 0:
    print("Command executed successfully.")
    print("Output:")
    print(result.stdout)
else:
    print("Error executing the command:")
    print(result.stderr)
Code language: Python (python)

Make sure you have SSH access to the remote server, and you may need to set up SSH keys for passwordless authentication if required.

Also, keep in mind that this approach is suitable for executing a series of commands sequentially on the remote server. If you need more advanced interaction or handling of complex scenarios, you might want to consider using a library like paramiko for SSH connections, which provides more fine-grained control over SSH sessions and command execution.

Read More;

  • Aniket Singh

    Aniket Singh holds a B.Tech in Computer Science & Engineering from Oriental University. He is a skilled programmer with a strong coding background, having hands-on experience in developing advanced projects, particularly in Python and the Django framework. Aniket has worked on various real-world industry projects and has a solid command of Python, Django, REST API, PostgreSQL, as well as proficiency in C and C++. He is eager to collaborate with experienced professionals to further enhance his skills.

    View all posts

Leave a Comment