Python fabric usage and examples

Source: Internet
Author: User
Tags fpm symlink

Abric is a python-based SSH command-line tool that simplifies application deployment and system administration tasks for SSH, which provides a system-based operational component that enables local or remote shell commands, including command execution, file upload, download, and full execution log output. The fabric is built on top of the Paramiko, making it easier to operate .

Command format:

Fab [options] <command>[:arg1,arg2=val2,host=foo,hosts= ' h1;h2 ',...] ...

Common parameters:

-L #显示定义好的任务函数名-F #指定fab入口文件, the default entry file name is Fabfile.py-f #指定网关 (transit) device, such as the Bastion machine environment, fill the bastion machine IP can-H #指定目标主机, multiple hosts with ', ' separated-p #远程账号的密码, Fab executes by default using the root account-P #以异步并行方式运行多主机任务, the default is serial run-R #指定role (role), differentiated by role name different business group devices-T #设置设备连接超时时间 (seconds)-T #设置远程 Host command execution time-out (seconds)-W #当命令执行失败, warning instead of default abort task.

Example: test.py

#!/usr/bin/env python#-*-coding:utf-8-*-from fabric.api Import run# define a task function to implement remote execute ' uname-s ' command with the Run Method def host_type () : Run (' uname-s ')

Fab Operations Command:

fab-h localhost host_type fab-p 123456-h localhost--' uname-s '

Fabfile File Preparation

Env object:

env.hosts    #定义目标主机, can be represented by IP or hostname, defined as a list of Python. such as env.hosts=[' 192.168.1.21 ', ' 192.168.1.22 ']env.exclude_hosts    #排除指定主机, such as env.exclude_hosts=[' 192.168.1.21 ']env.user    #定义用户名, such as env.user= ' root ' env.port    #定义端口, defaults to 22, such as Env.port = ' env.password    ' #定义密码, such as env.password= ' 123456 ' env.passwords   #定义多个密码, different hosts corresponding to different passwords, such as: env.passwords = {' [email protected]:22 ': ' 123456 ', ' [email protected]:22 ': ' 654321 '} env.gateway    #定义网关 (relay, Fortress machine) IP, such as env.gateway= ' 192.168.1.23env.roledefs    #定义角色分组, For example, the Web combination DB Group host distinguishes: env.roledefs = {' webserver ': [' 192.168.1.21 ', ' 192.168.1.22 '], ' dbserver ': [' 192.168.1.25 ', ' 192.168.1.26 ']}env.deploy_release_dir    #自定义全局变量, format:env. +  ' variable name ', such as Env . Age,env.sex, etc. 

Examples of how to use Env.roledefs:

Env.roledefs = {' webserver ': [' 192.168.1.21 ', ' 192.168.1.22 '], ' dbserver ': [' 192.168.1.25 ', ' 192.168.1.26 ']}# A python adorner is used to refer to a grouping, such as: @roles (' webserver ') def webtask (): Run ('/usr/local/nginx/sbin/nginx ') @roles (' webserver ', ' DBServer ') def publictask (): Run (' uptime ')


Fabric Common APIs

Local #执行本地命令, such as the local (' uname-s ') LCD #切换本地目录, such as the LCD (' home ') CD #切换远程目录run #执行远程命令sudo #sudo方式执行远程命令 such as sudo ('/etc/init.d/httpd start ') put #上次本地文件导远程主机, such as put ('/home/user.info ', '/data/user.info ') get #从远程主机下载文件到本地, such as: Get ('/da Ta/user.info ', '/home/user.info ') prompt #获得用户输入信息, such as: prompt (' Please input user password: ') Confirm #获得提示信息确认, such as: Confirm (' Test failed,continue[y/n]? ') Reboot #重启远程主机, such as: Reboot () @task #函数修饰符, the identified function is fab callable, non-tagged to fab not visible, pure business logic @runs_once #函数修饰符, the identified function is executed only once, not affected by multiple hosts


Fabric Application Examples:

Example 1: View local and remote host information fab-f test.py local_task fab-f test.py remote_task

#!/usr/bin/env python#-*-encoding:utf-8-*-from fabric.api Import *env.user = ' root ' env.hosts = [' 192.168.1.22 ']env.pas    Sword = ' 123456 ' @runs_once #查看本地系统信息, when there are multiple hosts only one time Def local_task (): #本地任务函数 local (' uname-a ') def remote_task (): With CD ('/var/logs '): #with的作用是让后面的表达式语句继承当前状态, implementation: Cd/var/logs && Ls-l effect Run (' ls-l ')


Example 2: Dynamically getting a list of remote directories fab-f test.py Go

#!/usr/bin/env python#-*-coding:utf-8-*-from fabric.api Import *env.user = ' root ' env.hosts = [' 192.168.1.22 ']ENV.PASSW Ord = ' 123456 ' @runs_once #主机遍历过程中, only the first trigger this function Def input_raw (): Return prompt (' Please input directoryname: ', default= '/ro OT ') def worktask (dirname): Run (' ls-l ' +dirname) @task #限定只有go函数对fab命令可见, other functions not using the @task tag the Fab command is not available def go (): Getdirna me = Input_raw () worktask (Getdirname)


Example 3: Gateway mode file upload and execution (relay, Fortress machine) Fab-f test.py go

#!/usr/bin/env python# -*- encoding: utf-8 -*-from fabric.api import * from fabric.context_managers import *from fabric.contrib.console import  confirmenv.user =  ' root ' env.gateway =  ' 192.168.1.23 '     #定义堡垒机IP, as a file upload, Relay settings performed env.hosts = [' 192.168.1.21 ', ' 192.168.1.22 ']env.passwords = {      ' [email protected]:22 ': ' 123456 ',     ' [email protected]:22 ': ' ABCdef ',      ' [email protected]:22 ': ' 123abc ',   #堡垒机账号信息}lpackpath =  '/home/ Install/lnmp.tar.gz '     #本地安装包路径rpackpath  =  '/tmp/install '     # Remote Installation package path @taskdef put_task ():   #上传文件     run (' Mkdir -p /tmp/install '      #默认情况下, Fabric stops executing subsequent commands when the command execution fails. Sometimes, we allow a command that ignores the failure to continue execution, such as run (' RM&NBSP;/TMP/ABC ') that may fail when the file does not exist, and can be used With settings (warn_Only=true): Executes the command so that fabric will only play a warning message without interrupting execution.     with settings (warn_only=true):         Result = put (Lpackpath,rpackpath)     #上传     if result.failed  and not confirm (' put file failed,continue[y/n]? '):         abort (' aborting file put task! ') @taskdef  run_task ():    #安装     with cd ('/tmp/install '):         run (' tar -zxvf lnmp.tar.gz ')       &NBSP;&NBSP;&NBSP;WITH&NBSP;CD (' lnmp/'):     #使用with继承/tmp/install directory location Status              run ('./centos.sh ') @taskdef  go ():    # Upload, install Combo command     put_task ()     run_task ()


Example 4: Package upload and checksum for a file

#!/usr/bin/env python# -*- coding: utf-8 -*-from fabric.api import * from fabric.context_managers import *from fabric.contrib.console import  confirmenv.user =  ' root ' env.hosts = [' 192.168.1.23 ', ' 192.168.1.24 ']env.password =   ' 123456 ' @task @runs_oncedef tar_task (): With lcd ("/data/logs"): Local ("tar zcf  Logs.tar.gz test.log ") @taskdef  put_task (): Run (' Mkdir -p /data/logs ') with cd ("/data/ Logs "): With settings (warn_only=true): Result=put ("/data/logs/logs.tar.gz ","/data/logs/logs.tar.gz ") if  result.failed and not confirm ("put file failed,continue[y/n]"): Abort (' Aborting  file put task ') @taskdef  check_task (): With settings (warn_only=true): Lmd5=local (" Md5sum /data/logs/logs.tar.gz ", Capture=true). Split ('   ') [0]rmd5=run (" md5sum /data/logs/ Logs.tar.gz "). Split ('   ') [0]IF&NBSP;LMD5==RMD5:PRint  "OK" else:print  "ERROR" Def go (): Tar_task () Put_task () Check_task () fab -f test.py  go


Example 5: Deploying the LNMP Environment

#!/usr/bin/env python# -*- coding: utf-8 -*-from fabric.colors import  *from fabric.api import *env.user= ' root ' env.roledefs={' webservers ':  [' 192.168.1.21 ', ' 192.168.1.22 '], ' dbservers ':  [' 192.168.1.23 ']}env.passwords={' [email protected]:22 ': ' 123456 ', ' [email  protected]:22 ': ' asdfgh ', ' [email protected]:22 ': ' 654321 '} @roles (' Webservers ') Def web_task (): Print yellow ("install nginx php php-fpm ...") with settings (warn_only=True): Run ("Yum  install -y nginx ") Run (" Yum install -y php-fpm php-mysql php-mbstring &NBSP;PHP-XML&NBSP;PHP-MCRYPT&NBSP;PHP-GD ") Run (" SYSTEMCTL&NBSP;ENABLE&NBSP;PHP-FPM ") Run (" Systemctl enable  nginx ") @roles (dbservers) def db_task ():p rint yellow (" Install mysql ... ") with settings ( Warn_only=true): Run ("Yum install -y mariadb mariadb-server") Run ("Systemctl enable  mariadb ") @roles (' WebServers ', ' Dbservers ') def pub_task ():p rint yellow ("Install ntp ...") with settings (warn_only =true): Run ("Yum install epel-release -y") Run ("yum install ntp -y ") def  deploy (): Execute (Pub_task) execute (web_task) execute (db_task) fab -f test.py deploy


Example: 6: Production Environment Code Release Management (Package release rollback)

#!/usr/bin/env python# -*- coding: utf-8 -*-from fabric.api import * from fabric.colors import *from fabric.context_managers import *from  fabric.contrib.console import confirmimport timeenv.hosts=[' 192.168.1.21 ', ' 192.168.1.22 '] env.user= ' root ' env.password= ' 124530 ' env.project_dev_source= '/data/dev/webadmin/' env.project_tar_source= '/data/ Dev/releases/' env.project_pack_name= ' release ' env.deploy_project_root= '/data/www/webadmin/' env.deploy_release_ Dir= ' releases ' env.deploy_current_dir= ' current ' Env.deploy_version=time.strftime ("%y-%m-%d") + "V2" @runs_oncedef  input_version (): Return prompt ("please input your roolback version id  ", default=") @task @runs_oncedef tar_source ():p rint yellow ("Creating source package ...") WITH&NBSP;LCD (Env.project_dev_source): local ("TAR&NBSP;-ZCF&NBSP;%S.TAR.GZ&NBSP;."  %  (Env.project_tar_source + env.projeCt_pack_name)) Print green ("creating source package success!") @taskdef  put_package ():p rint yellow ("Start put package ...") with settings (warn_only= True): WITH&NBSP;CD (Env.deploy_project_root+env.deploy_release_dir): Run ("mkdir %s"  %  (Env.deploy _version)) env.deploy_full_path=env.deploy_project_root + env.deploy_release_dir +  "/"  +env.deploy_versionwith settings (warn_only=true): Result=put (Env.project_tar_source+env.project_pack _name+ ". tar.gz", Env.deploy_full_path) if result.failed and not  ("put file failed, CONTINUE[Y/N]: Abort (' Aborting file put task ') WITH&NBSP;CD (Env.deploy_full_path): Run ("Tar  -zxf %s.tar.gz " %  (Env.project_pack_name)) Run (" Rm -rf %s.tar.gz " %  ( Env.project_pack_name)) Print green ("put & untar package success!") @taskdef  make_symlink ():p rint yellow ("Update curreNt symlink ") env.deploy_full_path=env.deploy_project_root + env.deploy_release_dir + " /" +env.deploy_versionwith settings (warn_only=true): Run (" rm -rf %s " %  ( Env.deploy_project_root+env.deploy_current_dir) Run ("ln -s %s %s"  %  (Env.deploy_full_ Path,env.deploy_project_root+env.deploy_current_dir)) Print green ("make symlink success!") @taskdef  roolback ():p rint yellow ("Roolback project version") versionid=input_version () if  versionid== ': Abort ("project version id error,abort!") env.deploy_full_path=env.deploy_project_root + env.deploy_release_dir +  "/"  + Versionidrun ("rm -f %s"  %  (Env.deploy_project_root+env.deploy_current_dir)) Run ("Ln -s  %s %s " %  (env.deploy_full_path,env.deploy_project_root+env.deploy_current_dir)) print  green ("roolback success!") @taskdef  go (): Tar_source () put_packAge () Make_symlink () Production nginx directory configuration root /data/www/webadmin/current; 




Python fabric usage and examples

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.