In the world of automation, running commands remotely can enhance the efficiency and versatility of your scripts. Python offers a powerful way to accomplish this using the paramiko module.
To illustrate its usage, let's suppose you want to run a command on a remote server named "remotehost," where you have a known password. Manually, this can be done with:
<code class="bash">ssh user@remotehost</code>
In Python, using paramiko, you can automate this process:
<code class="python">import paramiko # Initialize SSH client ssh = paramiko.SSHClient() ssh.connect("remotehost", username="user", password="password") # Execute remote command ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command("your_remote_command")</code>
The exec_command method returns three file-like objects: stdin for sending data to the remote command, stdout for capturing standard output, and stderr for capturing standard error.
If you're using SSH keys instead of passwords, the code can be modified as follows:
<code class="python">import paramiko # Load private key k = paramiko.RSAKey.from_private_key_file("keyfilename.pem") # Set missing host key policy ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # Connect using SSH key ssh.connect("remotehost", username="user", pkey=k) # Execute remote command ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command("your_remote_command")</code>
With paramiko, you gain the flexibility to execute remote commands in Python scripts, allowing you to automate a wide range of tasks from the comfort of your local machine.
The above is the detailed content of How to Automate Remote Commands with Python Using SSH?. For more information, please follow other related articles on the PHP Chinese website!