Home > Backend Development > Python Tutorial > How Can I Execute Commands Remotely Over SSH Using Python?

How Can I Execute Commands Remotely Over SSH Using Python?

Susan Sarandon
Release: 2024-11-04 18:10:02
Original
563 people have browsed it

How Can I Execute Commands Remotely Over SSH Using Python?

Performing Commands Over SSH with Python

Automating command execution on remote machines is a common task in system administration. Python's subprocess module can handle local commands, but what if you need to execute commands on a remote host over SSH?

To overcome this challenge, consider using the Paramiko library. Paramiko provides a comprehensive set of tools for SSH communication. Let's explore how to use Paramiko to perform remote command execution.

Using Paramiko for Remote Command Execution

<code class="python">import paramiko

# Connect to the remote host with username, password, and hostname
ssh = paramiko.SSHClient()
ssh.connect(hostname, username, password)

# Execute a command using exec_command
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(command)

# Handle output and error output
print(ssh_stdout.read().decode())
print(ssh_stderr.read().decode())

# Close the connection
ssh.close()</code>
Copy after login

Using SSH Keys for Authentication

If you prefer to use SSH keys for authentication, you can do so by setting the key using paramiko.RSAKey.from_private_key_file().

<code class="python">k = paramiko.RSAKey.from_private_key_file(keyfilename)

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname, username, pkey=k)</code>
Copy after login

Example Usage

For instance, you can execute and capture the output of a remote command with the following code:

<code class="python">ssh = paramiko.SSHClient()
ssh.connect("remote_host", "username", "password")
stdin, stdout, stderr = ssh.exec_command("df -h")
output = stdout.read().decode()
ssh.close()

print(output)</code>
Copy after login

By leveraging the power of Paramiko, you can effortlessly execute commands, retrieve output, and handle errors on remote machines from the comfort of your Python scripts.

The above is the detailed content of How Can I Execute Commands Remotely Over SSH Using Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template