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?

  • 3
    Very bad idea indeed ... But here you go: superuser.com/questions/67765/… – pLumo Oct 25 '18 at 8:13
  • @RoVo thank you the quick reply. If I understand that link you sent me it only covers passing a single variable (in this case the password). In my situation I not only want to pass my PW to Sudo, I also want to pass 'y" to ufw reset. – Robert Baker Oct 25 '18 at 8:19
  • 2
  • 1
    Passwords on a command line is always a bad idea. I'd rather do something like echo y | ssh root@::1 ufw reset. In order to not use an unencrypted key for root access you could use an encrypted key and load it into ssh-agent. – kasperd Oct 25 '18 at 13:03
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.

  • this is the wrong way round ;-) first the password, then the y ;-) – pLumo Oct 25 '18 at 8: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 8:31
  • Acutally @RoVo, you are correct. { echo 'passsword' ; echo 'y' ; } | sudo -S ufw reset - that works. – Robert Baker Oct 25 '18 at 8:33
  • still missing the -S – pLumo Oct 25 '18 at 8:37
  • 2
    @RobertBaker: That's becuase sudo caches the password and doesn't ask for it the second time. – choroba Oct 25 '18 at 9:17
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.

  • thanks for the tip about the yes tool, I will look into it. Also the NOASSWD tip. – Robert Baker Oct 25 '18 at 9:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.