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

Python脚本自动输入root密码执行命令时触发ValueError问题求助

Python脚本自动输入root密码执行命令时触发ValueError问题求助

各位好,我最近尝试写一个Python脚本,想自动处理需要输入root密码的命令,比如切换root用户、切换根目录还有远程SSH登录。我写了下面这段代码:

import subprocess

commands = ['sudo -s', 'cd /', 'ssh user@host']

password = 'myRootPassword'

for command in commands:
    process = subprocess.Popen(command.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
    # Check if the command prompts for a password
    output, error = process.communicate()
    if 'password' in output.decode('utf-8').lower():
        # Send the password to the process
        process.stdin.write(password.encode('utf-8'))
        process.stdin.write(b'\n')
        process.stdin.flush()
        # Execute the command
        output, error = process.communicate()
        print(output.decode('utf-8'))
        print(error.decode('utf-8'))

但是运行的时候,在执行process.stdin.write(password.encode('utf-8'))、process.stdin.write(b'\n')和process.stdin.flush()这几行代码时,触发了ValueError。我实在搞不清问题出在哪,有没有大佬能帮忙看看怎么解决这个问题?

备注:内容来源于stack exchange,提问作者Dannn

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.23 09:12:44