4

I am trying to make the following script work for the ufw command which is expecting me to press y or n to confirm my command. In addition I want to pass my password to the sudo command (I know, bad idea).

echo 'y' | { echo 'my password'; } | sudo ufw reset

The sudo password bit works but I get the following error message from the ufw reset command:

Resetting all rules to installed defaults. Proceed with operation (y|n)? Aborted

The command is being aborted rather than accepting the 'y' I was trying to send it. Can anyone tell me what I am doing wrong?

dessert
  • 39,982

2 Answers2

11

You're piping the y to echo 'my password', not to sudo.

Use the block to group both the echos:

{ echo 'my password' ; echo y ; } | sudo ufw reset

sudo normally reads the password from a terminal, not stdin, unless you supply the -S option.

choroba
  • 9,643
  • this is the wrong way round ;-) first the password, then the y ;-) – pLumo Oct 25 '18 at 08:26
  • sure that it works without the -S and with first printing y, then my_password? Maybe you should try again in a new terminal window where you haven't been logged into sudo before and see that it won't work... – pLumo Oct 25 '18 at 08:31
  • Acutally @RoVo, you are correct. { echo 'passsword' ; echo 'y' ; } | sudo -S ufw reset - that works. – Robert Baker Oct 25 '18 at 08:33
  • still missing the -S – pLumo Oct 25 '18 at 08:37
  • You know what interesting is that it only works once. If you run the same command a second time in the same terminal window, you get the "aborted" message again. Not that it matters, I only need to run it once, but it's strange. – Robert Baker Oct 25 '18 at 08:52
  • 2
    @RobertBaker: That's becuase sudo caches the password and doesn't ask for it the second time. – choroba Oct 25 '18 at 09:17
  • You can kill the cache with sudo -k. – Barmar Oct 25 '18 at 19:50
8

You can achieve it like this:

printf '%s\n%s\n' 'your_password' 'y' | sudo -S ufw reset

or with su -c:

printf '%s\n' 'your_password' | sudo -S su -c "{ yes | ufw reset; }"
  • This uses the nice little tool yes instead of echo y.
  • I prefer printf instead of echo for unknown strings. -> See this.

Note: This is really a bad idea. Better to add ufw to NOPASSWD list in sudoers file. See here. Or if you want to run that command repeatedly/automatically, you may instead add it as root cronjob.

pLumo
  • 26,947