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

如何通过parallel-ssh执行su命令切换至root用户并验证身份?

How to Execute su with parallel-ssh and Verify Root Identity

The issue you're hitting is that each call to run_command creates a separate, independent SSH session. When you run su in the first session, you switch to root only in that session—the second run_command('whoami') spins up a fresh session as your original myUser, hence the unexpected output.

Here are a few working solutions to fix this:

Solution 1: Use su -c to Run Commands Directly as Root

The cleanest way is to combine su with the command you want to execute using the -c flag. This runs the target command in the root context within a single SSH session:

from pssh.clients import ParallelSSHClient

hosts = ['myHost1', 'myHost2']
client = ParallelSSHClient(hosts, user='myUser', password='myPassword')

# Execute whoami directly as root via su -c
output = client.run_command('su root -c "whoami"')

# Send root password to the su prompt
for host in output:
    stdin = output[host].stdin
    stdin.write('rootPassword\n')
    stdin.flush()

client.join(output)

# Print results
for host, host_output in output.items():
    for line in host_output.stdout:
        print("Host [%s] - %s" % (host, line))

Solution 2: Chain Commands in a Single Session

If you need to run multiple commands after switching to root, chain them in one run_command call so they share the same session where su was executed:

from pssh.clients import ParallelSSHClient

hosts = ['myHost1', 'myHost2']
client = ParallelSSHClient(hosts, user='myUser', password='myPassword')

# Chain su and whoami in the same session
output = client.run_command('su && whoami')

for host in output:
    stdin = output[host].stdin
    stdin.write('rootPassword\n')
    stdin.flush()

client.join(output)

for host, host_output in output.items():
    for line in host_output.stdout:
        print("Host [%s] - %s" % (host, line))

Bonus: Consider Using sudo Instead

If your myUser has sudo privileges (a common setup), this is often more reliable for non-interactive use. For example:

  • If no password is required for sudo:
    output = client.run_command('sudo whoami')
    
  • If you need to provide the sudo password:
    output = client.run_command('echo "myUserPassword" | sudo -S whoami')
    

The key takeaway is that parallel-ssh doesn't persist session state between run_command calls—any context changes (like switching users) only apply to the session they're made in.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:57:59