local Run a command on the local system. 它是对subprocess模块的封装(Shell=True)可以通过设置Capture = True/False来捕获其执行结果。
run Run a shell command on a remote host. 该命令的返回值包含了远程命令是否执行成功以及远程命令的返回码等信息。通过run执行命令时,通常会要求输入目标机器密码,如果对多台机器进行部署,可以通过设置env.passwords来避免手动输入密码,具体的设置方法会在下篇笔记中介绍。
get Download one or more files from a remote host.
put Upload one or more files to a remote host.
sudo Run a shell command on a remote host, with superuser privileges. 功能与run操作类似,它可以对当前用户临时提权来执行某些需要root权限的命令。 此外,还有些不常用的命令(如:prompt, reboot, open_shell, require)这里没有列出
from __future__ import with_statement from fabric.api import * from fabric.contrib.console import confirm
env.hosts = ['my_server']
def test(): with settings(warn_only=True): result = local('./manage.py test my_app', capture=True) if result.failed and not confirm("Tests failed. Continue anyway?"): # 这有个短逻辑 abort("Aborting at user request.")
def commit(): local("git add -p && git commit")
def push(): local("git push")
def prepare_deploy(): test() commit() push()
def deploy(): code_dir = '/srv/django/myproject' with settings(warn_only=True): if run("test -d %s" % code_dir).failed: run("git clone user@vcshost:/path/to/repo/.git %s" % code_dir) with cd(code_dir): run("git pull") run("touch app.wsgi")
先看个例子,下面是一段部署脚本
deploy.py
1. 创建一个远程连接
2. 进入指定目录
3. 在指定目录下面执行重启命令
1 2 3 4 5 6 7 8 9 10 11 12 13
from fabric import Connection
defmain(): # ip 我是随便填的 # 如果你的电脑配了ssh免密码登录,就不需要 connect_kwargs 来指定密码了。 c = Connection("root@232.231.231.22", connect_kwargs={"password": "youpassword"})
from fabric import Connection c = Connection(‘web1’) c.put(‘myfiles.tgz’, ‘/opt/mydata’) c.run(‘tar -C /opt/mydata -xzvf /opt/mydata/myfiles.tgz’) 多台服务器
如果是要在多台服务器运行命令,简单的办法就是使用迭代,挨个服务器执行命令:
web1,web2,mac1 都是服务器的名字,你也可以用ip代替
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
>>> from fabric import Connection >>> for host in ('web1', 'web2', 'mac1'): >>> result = Connection(host).run('uname -s') ... print("{}: {}".format(host, result.stdout.strip())) ... web1: Linux web2: Linux mac1: Darwin 或者使用 SerialGroup
from fabric import SerialGroup as Group pool = Group('web1', 'web2', 'web3', connect_kwargs={"password": "youpassword"} ) pool.put('myfiles.tgz', '/opt/mydata') pool.run('tar -C /opt/mydata -xzvf /opt/mydata/myfiles.tgz') Group(*hosts, **kwargs) 参数说明: