Python建立SSH连接后,如何执行远程Bash命令?
Hey there! Let's fix your issue with running remote commands via SSH in Python. The problem with your current code is that each os.system() call runs as a separate local process—so when you run ssh -X ubuntu@192.168.0.2, it starts an interactive SSH session, but the next os.system('cd Desktop') runs locally on your machine, not the remote one. They don't share the same shell session at all.
Here are a few solid ways to execute remote Bash commands properly:
1. Pass Remote Commands Directly in the SSH Call
You can bundle the remote commands you want to run right into the ssh command itself. Use quotes to wrap the commands, and && to chain them so they run in the same remote shell:
import os def livestream(): # Chain commands with && to run them in the same remote shell os.system('ssh -X ubuntu@192.168.0.2 "cd Desktop && ./your_target_program"')
This works because the entire quoted string is executed as a single command on the remote machine. The cd Desktop changes the working directory, then ./your_target_program runs your desired app.
2. Use subprocess (Recommended Over os.system)
The subprocess module is more flexible than os.system—it lets you capture output, handle errors, and avoid shell injection risks more easily. Here's how to use it:
import subprocess def livestream(): # Define the remote command chain remote_cmd = "cd Desktop && ./your_target_program" # Build the SSH command list (avoids shell escaping issues) ssh_cmd = ["ssh", "-X", "ubuntu@192.168.0.2", remote_cmd] # Run the command and capture output result = subprocess.run(ssh_cmd, capture_output=True, text=True) # Check results if result.returncode == 0: print("Command ran successfully! Output:\n", result.stdout) else: print("Command failed. Error:\n", result.stderr)
3. Use a Dedicated SSH Library (For Complex Workflows)
If you need to run multiple commands, transfer files, or maintain a persistent SSH session, use a library like paramiko (you'll need to install it first with pip install paramiko):
import paramiko def livestream(): ssh_client = paramiko.SSHClient() # Auto-add the remote host key (for testing; in production, use known_hosts) ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: # Connect to the remote machine ssh_client.connect(hostname="192.168.0.2", username="ubuntu") # Execute the remote command stdin, stdout, stderr = ssh_client.exec_command("cd Desktop && ./your_target_program") # Read output and errors output = stdout.read().decode("utf-8") error = stderr.read().decode("utf-8") print("Remote Output:\n", output) if error: print("Remote Errors:\n", error) finally: # Always close the connection ssh_client.close()
Each method has its use case:
- Use the first approach for quick, simple one-liners.
- Use
subprocesswhen you need better control over input/output. - Use
paramikofor advanced SSH tasks like multiple commands or file transfers.
内容的提问来源于stack exchange,提问作者user7441

