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.

GSM
  • 356
  • 4
  • 11

1 Answers1

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.

Community
  • 1
  • 1
that other guy
  • 116,971
  • 11
  • 170
  • 194