Fabric application case and fabric application case
Example 1: file packaging, upload, and validation
We often do some file package distribution work. The implementation step is to compress and package the files first, upload them to the target server in batches, and finally perform Consistency Verification. In this case, put () methods to upload files. By comparing the md5 values of local and remote host files, the file consistency check is achieved.
#! /Usr/bin/env pythonfrom fabric. api import * from fabric. context_managers import * from fabric. contrib. console import confirmenv. user = 'root' env. hosts = ['2017. 168.1.23 ', '2017. 168.1.24 '] env. password = '000000' @ runs_oncedef tar_task (): # Run the local packaging task function only once with LCD ('/'): local ("tar zcvf auto.tar.gz auto ") def put_task (): run ('mkdir/data') # upload task function with cd ("/data"): with settings (warn_only = True): result = p Ut ("/auto.tar.gz", "/data") # if an exception occurs during the put upload, continue to execute the command. if result is not aborted. failed and not confirm ("put file failed, Continue [Y/N]? "): Abort ('aboring file put task! ') # When an exception occurs, check whether the user continues def check_task (): with settings (warn_only = True): lmd5 = local ("md5sum/auto.tar.gz", capture = True ). split ('') [0] rmd5 = run (" md5sum/data/auto.tar.gz "). split ('') [0] if lmd5 = rmd5: # Compare local and remote file MD5 information print" OK "else: print ERRORdef go (): tar_task () put_task () check_task ()