python编程(fabric部署)

栏目: Python · 发布时间: 8年前

内容简介:python编程(fabric部署)

【 声明:版权所有,欢迎转载,请勿用于商业用途。 联系信箱:feixiaoxing @163.com】

代码写好了,怎么部署到服务器上面一直是一个问题。过去,我们常常自己用pexpect或者paramiko通过ssh直接拷贝的方法来完成这一工作,这种方法非常暴力而且容易出错。后来有一次机会用了fabric,发现确实不错。通过它,上传、下载、执行服务器程序都能轻松搞定。

1、下载fabric

sudo apt-get install fabric

2、编写fabfile.py

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

3、执行fab文件

fab hello

默认情况下,系统会默认查找fabfile.py这个文件。当然大家也可以用自己喜欢的文件名,比如test.py,这个时候就要这么执行了,

fab -f test hello

4、带参数的task

def hello(name="world"):
    print("Hello %s!" % name)

这个时候只需要给出自己的参数就可以了,

fab hello:name=Jeff

5、执行本地命令

from fabric.api import local

def prepare():
    local("ls -l")

6、执行多个命令

from fabric.api import local

def test():
    local("ls -l")

def commit():
    local("ls -l")

def push():
    local("ls -l")

def prepare():
    test()
    commit()
    push()

7、出错处理

fab程序在执行脚本出错的时候会自动终止,不再继续往下执行。

8、远端执行

from __future__ import with_statement
from fabric.api import *
from fabric.contrib.console import confirm

env.hosts = ['user@ip']

def test():
    run('ls -l')

9、上传文件

from __future__ import with_statement
from fabric.api import *
from fabric.contrib.console import confirm

env.hosts = ['user@ip']

def test():
    l = './*.pdf'
    r = '~'
    put(l, r)

9、下载文件

from __future__ import with_statement
from fabric.api import *
from fabric.contrib.console import confirm

env.hosts = ['user@ip']

def test():
    r = '~/*.pdf'
    l = './'
    get(r, l)

10、远端起服务器程序

对于这种情况,建议先用创建run.sh,将要执行的命令用nohup运行的方式保存在run.sh中。接着,按照如下方式编写脚本运行就可以了,

def deploy():
    run('./run.sh', pty=False)

11、其他资料

关于fabric的其他资料,建议直接看 官网 ,上面的介绍也详细、直观得多。


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

GitHub入门与实践

GitHub入门与实践

[日] 大塚弘记 / 支鹏浩、刘斌 / 人民邮电出版社 / 2015-7 / 39.00元

本书从Git的基本知识和操作方法入手,详细介绍了GitHub的各种功能,GitHub与其他工具或服务的协作,使用GitHub的开发流程以及如何将GitHub引入到企业中。在讲解GitHub的代表功能Pull Request时,本书专门搭建了供各位读者实践的仓库,邀请各位读者进行Pull Request并共同维护。一起来看看 《GitHub入门与实践》 这本书的介绍吧!

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具