Fabric 是一个 Python 库,用于在多个服务器上执行远程操作,常用于自动化部署。下面是如何使用 Fabric 进行自动化部署的详细指南。
安装 Fabric
首先,使用 pip 安装 Fabric:
pip install fabric
基本用法
Fabric 使用 fabfile.py
文件来定义任务。以下是一个基本示例,包括连接到远程服务器和执行一些命令。
创建 fabfile.py
from fabric import Connection, task
# 定义连接参数
remote_host = 'your_server_ip'
username = 'your_username'
password = 'your_password'
# 任务:显示远程服务器上的文件列表
@task
def list_files(c):
c.run('ls -l')
# 任务:上传文件到远程服务器
@task
def upload_file(c, local_path, remote_path):
c.put(local_path, remote_path)
# 任务:执行远程命令
@task
def execute_command(c, command):
c.run(command)
运行任务
在命令行中运行 Fabric 任务:
fab -H your_server_ip -u your_username -p your_password list_files
fab -H your_server_ip -u