python fabric库
Fabric简介
Fabric 是一个 Python 库,用于执行本地或远程服务器上的命令,并且可以处理文件传输。它基于 SSH 协议,非常适合自动化服务器管理任务。
1. 安装 Fabric
pip install fabric sudo apt install fabric
2. SSH 密钥
Fabric 通过 SSH 连接到远程服务器。确保你有 SSH 密钥对,并将其添加到远程服务器的 ~/.ssh/authorized_keys
文件中。
3. 编写 Fabric 脚本
Fabric 脚本是一个 Python 脚本,可以在其中定义任务和函数。以下是一些基本的示例:
3.1 本地执行-定义任务
新建脚本文件fabfile.py写入,因为没有使用Connection进行远程连接,因此是在本地执行
from fabric import Connection, task @task def hello(c): c.run('echo "Hello, Fabric!"')
shell 执行fab hello
3.2 python执行-连接到远程服务器
执行 python fabfile.py
def main(): host = 'remotehost' user = 'remoteuser' c = Connection(host=host, user=user) with c.cd('/path/to/directory'): c.run('ls') with c.cd('/path/to/another/directory'): c.run('ls') if __name__ == '__main__': main()
3.3 定义任务-在远程服务器执行命令
fab指令会自动寻找名为fabfile.py的文件然后找到里面的@task进行执行,task必须传递c参数
from fabric import Connection, task @task def hello(c): host = 'remotehost' user = 'remoteuser' c = Connection(host=host, user=user) with c.cd('/home/ubuntu/'): c.run('ls')
shell执行fab hello即可在远程服务器执行
4. 处理文件传输
Fabric 传输文件
from fabric import Connection, task @task def upload_file(c): host = 'remotehost' user = 'remoteuser' c = Connection(host=host, user=user) c.put('local_file_path', 'remote_file_path') @task def download_file(c): host = 'remotehost' user = 'remoteuser' c = Connection(host=host, user=user) c.get('remote_file_path', 'local_file_path')
5. 并行执行任务
Fabric 并行执行任务
from fabric import Connection, task, parallel @task def task1(c): c.run('echo "Running task 1"') @task def task2(c): c.run('echo "Running task 2"') @parallel def parallel_tasks(c): task1(c) task2(c)
fab parallel_tasks
6. 错误处理
使用 try-except 块来捕获和处理错误
from fabric import Connection, task @task def check(c): try: result = c.run('ls nonexistent_file', warn=True) except Exception as e: print(f"An error occurred: {e}") else: print(result)
7. 使用 Fabric API
Fabric 提供了一个丰富的 API,允许执行更复杂的任务:
run
: 执行命令。sudo
: 以超级用户权限执行命令。get
: 从远程服务器获取文件。put
: 将文件上传到远程服务器。open_shell
: 打开一个交互式 shell。
8. 官方文档
本文作者:Fxe0_0
本文链接:https://www.cnblogs.com/Fxe00/articles/18311380
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步