search
HomeBackend DevelopmentPython Tutorialpython fabric implements remote deployment

python fabric实现远程部署

需求描述

在多人协同开发项目的过程中,几乎每天我们都要提交代码到git服务器,然后部署到测试服务器,每天都在敲那重复的几行命令,实在是无趣。怎么办?运维自动化!接下来就说说fabric这玩意儿,替我们完成一些重复繁杂的工作,相信你会跟我一样喜欢上它的!

本文项目背景

我们这次做的项目是用的django框架,每天我们提交代码到git服务器后,都要手动上传代码到测试服务器,然后执行一系列django框架的命令。每天都要浪费10多分钟的时间,做着重复的劳动,这些工作实在不是一个程序员该干的。。。

解决方案

借助Python的fabric模块可以将自动化部署或者多机操作的命令固化到一个脚本里,然后通过此脚本去执行。

安装fabric

注意:本机和目标服务器都要安装一下
sudo easy_install fabric

或者用pip安装:

pip install fabric

编写脚本

local 是在本机执行;run 是在远程机执行

from fabric.api import hosts, run, env, local, cd, get, lcd
from fabric.tasks import execute
 
env.hosts = ["fab@192.168.1.101:22", "root@192.168.1.101:22"]
env.passwords = {"fab@192.168.1.101:22": "fab", "root@192.168.1.101:22": "tofabor"}
 
 
@hosts("ktv@192.168.1.101:22")
def update():
  """更新测试服务器代码"""
  with cd("/opt/project/project"): # 进入测试服务器的项目目录
    run("git pull origin master") # 从git服务器的master分支下拉最新代码
    run("/usr/local/bin/python2.7 /opt/project/project/manage.py makemigrations") # 这是django框架检测数据库变动的命令
    run("/usr/local/bin/python2.7 /opt/project/project/manage.py migrate") # 这是django框架执行数据库变更的命令
 
@hosts("ktv@192.168.1.101:22")
def restart():
  """重启服务"""
  execute('stop')
  execute('start')
 
 
@hosts("root@192.168.1.101:22")
def start():
  """开始服务"""
  with cd("/opt/project/project"):
    run("supervisorctl start dev")
 
@hosts("ktv@192.168.1.101:22")
def stop():
  """停止服务"""
  pids = run("ps -ef |grep '9001'| awk '{print $2}'")
  pid_list = pids.split('\r\n')
  for i in pid_list[:-2]:
    run('kill -9 %s' % i) # 杀掉运行服务进程

如上脚本保存为fabfile.py (也可保存为其他名称,只是运行命令不一样,下面会详述)

执行脚本

如果你的脚本名称为fabfile.py,那么可以在终端进入你fabfile.py的目录,敲入如下命令回车:

fab update

紧接着,你会看到终端提示你输入git账号及密码,待你输入成功后,将自动下拉git服务器的代码到测试服务器。 
之后运行如下命令,重启服务:

fab restart

如果你的文件名为其他名称,比如ab.py, 那么执行 fab update /restart是错误的,怎么云运行呢? 

fab -f ab update 
fab -f ab restart

注:fabric相当强大,此文只是列举一小功能。如需深入学习,请参见官方文档http://docs.fabfile.org/en/1.6/

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持PHP中文网。

更多 python fabric实现远程部署相关文章请关注PHP中文网!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python and Time: Making the Most of Your Study TimePython and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)