python fabric使用笔记
fabric
title是开发,但是同时要干开发测试还有运维的活……为毛 task*3 不是 salary * 3 (o(╯□╰)o)
近期接手越来越多的东西,发布和运维的工作相当机械,加上频率还蛮高,导致时间浪费还是优点多。
修复bug什么的,测试,提交版本库(2分钟),ssh到测试环境pull部署(2分钟),rsync到线上机器A,B,C,D,E(1分钟),分别ssh到ABCDE五台机器,逐一重启(8-10分钟) = 13-15分钟
其中郁闷的是,每次操作都是相同的,命令一样,要命的是在多个机器上,很难在本机一个脚本搞定,主要时间都浪费在ssh,敲命令上了,写成脚本,完全可以一键执行,花两分钟看下执行结果
直到,发现了fabric这货
作用
很强大的工具
可以将自动化部署或者多机操作的命令固化到一个脚本里
和某些运维工具很像,用它主要是因为,python…..
简单好用易上手
当然,shell各种命令组合起来也可以,上古神器和现代兵器的区别
环境配置
在本机和目标机器安装对应包(注意,都要有)
sudo easy_install fabric
目前是1.6版本(或者用pip install,一样的)
安装完后,可以查看是否安装成功
[ken@~$] which fab
/usr/local/bin/fab
装完之后,可以浏览下官方文档 http://docs.fabfile.org/en/1.6/
然后,可以动手了
hello world
先进行本机简单操作,有一个初步认识,例子来源与官网
新建一个py脚本: fabfile.py
def hello():
print("Hello world!")
命令行执行:
[ken@~/tmp/fab$] fab hello
Hello world!
Done.
注意,这里可以不用fabfile作为文件名,但是在执行时需指定文件
[ken@~/tmp/fab$] mv fabfile.py test.py
fabfile.py -> test.py
[ken@~/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.
[ken@~/tmp/fab$] fab -f test.py hello
Hello world!
Done.
带参数:
修改fabfile.py脚本:
def hello(name, value):
print("%s = %s!" % (name, value))
执行
[ken@~/tmp/fab$] fab hello:name=age,value=20
age = 20!
Done.
[ken@~/tmp/fab$] fab hello:age,20
age = 20!
Done.
执行本机操作
简单的本地操作:
from fabric.api import local
def lsfab():
local('cd ~/tmp/fab')
local('ls')
结果:
[ken@~/tmp/fab$] pwd;ls
/Users/ken/tmp/fab
fabfile.py fabfile.pyc test.py test.pyc
[ken@~/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
def setting_ci():
local("cd /home/project/test/conf/")
local("git add settings.py")
#后面你懂的,懒得敲了…..
混搭整合远端操作
这时候,假设,你要到机器A的/home/ken/project对应项目目录把配置文件更新下来
#!/usr/bin/env python
# encoding: utf-8
from fabric.api import local,cd,run
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()
然后,执行之:
[ken@~/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)
结果:
[ken@~/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.错误和异常
关于错误处理
默认,一组命令,上一个命令执行失败后,不会接着往下执行
失败后也可以进行不一样的处理,文档
目前没用到,后续用到再看了
3.密码管理
看文档
更好的密码管理方式,哥比较土,没打通,主要是服务器列表变化频繁,我的处理方式是:
1.host,user,port,password配置列表,所有的都写在一个文件
或者直接搞到脚本里,当然这个更........
env.hosts = [
'host1',
'host2'
]
env.passwords = {
'host1': "pwdofhost1",
'host2': "pwdofhost2",
}
或者
env.roledefs = {
'testserver': ['host1', 'host2'],
'realserver': ['host3', ]
}
env.passwords = {
'host1': "pwdofhost1",
'host2': "pwdofhost2",
'host3': "pwdofhost3",
}
2.根据key解析成map嵌套,放到deploy中
另外命令其实也可以固化成一个cmds列表的…..
初略就用到这些,后续有更多需求的时候再去捞文档了,话说文档里好东西真多,就是太多了,看了晕。。。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to download DeepSeek Xiaomi? Search for "DeepSeek" in the Xiaomi App Store. If it is not found, continue to step 2. Identify your needs (search files, data analysis), and find the corresponding tools (such as file managers, data analysis software) that include DeepSeek functions.

The key to using DeepSeek effectively is to ask questions clearly: express the questions directly and specifically. Provide specific details and background information. For complex inquiries, multiple angles and refute opinions are included. Focus on specific aspects, such as performance bottlenecks in code. Keep a critical thinking about the answers you get and make judgments based on your expertise.

Just use the search function that comes with DeepSeek. Its powerful semantic analysis algorithm can accurately understand the search intention and provide relevant information. However, for searches that are unpopular, latest information or problems that need to be considered, it is necessary to adjust keywords or use more specific descriptions, combine them with other real-time information sources, and understand that DeepSeek is just a tool that requires active, clear and refined search strategies.

DeepSeek is not a programming language, but a deep search concept. Implementing DeepSeek requires selection based on existing languages. For different application scenarios, it is necessary to choose the appropriate language and algorithms, and combine machine learning technology. Code quality, maintainability, and testing are crucial. Only by choosing the right programming language, algorithms and tools according to your needs and writing high-quality code can DeepSeek be successfully implemented.

Question: Is DeepSeek available for accounting? Answer: No, it is a data mining and analysis tool that can be used to analyze financial data, but it does not have the accounting record and report generation functions of accounting software. Using DeepSeek to analyze financial data requires writing code to process data with knowledge of data structures, algorithms, and DeepSeek APIs to consider potential problems (e.g. programming knowledge, learning curves, data quality)

Python is an ideal programming introduction language for beginners through its ease of learning and powerful features. Its basics include: Variables: used to store data (numbers, strings, lists, etc.). Data type: Defines the type of data in the variable (integer, floating point, etc.). Operators: used for mathematical operations and comparisons. Control flow: Control the flow of code execution (conditional statements, loops).

Pythonempowersbeginnersinproblem-solving.Itsuser-friendlysyntax,extensivelibrary,andfeaturessuchasvariables,conditionalstatements,andloopsenableefficientcodedevelopment.Frommanagingdatatocontrollingprogramflowandperformingrepetitivetasks,Pythonprovid

Detailed explanation of DeepSeekAPI access and call: Quick Start Guide This article will guide you in detail how to access and call DeepSeekAPI, helping you easily use powerful AI models. Step 1: Get the API key to access the DeepSeek official website and click on the "Open Platform" in the upper right corner. You will get a certain number of free tokens (used to measure API usage). In the menu on the left, click "APIKeys" and then click "Create APIkey". Name your APIkey (for example, "test") and copy the generated key right away. Be sure to save this key properly, as it will only be displayed once
