安装Fabric
1 | $ pip install fabric |
命令
run (fabric.operations.run)
sudo (fabric.operations.sudo)
local (fabric.operations.local)
get (fabric.operations.get)
put (fabric.operations.put)
prompt (fabric.operations.prompt)
reboot (fabric.operations.reboot)
Example
DateFormat.py
// 根据时间获取上个小时log文件名中的时间,单独处理0点时刻
# coding=utf8
import datetime
def date_format(flag=''):
fm = '%Y-%m-%d' if flag else '%Y%m%d'
h = datetime.datetime.now().hour
if h == 0:
dt = datetime.date.today() - datetime.timedelta(days=1)
dt = dt.strftime(fm)
h = 23
else:
dt = datetime.date.today()
dt = dt.strftime(fm)
h = datetime.datetime.now().hour - 1
if h < 10:
h = ''.join(['0', str(h)])
else:
h = str(h)
if flag:
return '-'.join([dt, h])
else:
return dt + h
LogFileLoad.py
// Fabric执行文件
#coding=utf8
import os, sys
import random
import datetime
from fabric.api import *
from fabric.colors import red, green, yellow
from fabric.operations import *
// 远程主机设置
env.hosts = ['root@192.168.0.1:22', 'root@192.168.0.1:22',
'root@192.168.0.1:22']
// 远程主机设置密码设置
env.passwords = {
'root@192.168.0.1:22':'123abc',
'root@192.168.0.1:22':'123abc',
'root@192.168.0.1:22':'123abc'
}
// Test for connection
def test():
run('uname -s')
def format_log_file_name_by_time():
# Format log file name by datetime like access_2015031204.log .
dt = date_format()
file_name = ['access_', dt, '.log']
file_name = ''.join(file_name)
return file_name
def load():
remote_log_path = "/nginx/www/logs/log/"
remote_log_full_path = ''.join(
[remote_log_path, format_log_file_name_by_time()])
# Need change to absolute path equal the script's path.
local_path = os.getcwd()
local_path = '/'.join([local_path, date_format('-')])
if not os.path.exists(local_path):
os.mkdir(local_path)
local_log_file_name = '.'.join( //随机生成本地文件名
[str(int(time.time())) + str(random.randint(1000, 9999)), 'log'])
local_full_path = '/'.join([local_path, local_log_file_name])
print "%s -> %s ..." % (remote_log_full_path, local_full_path)
get(remote_log_full_path, local_full_path) //下载文件
if __name__ == '__main__':
load()
fab -f LogFileLoad.py load
测试通过后即可通过crontab部署,注意,在crontab时需将脚本中的相对路径全部改为绝对路径。
更多使用方法可以参考链接。