How to copy /etc/hosts to all my machines?
Solution 1
cat /etc/hosts | ssh otherhost "sudo sh -c 'cat >/etc/hosts'"
will do the trick.
Solution 2
This is easily done using Paramiko (the native Python SSH client) rather than calling the ssh command.
- Use Paramiko to scp the file to /tmp on the remoteserver
- Use Paramiko to run 'sudo cp /tmp/hosts /etc/hosts' on the remove server.
There are many examples of Paramiko being used for scp, and to run commands with sudo, available on the web.
Solution 3
You need to do the sudo on the remote host instead of locally. Obviously for this to work, your account on the remote host will need sudo permissions to run the relevant copy command. It would look something like this:
cmd = 'scp /etc/hosts regular_user@%s:/tmp/hosts' % s
os.system(cmd)
cmd = 'ssh regular_user@%s sudo cp /tmp/hosts /etc/hosts' % s
os.system(cmd)
You might find using a framework like fabric or a configuration management system like cfengine or puppet to be a better long term choice...
Related videos on Youtube
Alex
Updated on September 17, 2022Comments
-
Alex over 1 year
import os, sys, time servers = ['dev','admin','db1'] for s in servers: cmd = 'scp /etc/hosts regular_user@%s:/etc/hosts' % s print cmd os.system(cmd)
I have written this script to copy my current HOSTS file to all my other servers. However, I would like to do this from a regular user, not ROOT.
Since over-writing /etc/hosts takes root privelages, I would like to do SUDO. How can I put sudo inside that script?
This won't work, because it is permission denied to change /etc/hosts file.
cmd = 'sudo scp /etc/hosts regular_user@%s:/etc/hosts' % s
-
OMG Ponies over 14 yearsWhy not use DNS?
-
Alex over 14 yearsHow do I use DNS?
-
OMG Ponies over 14 yearsBIND setup: dalantech.com/fusionbb/showtopic.php?tid/33013
-
David Pashley over 14 yearsyou're doing it wrong.
-
Spence over 14 yearsThis is definitely one of those "I need to drive a nail-- should I use an egg or fine china?" kind of questions.
-
-
Jim Zajkowski over 14 yearsThis has a race condition on /tmp/hosts.
-
user1686 over 14 years
< /etc/hosts ssh otherhost "sudo tee /etc/hosts > /dev/null"
- otherwise you get the "Useless use ofsh
award" -
Jim Zajkowski over 14 yearsAt least I'll understand my command line when I read it again in six months. Using
tee
to avoid a call tosh
is certainly a candidate for "Obfuscated Command Line" or "Confusing Use of Side Effect."tee
was made to watch the output of a command while logging the results, not as a replacement for redirection.