fabric远程批量操作主机

远程批量操作主机

  • ansible: 需要被控主机安装python
  • fabric: 被控主机支持ssh即可,但目前不怎么维护了

安装使用

1
$ pip install fabric

编写脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
from fabric import task
from fabric import ThreadingGroup as Group

# 定义要连接的主机
hosts = ['10.103.172.101', '10.103.172.102', '10.103.172.103', '10.103.172.104', '10.103.172.105', '10.103.172.106']

@task
def exec(c, cmd, arg1=""):
# 创建一个 ThreadingGroup 对象
group = Group(*hosts, user='root', connect_kwargs={'password': 'Admin@123.perf'})

# 并行执行任务
results = group.run(f'{cmd} {arg1}', hide=True)

# 处理结果
for connection, result in results.items():
print(f'{connection.host}:\n{result.stdout}')

@task
def put(c, script):
# 创建一个 ThreadingGroup 对象
group = Group(*hosts, user='root', connect_kwargs={'password': 'Admin@123.perf'})

for connection in group:
remote_path = f"/tmp/{script.split('/')[-1]}"
connection.put(script, remote_path)

批量执行命令

1
2
3
4
# 批量执行命令
$ fab exec "ip a"
# 批量上传文件
$ fab put ./setip.sh

参考