我需要一个脚本来使用 python 和 paramiko 远程执行某些操作。我使用
在远程计算机中执行 sudo 操作'echo '+password+' | sudo -S '+'cmd_to_be_executed'
通过在 paramiko 中将标志 get_pty 设置为 true 解决了 tty 问题。现在有一台远程计算机没有该用户的 sudo 权限,切换到 root 的唯一方法是使用 su 命令。所以我尝试了
'echo '+password+' | su -c '+'cmd_to_be_executed'
但它会引发 tty 问题。现在,即使我在 paramiko 中将 pty 标志设置为 true,也会出现相同的问题
standard in must be a tty
有什么办法可以解决这个问题吗?非常感谢任何帮助,谢谢!!!
最佳答案
是的。您可以使用 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()
关于python - 使 su 非交互式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44335183/