分享

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

 Python集中营 2022-10-10 发布于甘肃

【粉丝福利】回复任意消息,获取全套进阶资料fabric是一款命令行工具,支持执行本地命令,执行远程命令,上传下载等。fabric像一个subprocess+paramiko的集合,又像一个更加轻量级的ansible,可以批量对服务进行操作。点 '关注' ,不迷路,快来和我一起每天进步一点点吧!

安装插件

 1'''
2安装fabric3
3pip3 install fabric3
4'''

5
6# C:\Users\Administrator>pip3 install fabric3
7# Collecting fabric3
8#   Downloading Fabric3-1.14.post1-py3-none-any.whl (92 kB)
9#      |████████████████████████████████| 92 kB 73 kB/s
10# Requirement already satisfied: six>=1.10.0 in c:\python38\lib\site-packages (from fabric3) (1.15.0)
11
12'''
13查看版本信息
14fab -V
15'''

16# C:\Users\Administrator>fab -V
17# Fabric3 1.14.post1
18# Paramiko 2.7.2
19
20'''
21查看帮助信息
22fab -h
23'''

24# C:\Users\Administrator>fab -h
25# Usage: fab [options] <command>[:arg1,arg2=val2,host=foo,hosts='h1;h2',...] ...
26#
27# Options:
28#   -h, --help            show this help message and exit
29#   -d NAME, --display=NAME
30#                         print detailed info about command NAM

远程启用应用

 1# 导入Connection连接对象
2from fabric import Connection
3
4def run():
5    '''
6    应用部署
7    :return:
8    '''

9    # 连接服务器
10    conn = Connection("docker@10.3.210.19", connect_kwargs={"password""docker"})
11    # 执行控制台命令
12    with conn.cd('/usr/load/project'):
13        # 拉取hello world的docker镜像
14        conn.run("docker pull hello world")
15        # 启动镜像
16        conn.run("docker run hello world")

本地命令执行

 1# 创建fabfile.py文件
2# 导入本地local
3from fabric.api import local
4
5def hello_world():
6    '''
7    本地命令行
8    :return:
9    '''

10    print("查看当前文件目录")
11    local("ll -a")
12
13# 命令行调用函数
14# $ fab hello_world

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多