You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python建立SSH连接后,如何执行远程Bash命令?

How to Run Remote Bash Commands Over SSH in Python

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.

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 subprocess when you need better control over input/output.
  • Use paramiko for advanced SSH tasks like multiple commands or file transfers.

内容的提问来源于stack exchange,提问作者user7441

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:41:57