用Python写Linux脚本实例(一)

前言

需求就是读取日志文件实现企业微信报警,由于之前没有写过python脚本,一开始是由shell实现的。但是shell对于json的拼接很不友好,对于“空格”和“引号”的处理更是让人难受,于是打算尝试写一个python脚本。

过程

时间戳的获取
T = time.time()
t2 = (int(round(T * 1000)))
t3 = (int(round(T * 1000 - 5*60*1000)))
python的比较问题

shell中直接拿出awk过滤出的东西可以直接比较。但在python中是有类型的。字符串当然没办法和整形进行比较,首先就是要把split分割日志返回的数组转为整形变量。
我要分割的日志有特殊的格式$1和$2为数字需要进行比较。$3为拼接好的json

 array_str = line.split(LOG_MARK)
 time_stamp = int(array_str[1]) 
 type_ = int(array_str[2])
字符的拼接

这里是调用shell命令实现http post 请求

os.system("curl " + URL + " -H 'Content-Type: application/json' -d '" + array_str[2] + "' ")

也没啥注意的,记住格式就好。

完整代码

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
import sys
import time

LOG_MARK = ":---:"
# 中国移动线上报警群URL
URL = 'https://qyapi.weixin.qq.com/xxxxxxxxxxxxxxxxxxxxxxx'
TIME = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))

def main():
    t2,t3 = time_time()
    type_1_message(t2,t3)

def time_time():
    T = time.time()
    t2 = (int(round(T * 1000)))
    t3 = (int(round(T * 1000 - 5 * 60 * 1000)))
    return t2, t3

def send_message(message):
    os.system("curl " + URL + " -H 'Content-Type: application/json' -d '" + message + "' ")

def scp_monitor_log():
    ssh_address = "xxx.xxx.xxx.xxx"
    logs_address = "/data/logs/wxWordMonitorLog/wxWordMonitorLog"
    os.system("scp " + ssh_address + ":" + logs_address + " ./wxWordMonitorLog")

def type_1_message(t2,t3):
    scp_monitor_log()
    print ("----------------------------任务开始  时间:" + TIME + "-------------------------------------")
    # print (time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
    file = open("wxWordMonitorLog", 'r')
    for line in file:
        print ('\n' * 3)
        print (line)
        array_str = line.split(LOG_MARK)
        send_type_int = int(array_str[0])
        send_type_str = str(send_type_int)
        time_stamp_int = int(array_str[1])
        time_stamp_str = str(time_stamp_int)
        if send_type_int == 1 and t3 <= time_stamp_int <= t2:
            print (send_type_str)
            print (time_stamp_str)
            print (array_str[2])
            send_message(array_str[2])
            print ("curl " + URL + " -H 'Content-Type: application/json' -d '" + array_str[2] + "' ")
        else:
            print (time_stamp_str + "当前日志时间不在检查时间内" + array_str[2])
    file.close()

    print ("----------------------------任务结束--------------------------------------------------------")

    os.system("rm -rf ./wxWordMonitorLog")

if __name__ == '__main__':
    main()

你可能感兴趣的:(Python)