Home > Article > Backend Development > 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>
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>
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>
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!