【问题标题】:Making su non-interactive使 su 非交互
【发布时间】:2017-06-02 18:18:20
【问题描述】:

我需要一个脚本来使用 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

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

【问题讨论】:

    标签: python linux ssh paramiko server-administration


    【解决方案1】:

    是的。您可以使用 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()
    

    【讨论】:

    • popen() 无法处理像ssh/su 这样从 tty 读取密码的命令。这就是为什么我们有expect/pexpect
    • 同样的错误仍然存​​在,而且我应该首先使用ssh连接到远程机器
    • 是的,你需要在远程机器上运行 python 脚本,然后你 ssh 到它(看看stackoverflow.com/questions/4180390/…
    猜你喜欢
    • 1970-01-01
    • 2012-11-11
    • 2010-11-26
    • 1970-01-01
    • 2013-04-16
    • 1970-01-01
    • 1970-01-01
    • 2021-09-23
    • 2011-12-21
    相关资源
    最近更新 更多