Python fabric 实现 linux 的实现远程操作和部署

发布时间: 更新时间: 总字数:1548 阅读时间:4m 作者: 分享 复制网址

在搞openstack安装部署的时候,总会不停的在控制节点、网络节点和计算节点不停的操作相同的命令和切换窗口,相当机械且浪费时间,知道有一天遇到这fabric这货。

环境配置

官方文档参考链接:

在所有Centos6.5的机器上安装fabric软件:

sudo easy_install fabric

hello world

新建一个py脚本: fabfile.py

def hello():
    print("Hello world!")

命令行执行:

[xiexianbin_cn@~/tmp/fab$] fab hello
Hello world!

Done.

注意,这里可以不用fabfile作为文件名,但是在执行时需指定文件:

[xiexianbin_cn@~/tmp/fab$] mv fabfile.py test.py
fabfile.py -> test.py
[xiexianbin_cn@~/tmp/fab$] fab hello

Fatal error: Couldn't find any fabfiles!

Remember that -f can be used to specify fabfile path, and use -h for help.

Aborting.
[xiexianbin_cn@~/tmp/fab$] fab -f test.py hello
Hello world!

Done.

带参数,修改fabfile.py脚本:

[xiexianbin_cn@~/tmp/fab$] fab hello:name=age,value=20
age = 20!

Done.
[xiexianbin_cn@~/tmp/fab$] fab hello:age,20
age = 20!

Done.

执行本机操作

简单的本地操作:

from fabric.api import local, lcd

def lsfab():
    with lcd('~/tmp/fab'):
        local('ls')

结果:

[xiexianbin_cn@~/tmp/fab$] pwd;ls
/Users/xiexianbin_cn/tmp/fab
fabfile.py   fabfile.pyc  test.py      test.pyc
[xiexianbin_cn@~/tmp/fab$] fab -f test.py lsfab
[localhost] local: cd ~/tmp/fab
[localhost] local: ls
fabfile.py  fabfile.pyc test.py     test.pyc

Done.

实战开始,假设,你每天要提交一份配置文件settings.py到版本库(这里没有考虑冲突的情况)

如果是手工操作:

cd /home/project/test/conf/
git add settings.py
git commit -m 'daily update settings.py'
git pull origin
git push origin

也就是说,这几个命令你每天都要手动敲一次,所谓daily job,就是每天都要重复的,机械化的工作,让我们看看用fabric怎么实现一键搞定:(其实用shell脚本可以直接搞定,但是fab的优势不是在这里,这里主要位后面本地+远端操作做准备,毕竟两个地方的操作写一种脚本便于维护)

from fabric.api import local, lcd

def setting_ci():
    with lcd('/home/project/test/conf/'):
        local("git add settings.py")
        #后面你懂的,懒得敲了......

混搭整合远端操作

这时候,假设,你要到机器A的/home/xiexianbin_cn/project对应项目目录把配置文件更新下来

#!/usr/bin/env python
# encoding: utf-8

from fabric.api import local,cd,run, env

env.hosts=['user@ip:port',] #ssh要用到的参数
env.password = 'pwd'


def setting_ci():
    local('echo "add and commit settings in local"')
    #刚才的操作换到这里,你懂的

def update_setting_remote():
    print "remote update"
    with cd('~/temp'):   #cd用于进入某个目录
        run('ls -l | wc -l')  #远程操作用run

def update():
    setting_ci()
    update_setting_remote()

然后,执行之:

[xiexianbin_cn@~/tmp/fab$] fab -f deploy.py update
[user@ip:port] Executing task 'update'
[localhost] local: echo "add and commit settings in local"
add and commit settings in local
remote update
[user@ip:port] run: ls -l | wc -l
[user@ip:port] out: 12
[user@ip:port] out:


Done.

注意,如果不声明env.password,执行到对应机器时会跳出要求输入密码的交互。

多服务器混搭

操作多个服务器,需要配置多个host:

#!/usr/bin/env python
# encoding: utf-8

from fabric.api import *

#操作一致的服务器可以放在一组,同一组的执行同一套操作
env.roledefs = {
            'testserver': ['user1@host1:port1',],
            'realserver': ['user2@host2:port2', ]
            }

#env.password = '这里不要用这种配置了,不可能要求密码都一致的,明文编写也不合适。打通所有ssh就行了'

@roles('testserver')
def task1():
    run('ls -l | wc -l')

@roles('realserver')
def task2():
    run('ls ~/temp/ | wc -l')

def dotask():
    execute(task1)
    execute(task2)

结果:

[xiexianbin_cn@~/tmp/fab$] fab -f mult.py dotask
[user1@host1:port1] Executing task 'task1'
[user1@host1:port1] run: ls -l | wc -l
[user1@host1:port1] out: 9
[user1@host1:port1] out:

[user2@host2:port2] Executing task 'task2'
[user2@host2:port2] run: ls ~/temp/ | wc -l
[user2@host2:port2] out: 11
[user2@host2:port2] out:


Done.

扩展

1.颜色

可以打印颜色,在查看操作结果信息的时候更为醒目和方便

from fabric.colors import *

def show():
    print green('success')
    print red('fail')
    print yellow('yellow')
#fab -f color.py show

2.错误和异常

http://docs.fabfile.org/en/1.6/usage/execution.html#failures

http://docs.fabfile.org/en/1.6/tutorial.html#failure-handling

3.密码管理

更好的密码管理方式,哥比较土,没打通,主要是服务器列表变化频繁,我的处理方式是:

3.1 host,user,port,password配置列表,所有的都写在一个文件

或者直接搞到脚本里,当然这个更……..

env.hosts = [
        'host1',
        'host2'
]
# 注意: 要使env.passwords生效, host格式必须是  user@ip:port 端口号一定要显式写出来,即使是使用的默认22端口
env.passwords = {
    'host1': "pwdofhost1",
    'host2': "pwdofhost2",
}

或者
env.roledefs = {
'testserver': ['host1:22', 'host2:22'],
'realserver': ['host3:22', ]
}
# 注意: 要使env.passwords生效, host格式必须是  user@ip:port 端口号一定要显式写出来,即使是使用的默认22端口
env.passwords = {
    'host1:22': "pwdofhost1",
    'host2:22': "pwdofhost2",
    'host3:22': "pwdofhost3",
}

3.2 根据key解析成map嵌套,放到deploy中

另外命令其实也可以固化成一个cmds列表的…..

粗略就用到这些,后续有更多需求的时候再去捞文档了,话说文档里好东西真多,就是太多了,看了晕。。。

TODO:

装饰器作用?
@task
@parallel

命令行常用: fab --help
fab -l             -- 显示可用的task(命令)
fab -H             -- 指定host,支持多host逗号分开
fab -R             -- 指定role,支持多个
fab -P             -- 并发数,默认是串行
fab -w             -- warn_only,默认是碰到异常直接abort退出
fab -f             -- 指定入口文件,fab默认入口文件是:fabfile/fabfile.py

状态确认及错误处理

更复杂的操作
Home Archives Categories Tags Statistics
本文总阅读量 次 本站总访问量 次 本站总访客数