Search code examples
pythonlinuxsudoparamiko

Python + Paramiko + Error: sudo: no tty present and no askpass program specified


I have verified the existing thread but unable to get the exact reason and resolution of this problem.

PROBLEM: 'sudo: no tty present and no askpass program specified' When code is as follows:

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

Below are the possible solutions that I have applied but still no progress.

  1. Sol: Append the Password to command. 'sudo: no tty present and no askpass program specified. bash: line 1: : command not found'

  2. Sol2: stdin, stdout, stderr = client.exec_command(command, get_pty=True) More than 30 seconds still no idea whether control passed from exec_command(...).

  3. Sol3: self.client.get_pty() Unable to setup the connection.

  4. Sol4:

    stdin, stdout, stderr = self.client.exec_command('sudo -S ls') stdin.write('\n') stdin.flush() time.sleep(2)

Unable to do the same for sudo command 'stdin, stdout, stderr = self.client.exec_command('sudo -S info')' cause the same PROBLEM.

Can someone please point me if there is any solution to handle Sudo commands or workarounds?


Solution

  • I am able to get the solution for this problem.

    I have used send(..) instead of execute_command(...).

    SETUP:

    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)
    

    EXECUTION:

    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
    

    Suggestions and corrections are welcomed.