一 点睛
本实战调用local()方法执行本地(主控端)命令,添加“@runs_once”修饰符保证该任务函数只执行一次。调用run()方法执行远程命令。
二 代码
#coding=utf-8
#!/usr/bin/env python
from fabric.api import *
env.user='root'
env.hosts=['192.168.0.101','192.168.0.120']
env.password='123456'
@runs_once # 查看本地系统信息,当有多台主机时只运行一次
def local_task(): # 本地任务函数
local("uname -a")
def remote_task():
with cd("/data"): # “with”的作用是让后面的表达式的语句继承当前状态,实现“cd /data/logs && ls -l”的效果
run("ls -l")
三 运行结果
# 本地命令只在本地执行一次
[root@localhost pymaintain]# fab -f 7_3_3.py local_task
[192.168.0.101] Executing task 'local_task'
[localhost] local: uname -a
Linux localhost.localdomain 3.10.0-693.21.1.el7.x86_64 #1 SMP Wed Mar 7 19:03:37 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux
Done.
# 远程命令在每台远程机上都会执行一次
[root@localhost pymaintain]# fab -f 7_3_3.py remote_task
[192.168.0.101] Executing task 'remote_task'
[192.168.0.101] run: ls -l
[192.168.0.101] out: total 4
[192.168.0.101] out: -rw-r--r-- 1 root root 115 Feb 24 16:55 test.tar.gz
[192.168.0.101] out: -rw-r--r-- 1 root root 0 Feb 24 16:42 test.txt
[192.168.0.101] out:
[192.168.0.120] Executing task 'remote_task'
[192.168.0.120] run: ls -l
[192.168.0.120] out: total 8
[192.168.0.120] out: -rw-r--r--. 1 root root 512 Mar 2 08:50 1_2_2.py
[192.168.0.120] out: -rw-r--r--. 1 root root 69 Feb 24 10:01 EICAR
[192.168.0.120] out: -rw-r--r--. 1 root root 0 Feb 24 16:16 test.txt
[192.168.0.120] out:
Done.
Disconnecting from 192.168.0.120... done.
Disconnecting from 192.168.0.101... done.