How to copy /etc/hosts to all my machines?

7,115

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...

Share:
7,115

Related videos on Youtube

Alex
Author by

Alex

Updated on September 17, 2022

Comments

  • Alex
    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
      OMG Ponies over 14 years
      Why not use DNS?
    • Alex
      Alex over 14 years
      How do I use DNS?
    • OMG Ponies
      OMG Ponies over 14 years
    • David Pashley
      David Pashley over 14 years
      you're doing it wrong.
    • Spence
      Spence over 14 years
      This is definitely one of those "I need to drive a nail-- should I use an egg or fine china?" kind of questions.
  • Jim Zajkowski
    Jim Zajkowski over 14 years
    This has a race condition on /tmp/hosts.
  • user1686
    user1686 over 14 years
    < /etc/hosts ssh otherhost "sudo tee /etc/hosts > /dev/null" - otherwise you get the "Useless use of sh award"
  • Jim Zajkowski
    Jim Zajkowski over 14 years
    At least I'll understand my command line when I read it again in six months. Using tee to avoid a call to sh 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.