1、注意一定要安裝
fabric == 1.14.0 版本!
2、初步使用
從hello_world開始。
def hello(name="world"):
print("hello %s"%name)
在命令行下直接執(zhí)行:
fab -f xxx.py hello:name=tly
輸出:
hello tly
Done.
fab 是fabric的一個shell命令用來執(zhí)行函數(shù), -f 指定是哪個文件,默認(rèn)是fabfile.py
3、函數(shù)的使用
3.1、local
local函數(shù):本地執(zhí)行的shell命令
from fabric.api import local
def prepare_deploy():
local('uname -s')
執(zhí)行如下:
$ fab -f fabfile_2.py prepare_deploy
[localhost] local: uname -s
Linux
Done.
3.2、run
遠(yuǎn)程服務(wù)器執(zhí)行命令
run('ls -l')
3.3、cd
def execute_ls():
with cd('/etc'):
run('uname -s')
run('ls -l')
進入文件夾,且保存上下文環(huán)境。一定要使用with
3.4、lcd
切換本地文件夾,操作如上
3.5、put
上傳本地文件到遠(yuǎn)程服務(wù)器
def execute_put():
with cd('/root'):
put('/home/tly/project/fibric_demo/aaa', 'aaa')
結(jié)果如下:
$ fab -f fabfile_3.py execute_put
[root@192.200.41.231:22] Executing task 'execute_put'
[root@192.200.41.231:22] put: /home/tly/project/fibric_demo/aaa -> /root/aaa
Done.
Disconnecting from root@192.200.41.231... done.
3.6、get
下載本地文件到遠(yuǎn)程服務(wù)器
def execute_get():
get('/root/aaa', '%(path)s')
結(jié)果如下:
$ fab -f fabfile_3.py execute_get
[root@192.200.41.233:22] Executing task 'execute_get'
[root@192.200.41.233:22] download: /home/tly/project/fibric_demo/aaa <- /root/aaa
Done.
3.7、prompt
3.8、reboot
重啟遠(yuǎn)程服務(wù)器
3.9、@task
3.10、@runs_ones
4、環(huán)境的使用
需要訪問遠(yuǎn)程服務(wù)器的話,那么我們需要填入一些基本的信息,host,user,password等信息。
fabric中是通過設(shè)置env上下文管理器來管理的。
如下:
from fabric.api import *
env.hosts = ['192.200.41.233','192.200.41.232'] #添加多臺服務(wù)器的域名
env.user = 'root' #服務(wù)器的用戶名
env.password = '1' #服務(wù)器的密碼
def execute_ls():
with cd('/virus'):
run('ls')
run('uname -s')
執(zhí)行如下:
(fabric) tly@tly-dev:~/project/fibric_demo$ fab -f fabfile_3.py execute_ls
[192.200.41.233] Executing task 'execute_ls'
[192.200.41.233] run: ls
[192.200.41.233] out: anaconda-ks.cfg api.tar docker perl5 saas-setup saas-setup.tar.gz
[192.200.41.233] run: uname -s
[192.200.41.233] out: Linux
[192.200.41.232] Executing task 'execute_ls'
[192.200.41.232] run: ls
[192.200.41.232] out: anaconda-ks.cfg authority.tar zabbix-release-3.4-2.el7.noarch.rpm
[192.200.41.232] run: uname -s
[192.200.41.232] out: Linux
Done.
Disconnecting from 192.200.41.233... done.
Disconnecting from 192.200.41.232... done.
如果多個服務(wù)器,有多個不同的命令該怎么寫?
使用env.passwords來配置。代碼如下:
from fabric.api import *
env.hosts = ['192.200.41.233', '192.200.41.231']
env.user = 'root'
env.passwords = {
'root@192.200.41.233:22' : '1',
'root@192.200.41.231:22' : '1'
}
def execute_ls():
run('uname -s')
run('ls -l')
一定要記得寫端口等信息。
5、分配不同的組
多個項目,不同的操作,那么我們就需要使用不同的操作。引入 分組
from fabric.api import *
env.passwords = {
'root@192.200.41.233:22' : '1',
'root@192.200.41.231:22' : '1',
'root@192.200.41.203:22' : '2',
'tly@192.168.11.11:22': 1,
}
env.roledefs = {
'testserver': ['root@192.200.41.233:22',],
'realserver': ['tly@192.168.11.11:22', ]
}
@roles('testserver')
def execute_ls():
with cd('/etc'):
run('uname -s')
run('ls -l')