Paramiko error when trying to edit file: “sudo: no

2020-03-31 05:42发布

问题:

I am using Paramiko to SSH and edit a config file. The file itself needs sudo permissions to edit. This hasn't been a problem so far, as I've just done echo <sudopw> | sudo <command> for other sudo commands in my script.

When I try to edit this file using sed, though, nothing happens. stderr produces: sudo: no tty present and no askpass program specified

Here is my code:

stdin, stdout, stderr = client.exec_command
('echo <sudopassword> | sudo sed -i -e \"\\$aAllowUsers\" /etc/ssh/sshd_config)')

I have tried solutions using invoke_shell but nothing seems to be working. Any solution to edit this file would be helpful.

EDIT: This has been solved! Don't use get_pty. Use the -S option of sudo right after "sudo".

回答1:

If you read the error message

sudo: no tty present and no askpass program specified

then you can easily find the solution: add the -t option to your ssh command:

-t
Force pseudo-terminal allocation. This can be used to execute arbitrary screen-based programs on a remote machine, which can be very useful, e.g. when implementing menu services. Multiple -t options force tty allocation, even if ssh has no local tty.

This has been discussed before:

  • How to fix 'sudo: no tty present and no askpass program specified' error?
  • sudoers NOPASSWD: sudo: no tty present and no askpass program specified

Regarding Paramiko, there have been related questions, with a couple of different approaches:

  • use the get_pty method of the ssh Channel to obtain a pseudo-terminal (which is analogous to telling ssh to do this)
  • use the -S option of sudo, and send the password on your standard output.

For discussion, see the suggested answers here:

  • Paramiko and Pseudo-tty Allocation
  • Nested SSH session with Paramiko