Search code examples
linuxbashshellsshsudo

Remove verbosity from sudo with pseudo-terminal


If I run the following script on some hosts:

ssh -t myhost /usr/bin/sudo /bin/bash <<'HERE_DOCUMENT'
whoami
uptime
exit
HERE_DOCUMENT

I get the following output:

Pseudo-terminal will not be allocated because stdin is not a terminal.
sudo: sorry, you must have a tty to run sudo

as sudo settings have requiretty enabled. I don't want to change that setting.

So my fix from existing StackOverflow answer is to add -tt option to ssh.

ssh -tt myhost /usr/bin/sudo /bin/bash <<'HERE_DOCUMENT'
whoami
uptime
exit
HERE_DOCUMENT

But that creates another problem, the output becomes too verbose:

[root@myhost ec2-user]# whoami
root
[root@myhost ec2-user]# uptime
 03:44:29 up 2 days,  3:26,  2 users,  load average: 0.00, 0.01, 0.05
[root@myhost ec2-user]# exit
exit
Connection to myhost closed.

What is the best way to remove prompts and command echoing?
The commands are just examples, and I do need sudo access to run privileged commands.


Solution

  • Don't start an interactive shell on the tty if you don't want an interactive shell session. Just start a shell that runs your command noninteractively:

    ssh -tt host "sudo bash -c '
      whoami
      uptime
      '"