Method to dynamically modify remote machine hosts using python Fabric

  • 2021-01-14 06:02:00
  • OfStack

1. About fabric

fabric is a powerful package for solidifying multi-machine operation and deployment commands into scripts.

Details refer to the document http: / / fabric - chs readthedocs. io/zh_CN chs /

2. Modify remote hosts method

How to modify remote server hosts, think of two ways:

The first idea is to connect to the server through the command, and then use the editor vim or other open hosts file, edit; One obvious disadvantage of this approach is the complexity of the script operation, which requires the use of an editor in the script, as well as the dynamic parsing of existing hosts and the merging of hosts.

The second method is to use the way of file replacement, edit hosts locally, after editing, upload to the server, replace the existing hosts file; This method is easy to use, the script is not complex to execute, the feasibility is much higher, of course, the drawback is that when adding hosts, the operator itself needs to be very clear about the existing hosts.

3. The source code


# encoding=utf-8
from fabric.api import *
 
#  It's configured here hosts information 
env.hosts = ['10.13.131.46', '10.13.135.121', '10.13.133.232']
env.password = "xxxxxxxxxxxxx"
env.user = "xiuzhu"
env.port = 10022
 
@task
def flush():
 sudo('cp /etc/hosts /home/xiuzhu/hosts.bak')
 put("host1", "/home/xiuzhu/hosts.new")
 sudo("mv /etc/hosts /etc/hosts.bak")
 sudo("mv /home/xiuzhu/hosts.new /etc/hosts")

Related articles: