1

I want to modify /etc/hosts (and later also hostname) via a script and ssh. So I'm logged in via ssh and this works:

sudo nano /etc/hosts

It shows the remote hosts file in nano. However I was trying this (via commandline, but this should work in order to make it work in a script right?):

echo [mypassword] | sudo -S nano /etc/hosts

but get this output:

Recieved SIGHUP or SIGTERM

Buffer written to /etc/hosts.save

I just saw that this also happens with more simple text-files (e.g. test.txt). Any ideas how to fix this?

And yes, I am aware of the insecurity of the clear password. :)

Thanks in advance

3 Answers 3

1

I suggest using passwordless sudo than writing your password in clear typing in script.

In the script, use echo to write to the textfile, not nano.

like

#!/bin/bash
echo 'text to write to /etc/hosts' > /etc/hosts

or did i get your purpose right?

2
  • sorry for late answer. This is what I want to do, but entering your code into the terminal gives "/etc/hosts: Permission denied". passwordless sudo is working as I'm not asked to enter a password when doing sudo
    – sotix
    Jul 26, 2013 at 15:52
  • bash -c "echo 'some text' >> /target/file". Also, I suppose OP wanted to append (>>), not overwrite (>) the file. Aug 20, 2013 at 8:49
1

I found the tee command to be helpful in avoiding the sudo limitation on file redirection.

This is the command I used to remotely append the hosts for all machines in my cluster to /etc/hosts:

for i in {1..10}; do ssh [email protected].$i -t "echo '10.1.1.1 dev-1    
10.1.1.4 dev-4
10.1.1.3 dev-3
10.1.1.2 dev-2
10.1.1.6 dev-6
10.1.1.8 dev-8
10.1.1.5 dev-5
10.1.1.10 dev-10
10.1.1.9 dev-9
10.1.1.7 dev-7' | sudo tee -a /etc/hosts >/dev/null" 

The output for each iteration looks like this:

0+1 records in
0+1 records out
255 bytes (255 B) copied, 4.1338e-05 s, 6.2 MB/s

This SU answer was pivotal in building my final solution: https://superuser.com/a/1026359/587485

2
  • Why sudo echo? And dd seems a little over the top for a little output redirection. The recommended way to redirect-append output as super-user is along the lines of sudo tee -a FILE >/dev/null or sudo sh -c "exec cat >> FILE". Sep 29, 2016 at 20:23
  • 1
    @DavidFoerster The sudo was a remnant of prior work and I agree, tee is a bit better solution, so I updated the answer.
    – Garren
    Sep 29, 2016 at 20:50
0

What worked for me is writing in a temporary file and replacing /etc/hosts with it

#!/bin/bash

# $1: IP of the new host
# $2: name of the new host

# read current /etc/hosts int temp-file
cat /etc/hosts > tmphost
# add new entry to temp-file
echo "$1 $2" >> tmphost
# replace hosts file
sudo cp tmphost /etc/hosts
# remove temp-file
rm tmphost

like @Pasi suggested, this needs passwordless sudo

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .