Fabric简单案例
注意:创建以 .py 为尾缀的文件,用 fab 执行该文件,若文件名不是 fabfile.py,执行时应为:fab -f +(file name)+(function name) 案例一:运行输出 Hello world
vim fabfile.py
def hello():
print "Hello world!"
fab hello
案例二:
vim fabfile.py
from fabric.api import run, env
env.hosts = ['192.168.1.3']
env.user = 'root'
env.password = '123456'
def hello():
run('touch /home/{4..6}.txt')
fab hello
案例三:分组执行对应的事件(好像还有问题)
vim grouping.py
from fabric.api import env,roles,run,execute,cd
env.roledefs = {
'13': ['root@192.168.1.5','root@192.168.1.6']
'12': ['root@192.168.80.9']
}
env.passwords = {
'13': '123456'
'12': '123456'
}
@roles('12')
def th():
with cd ('/home'):
run('rm -rf 1*')
run('mkdir one')
@roles('13')
def tw():
run('sh /home/shad.sh')
def tom():
#execute(th)
execute(tw)
案例四:一键部署守护进程
from fabric.api import env,roles,run,execute
env.roledefs = {
'yijian':['root@192.168.1.1','root@192.168.2.2']
}
env.passwords = {
'yijina':'123456'
}
@roles('yijian')
def tom():
run('apt update')
run('apt-get install -y supervisor')
run('apt-get install -y python-pip')
run('apt install -y shadowsocks')
run('touch /etc/supervisor/conf.d/shadowsocks.conf')
run('echo [program:shadowsocks] >> /etc/supervisor/conf.d/shadowsocks.conf')
run('echo command:ssserver -p 443 -k password -m aes-256-cfb >> /etc/supervisor/conf.d/shadowsocks.conf')
run('echo numprocs=1 >> /etc/supervisor/conf.d/shadowsocks.conf')
run('echo autostart=true >> /etc/supervisor/conf.d/shadowsocks.conf')
run('echo autorestart=true >> /etc/supervisor/conf.d/shadowsocks.conf')
run('echo user=root >> /etc/supervisor/conf.d/shadowsocks.conf')
run('supervisorctl reload')