0

I have a situation that I need to append several lines(ip and hosts) from a file to /etc/hosts.

If I execute the below command

sshpass -p password cat /tmp/hosts |sudo tee -a /etc/hosts

I am getting

sudo: no tty present and no askpass program specified. Sorry, try again.

sudo: no tty present and no askpass program specified. Sorry, try again.

sudo: no tty present and no askpass program specified. Sorry, try again.

sudo: 3 incorrect password attempts

Any alternatives to this?

Community
  • 1
  • 1
Paul
  • 1,066
  • 2
  • 11
  • 27

2 Answers2

3

How about

sudo -S sh -c 'cat /tmp/hosts >> /etc/hosts' <<< "password"

It's best to contain redirections for sudo within a subshell so that the elevated permissions are applied to opening the destination file.

ref: See https://stackoverflow.com/a/4327123/7552

Community
  • 1
  • 1
glenn jackman
  • 207,528
  • 33
  • 187
  • 305
0

The error you face comes from the fact that sshpass tries to send the password to cat, not to sudo. Your command line should have, in theory, looked rather like this:

cat /tmp/hosts |sshpass -p password sudo tee -a /etc/hosts

but sshpass does not forward stdin to sudo so this is a dead end. (sudo does forward stdin though that is why something like sudo tee works)

You could do something like this

sshpass -p password sudo echo "Hello"
cat /tmp/hosts | sudo tee -a /etc/hosts

so that the second call to sudo does not require a password.

Another option is to embed the cat and the redirection in a shell script and then just

sshpass -p password sudo ./thescript.sh

Or you can, as @glennjackman wrote, embed the cat and the redirection in a subshell:

sshpass -p password sudo sh -c 'cat /tmp/hosts >> /etc/hosts'

And of course, you can configure sudo to not require passwords.

Community
  • 1
  • 1
damienfrancois
  • 39,477
  • 7
  • 71
  • 82