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
  • 40,956

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
  • 10,313
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
  • 27,991