【问题标题】:Python + Paramiko + Error: sudo: no tty present and no askpass program specified [duplicate]Python + Paramiko +错误:sudo:不存在tty并且没有指定askpass程序[重复]
【发布时间】:2023-09-28 22:06:02
【问题描述】:

我已经验证了现有的线程,但无法得到这个问题的确切原因和解决方案。

问题:'sudo:不存在 tty,也没有指定 askpass 程序' 当代码如下:

str_command_to_exec += str(each_cmd).strip() + "\n"
# Now execute the command
stdin, stdout, stderr = self.client.exec_command('sudo -S ls')

以下是我已经应用但仍然没有进展的可能解决方案。

  1. Sol:将密码附加到命令。 'sudo: 没有 tty,也没有指定 askpass 程序。 bash:第 1 行::找不到命令'

  2. Sol2:stdin、stdout、stderr = client.exec_command(command, get_pty=True) 超过 30 秒仍然不知道控制是否从 exec_command(...) 传递过来。

  3. Sol3:self.client.get_pty() 无法设置连接。

  4. 溶胶4:

    stdin、stdout、stderr = self.client.exec_command('sudo -S ls') stdin.write('\n') 标准输入.flush() time.sleep(2)

无法对 sudo 命令 'stdin, stdout, stderr = self.client.exec_command('sudo -S info')' 执行相同操作会导致相同的问题。

如果有任何处理 Sudo 命令或变通方法的解决方案,有人可以指出我吗?

【问题讨论】:

    标签: python linux sudo paramiko


    【解决方案1】:

    我能够得到这个问题的解决方案。

    我使用了 send(..) 而不是 execute_command(...)。

    设置:

    self.client = paramiko.client.SSHClient()
    self.client.set_missing_host_key_policy(paramiko.client.AutoAddPolicy())
    self.client.connect(hostname=self.str_host_name, port=22,
                        username=self.str_user_name, password=self.str_user_pass)
    self.transport = paramiko.Transport(self.str_host_name, 22)
    self.transport.connect(username=self.str_user_name, password=self.str_user_pass)
    

    执行:

    if self.shell:
        self.shell.send(str_sudo_command + "\n")
    
        if self.shell is not None:
        time.sleep(2)
        self.str_sudo_command_result += str(self.shell.recv(1024).decode('utf-8'))
        self.str_sudo_command_result = str(self.str_sudo_command_result).strip()
        self.str_sudo_command_result = self.str_sudo_command_result.splitlines()
        if len(self.str_sudo_command_result) > 0:
            if "[sudo] password for " in self.str_sudo_command_result[-1]:
                self.str_sudo_command_result = ""
                self.shell.send(self.str_user_pass + "\n")
                time.sleep(2)
            else:
                while True:
                    result = str(self.str_sudo_command_result)
                    result = result.splitlines()
                    time.sleep(2)
                    if self.str_result_end_line not in result[-1]:
                        while self.shell.recv_ready():
                            self.str_sudo_command_result += str(self.shell.recv(9999).decode('utf-8'))
                else:
                    break
    

    欢迎提出建议和指正。

    【讨论】: