0

I do not have passwordless ssh enabled between my two servers a and b. So I am using sshpass to connect to the server b from a.

I have a requirement to add host entries in the /etc/hosts of server b from a. But the user that i am logging into server b is non-root user but has sudo privileges to edit files owned by root.

How do i add host entries to /etc/hosts of server b from server a through a shell script while using sshpass.

Here is the script that was tried:

#!/bin/bash

export SSHPASS="password"
SSHUSER=ciuser
WPC_IP=10.8.150.28

sshpass -e ssh -o UserKnownHostsFile=/dev/null -o 'StrictHostKeyChecking no' $SSHUSER@$WPC_IP "echo test >> /etc/hosts"

Output:

bash test.sh
Warning: Permanently added '10.8.150.28' (RSA) to the list of known hosts.
bash: /etc/hosts: Permission denied

Thank you.

2
  • Can you post the command you tried and how it failed? Commented Dec 2, 2016 at 21:05
  • @thatotherguy: updated the question. Thanks Commented Dec 2, 2016 at 22:19

1 Answer 1

1

sudo doesn't work with redirects directly, so you can use sudo tee -a to append to a file:

echo '1.2.3.4 test' | sudo tee -a /etc/hosts

In your command, this would be:

sshpass -e ssh -o UserKnownHostsFile=/dev/null -o 'StrictHostKeyChecking no' "$SSHUSER@$WPC_IP" "echo test | sudo tee -a /etc/hosts"

Note that this requires passwordless sudo access without a tty, which is not necessarily the same as your sudo privileges.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.