简体   繁体   中英

How to use tee with sshpass in shell script

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?

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM