首页 > 解决方案 > Python + Paramiko + 错误:sudo:没有 tty,也没有指定 askpass 程序

问题描述

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

问题:'sudo: no tty present and no askpass program specified' 当代码如下:

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:

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

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

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

标签: pythonlinuxsudoparamiko

解决方案


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

我使用了 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

欢迎提出建议和指正。


推荐阅读