运行脚本的环境为centos7 ,因centos6安装低版本的fabirc 时老报错, 测试业务服务器为centos6.5
yum install python-setuptools
pip install fabric==1.14.0 (默认会安装新版本,新版本去掉了fabric.api 模块)
fab -f simple5.py deploy() 运行脚本 ,用fab 命令,而不是用python运行
最后显示如下 表示成功
Done.
Disconnecting from 192.168.1.10... done.
Disconnecting from 192.168.1.20... done.
Disconnecting from 192.168.0.22... done.
脚本参照刘天斯的python自动化运维如下:
[root@localhost ~]# cat simple5.py
#!/usr/bin/env python
from fabric.colors import *
from fabric.api import * #新版本的fabric 已移除次模块
env.user='root'
env.roledefs = {
'webservers': ['192.168.1.10', '192.168.1.20'], # 定义服务器组
'dbservers': ['192.168.0.22']
}
env.passwords = {
'[email protected]:22': 'waihai', #服务器密码配置
'[email protected]:22': 'root',
'[email protected]:22': 'waihai'
}
@roles('webservers') #引用上面的服务器组定义,表示只对wenservers下的服务器执行
def webtask():
print yellow("Install nginx php php-fpm...")
with settings(warn_only=True): # with 表示按继承状态,按顺序执行下面命令
run("yum -y install nginx")
run("yum -y install php-fpm php-mysql php-mbstring php-xml php-mcrypt php-gd")
run("chkconfig --levels 235 php-fpm on")
run("chkconfig --levels 235 nginx on")
@roles('dbservers') #引用上面的服务器组定义,表示只对dbservers下的服务器执行
def dbtask():
print yellow("Install Mysql...")
with settings(warn_only=True):
run("yum -y install mysql mysql-server")
run("chkconfig --levels 235 mysqld on")
@roles ('webservers', 'dbservers')
def publictask():
print yellow("Install epel ntp...")
with settings(warn_only=True):
run("rpm -Uvh http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm")
run("yum -y install ntp")
def deploy():
execute(publictask) 执行函数
execute(webtask)
execute(dbtask)