使su非交互式

时间:2017-06-02 18:18:20

标签: python linux ssh paramiko server-administration

我需要一个脚本来使用python和paramiko远程执行某些操作。我使用

在远程机器上执行了sudo操作
  

'echo'+密码+'| sudo -S'+'cmd_to_be_executed'

通过在paramiko中将标志get_pty设置为true来解决

和tty问题。现在有一个远程机器没有该用户的sudo权限,切换到root的唯一方法是使用su命令。所以我试过

  

'echo'+密码+'| su -c'+'cmd_to_be_executed'

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

  

标准必须是tty

有什么方法可以解决这个问题吗?非常感谢任何帮助,谢谢!

1 个答案:

答案 0 :(得分: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()
相关问题