Sobes.tech
Senior

How to execute shell commands from Python code locally and remotely?

sobes.tech AI

Answer from AI

To execute shell commands from Python locally, you can use the subprocess module. For example:

import subprocess

# Execute command locally
result = subprocess.run(['ls', '-l'], capture_output=True, text=True)
print(result.stdout)

For remote command execution, SSH is usually used. You can apply the paramiko library:

import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname='remote_host', username='user', password='pass')
stdin, stdout, stderr = ssh.exec_command('ls -l')
print(stdout.read().decode())
ssh.close()

Thus, locally — via subprocess, remotely — via SSH libraries, such as paramiko.