且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python编程:fabric实现SSH远程管理服务器

更新时间:2022-09-03 20:05:47

fabric 可以很轻松的实现 SSH链接

安装

pip install fabric

查看版本

$ fab --version
Fabric 2.4.0
Paramiko 2.4.1
Invoke 1.2.0

脚本运行

# 执行本机命令
import os

os.system("echo 'hi'")

# 执行远程命令
from fabric import Connection

conn = Connection("root@remote")
conn.run("cd /demodir && bash deploy.sh")
conn.close()

命令行运行

编写任务 fabfile.py

# -*- coding: utf-8 -*-

from fabric import task, Connection

@task
def local_list(ctx):
    # 执行本机命令, 会有环境异常,试试 os.system(command)
    ctx.run("ls")


@task
def remote_list(ctx):
    # 链接远程服务器执行命令 
    conn = Connection("root@localhost", connect_kwargs={"password": "123456"})
    conn.run("ls")
    conn.close()

运行任务

$ fab -l
Available tasks:

  local-list
  remote-list

$ fab local-list
fabfile.py

$ fab remote-list
change_url.py
change_url_raw.py
...

相关资料

网站: https://www.fabfile.org/index.html

github: https://github.com/fabric/fabric

英文文档2.4: http://docs.fabfile.org/en/2.4/index.html#

英文文档1.14: http://docs.fabfile.org/en/1.14/index.html

中文文档(2016年版本较低):https://fabric-chs.readthedocs.io/zh_CN/chs/index.html

参考

“No idea what something is!” after running fabric2