背景:fabric主要执行远程的shell命令,包括文件的上传、下载,以及提示用户输入等辅助其它功能。
测试系统:ubuntu16
要求:python //系统有自带,ubuntu16 通常自带python2.7.5
一、安装fabric
1、安装fabric
$ sudo apt-get install python-pip $ sudo pip install --upgrade pip //升级pip $ sudo pip install fabric
2、查看安装结果
$ which fab
二、fabric的使用
1、编写hello脚本: vim /tmp/fab/hello.py
1.1 脚本内容
#!/usr/bin/env python def hello(): print("Hello world!")
1.2 运行文件及输出结果
$ fab -f hello.py hello -----------------------------------------> Hello world! Done.
2、参数传递:vim /tmp/fab/test1.py
2.1 脚本内容
#!/usr/bin/env python def hello(name): print(‘Hello %s!‘ % name)
2.2 运行文件及输出结果
$ fab -f test01.py hello:jeff --------------------------------------> Hello jeff! Done.
3、本地操作
3.1 vim /tmp/fab/lslocal.py
#!/usr/bin/env python from fabric.api import local def lslocal(): local(‘cd /usr/local‘) local(‘ls‘)
3.2 运行文件及输出结果
$ fab -f local.py lslocal [localhost] local: cd /usr/local && ls bin etc games include lib man sbin share src Done.
4、远程操作
4.1 脚本内容
#!/usr/bin/env python # -*- coding: utf-8 -*- from fabric.api import env,roles,run,execute env.roledef = { ‘server1‘: [‘root@172.16.1.201:22‘,], ‘server2‘: [‘zun1@172.16.1.206:22‘,] } env.password = ‘123456‘ @roles(‘server1‘) def task1(): run(‘cd /usr/local && ls‘) @roles(‘server2‘) def task2(): run(‘cd /home/zun1 && ls‘) def test(): execute(task1) execute(task2)
4.2 运行文件及输出结果
$ fab -f test01.py test ------------------------------------------------------------------------------------> [root@172.16.1.201:22] Executing task ‘task1‘ [root@172.16.1.201:22] run: cd /usr/local && ls [root@172.16.1.201:22] out: bin etc games include lib lib64 libexec sbin share src [root@172.16.1.201:22] out: [zun1@172.16.1.206:22] Executing task ‘task2‘ [zun1@172.16.1.206:22] run: cd /home/zun1 && ls [zun1@172.16.1.206:22] out: test_fabric walle-web.vendor.tgz [zun1@172.16.1.206:22] out: Done. Disconnecting from root@172.16.1.201... done. Disconnecting from 172.16.1.206... done.
以上只对fabric做个大概演示,如想深入研究,可查看 官网教程。
时间: 2025-01-04 14:30:43