3. 文件名不为fabfile.py时需进行指定
# mv fabfile.py test.py
# fab hello
Fatal error: Couldn't find any fabfiles!
Remember that -f can be used to specify fabfile path, and use -h for help.
# fab -f test.py hello
Hello fab!
4. 参数传递
#vi fabfile.py
def hello(name):
print 'Hello %s!'%name
# fab hello:name=fab
Hello fab!
# fab hello:fab
Hello fab!
2.2. 本地操作
执行本地操作命令使用local
1. fabfile.py脚本内容如下
from fabric.api import local
def test():
local('cd /home/')
local('ls -l|wc -l')
2. 执行命令fab test,结果如下
# fab test
[localhost] local: cd /home/
[localhost] local: ls -l|wc -l
2.3. 远程操作
执行远程操作命令使用run
1. fabfile.py脚本内容如下
from fabric.api import cd,run,env,hosts
env.hosts=['192.168.85.99:22','192.168.85.101:22']
env.password='test'
def test():
with cd('/home'):
run("du -sh")
2. 执行命令fab test,结果如下
# fab test
[192.168.85.99:22] Executing task 'test'
[192.168.85.99:22] run: du -sh
[192.168.85.99:22] out: 392G .
[192.168.85.99:22] out:
[192.168.85.101:22] Executing task 'test'
[192.168.85.101:22] run: du -sh
[192.168.85.101:22] out: 5.6G .
[192.168.85.101:22] out:
Disconnecting from 192.168.85.99... done.
Disconnecting from 192.168.85.101... done.
3. 多服务器混合,需要在不同服务器进行不同操作时,可参考如下脚本
from fabric.api import env,roles,run,execute
env.roledefs = {
'server1': ['root@192.168.85.99:22',],
'server2': ['root@192.168.85.100:22', ]
}
env.password = 'test'
@roles('server1')
def task1():
run('ls /home/ -l | wc -l')
@roles('server2')
def task2():
run('du -sh /home')
def test():
execute(task1)
execute(task2)
结果如下
# fab test [root@192.168.85.99:22] Executing task 'task1' [root@192.168.85.99:22] run: ls /home/ -l | wc -l [root@192.168.85.99:22] out: 27 [root@192.168.85.99:22] out: [root@192.168.85.100:22] Executing task 'task2' [root@192.168.85.100:22] run: du -sh /home [root@192.168.85.100:22] out: 1.4G /home [root@192.168.85.100:22] out: Disconnecting from 192.168.85.99... done. Disconnecting from 192.168.85.100... done. |