继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

python远程服务操作工具:fabric,远程命令、本地命令、服务器操作利器!

OverWrite_235
关注TA
已关注
手记 138
粉丝 10
获赞 65

fabric是一款命令行工具,支持执行本地命令,执行远程命令,上传下载等。fabric像一个subprocess+paramiko的集合,又像一个更加轻量级的ansible,可以批量对服务进行操作

file

安装插件

'''
安装fabric3
pip3 install fabric3
'''

# C:\Users\Administrator>pip3 install fabric3
# Collecting fabric3
#   Downloading Fabric3-1.14.post1-py3-none-any.whl (92 kB)
#      |████████████████████████████████| 92 kB 73 kB/s
# Requirement already satisfied: six>=1.10.0 in c:\python38\lib\site-packages (from fabric3) (1.15.0)

'''
查看版本信息
fab -V
'''
# C:\Users\Administrator>fab -V
# Fabric3 1.14.post1
# Paramiko 2.7.2

'''
查看帮助信息
fab -h
'''
# C:\Users\Administrator>fab -h
# Usage: fab [options] <command>[:arg1,arg2=val2,host=foo,hosts='h1;h2',...] ...
#
# Options:
#   -h, --help            show this help message and exit
#   -d NAME, --display=NAME
#                         print detailed info about command NAM

远程启用应用

# 导入Connection连接对象
from fabric import Connection

def run():
    '''
    应用部署
    :return:
    '''
    # 连接服务器
    conn = Connection("docker@10.3.210.19", connect_kwargs={"password": "docker"})
    # 执行控制台命令
    with conn.cd('/usr/load/project'):
        # 拉取hello world的docker镜像
        conn.run("docker pull hello world")
        # 启动镜像
        conn.run("docker run hello world")

本地命令执行

# 创建fabfile.py文件
# 导入本地local
from fabric.api import local

def hello_world():
    '''
    本地命令行
    :return:
    '''
    print("查看当前文件目录")
    local("ll -a")

# 命令行调用函数
# $ fab hello_world
打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP