Python 使su非交互式

Python 使su非交互式,python,linux,ssh,paramiko,server-administration,Python,Linux,Ssh,Paramiko,Server Administration,我需要一个脚本来使用python和paramiko远程执行某些操作。我在远程机器上使用 'echo'+password+'| sudo-S'+'cmd_to_be_executed' 通过在paramiko中将标志get_pty设置为true,解决了tty问题。现在有一台远程机器没有该用户的sudo权限,切换到root的唯一方法是使用su命令。所以我试过了 'echo'+password+'| su-c'+'cmd_to_be_executed' 但这也带来了一个棘手的问题。现在,即使我在par

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

'echo'+password+'| sudo-S'+'cmd_to_be_executed'

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

'echo'+password+'| su-c'+'cmd_to_be_executed'

但这也带来了一个棘手的问题。现在,即使我在paramiko中将pty flag设置为true,也会出现相同的问题

中的标准必须是tty


有什么办法解决这个问题吗?非常感谢您的帮助,谢谢

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

用于接受作为密码的命令行参数

用于调用脚本。您可能需要在子流程中使用shell=True。(或使用而不是子流程)

试着这样做:

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()

popen()
无法处理从tty读取密码的命令,如
ssh
/
su
。这就是为什么我们有
expect
/
pexpect
。同样的错误仍然存在,而且我应该首先使用ssh连接到远程机器是的,在ssh连接到远程机器上之后,您需要让python脚本在远程机器上运行(查看)