2.1.    Hello,fab
1. 在当前目录下新建文件fabfile.py,输入内容如下
2. 执行命令fab hello,结果如下
3. 文件名不为fabfile.py时需进行指定
| 1 | # mv fabfile.py test.py | 
 
| 7 | Fatal error: Couldn't find any fabfiles! | 
 
| 11 | Remember that -f can be used to specify fabfile path, and use -h for help. | 
 
| 15 | # fab -f test.py hello | 
 
 
 
4. 参数传递
2.2.    本地操作
执行本地操作命令使用local
1. fabfile.py脚本内容如下
| 1 | from fabric.api import local | 
 
 
 
2. 执行命令fab test,结果如下
| 3 | [localhost] local: cd /home/ | 
 
| 5 | [localhost] local: ls -l|wc -l | 
 
 
 
2.3.    远程操作
执行远程操作命令使用run
1. fabfile.py脚本内容如下
| 1 | from fabric.api import cd,run,env,hosts | 
 
| 3 | env.hosts=['192.168.85.99:22','192.168.85.101:22'] | 
 
 
 
2. 执行命令fab test,结果如下
| 3 | [192.168.85.99:22] Executing task 'test' | 
 
| 5 | [192.168.85.99:22] run: du -sh | 
 
| 7 | [192.168.85.99:22] out: 392G      . | 
 
| 9 | [192.168.85.99:22] out: | 
 
| 11 | [192.168.85.101:22] Executing task 'test' | 
 
| 13 | [192.168.85.101:22] run: du -sh | 
 
| 15 | [192.168.85.101:22] out: 5.6G     . | 
 
| 17 | [192.168.85.101:22] out: | 
 
| 19 | Disconnecting from 192.168.85.99... done. | 
 
| 21 | Disconnecting from 192.168.85.101... done. | 
 
 
 
3. 多服务器混合,需要在不同服务器进行不同操作时,可参考如下脚本
| 1 | from fabric.api import env,roles,run,execute | 
 
| 5 | 'server1': ['root@192.168.85.99:22',], | 
 
| 7 | 'server2': ['root@192.168.85.100:22', ] | 
 
| 17 | run('ls /home/ -l | wc -l') | 
 
 
 
结果如下
| 3 | [root@192.168.85.99:22] Executing task 'task1' | 
 
| 5 | [root@192.168.85.99:22] run: ls /home/ -l | wc -l | 
 
| 7 | [root@192.168.85.99:22] out: 27 | 
 
| 9 | [root@192.168.85.99:22] out: | 
 
| 11 | [root@192.168.85.100:22] Executing task 'task2' | 
 
| 13 | [root@192.168.85.100:22] run: du -sh /home | 
 
| 15 | [root@192.168.85.100:22] out: 1.4G   /home | 
 
| 17 | [root@192.168.85.100:22] out: | 
 
| 19 | Disconnecting from 192.168.85.99... done. | 
 
| 21 | Disconnecting from 192.168.85.100... done. | 
 
 
 
 
3.    参考文章
上面只是对Python+fabric自动部署脚本编写方法的简单介绍,在实际应用过程中根据具体需求编写相应的脚本时可以参考如下文章:
1. http://docs.fabfile.org/en/latest/index.html
2. http://wklken.me/posts/2013/03/25/python-tool-fabric.html