-1

我需要一个脚本来使用 python 和 paramiko 远程执行某些操作。我使用在远程机器上执行了 sudo 操作

'回声'+密码+' | sudo -S '+'cmd_to_be_executed'

通过在 paramiko 中将标志 get_pty 设置为 true 解决了 tty 问题。现在有一台远程机器没有该用户的 sudo 权限,切换到 root 的唯一方法是使用 su 命令。所以我尝试了

'回声'+密码+' | su -c '+'cmd_to_be_executed'

但它会引发 tty 问题。现在即使我在 paramiko 中将 pty 标志设置为 true,也会出现同样的问题

标准输入必须是 tty

有没有办法解决这个问题?任何帮助都非常感谢谢谢!!!

4

1 回答 1

0

是的。您可以使用 Python 命令脚本来实现这一点。

使用argparse接受命令行参数,这将是您的密码。

使用subprocess.run调用您的脚本。您可能需要将 shell=True 与子进程一起使用。(或使用Pexpect而不是子进程)。

尝试这样的事情:

import subprocess, argparse

#Set up the command line arguments

parser = argparse.ArgumentParser(description='Provide root password.')
parser.add_argument('--password', help='password help')

# Collect the arguments from the command line
args = parser.parse_args()

# Open a pipe to the command you want to run
p = subprocess.Popen(['su', '-c', !!your command here!!],stdout=subprocess.PIPE,stdin=subprocess.PIPE)

# Prepare the password and write it
pwd = args.password + '\n'
p.stdin.write(pwd)
p.communicate()[0]
p.stdin.close()
于 2017-06-02T19:35:18.933 回答