9月 22

python获取 需要的 随机数格式

要产生自己需要的随机数格式。python2.7.

# 产生随机数,状态有三种,num为数字,let为字母,mix为混合
def create_random(rand_type, rand_len):
    import random
    list_num = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
    list_let = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "g", \
                "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", \
                "u", "v", "w", "x", "y", "z"]
    rand_str = ""
    if rand_type == "num":
        for ll in xrange(rand_len):
            rand_str = "%s%s" % (rand_str, random.sample(list_num, 1)[0])
    elif rand_type == "let":
        for ll in xrange(rand_len):
            rand_str = "%s%s" % (rand_str, random.sample(list_let, 1)[0])
    elif rand_type == "mix":
        list_all = list_num + list_let
        for ll in xrange(rand_len):
            rand_str = "%s%s" % (rand_str, random.sample(list_all, 1)[0])
    else:
        rand_str =""
    return rand_str
9月 10

python格式化n天前日期

需要获取n天前,或者n天后的信息。比如获取一天前,格式化为2015-10-09的格式。

导入time,time.time()为unixtime,60*60*24就是60秒乘60分钟乘24小时,减去一天就是一天前,加上一天就是后一天。

import time
time.strftime("%Y-%m-%d", time.localtime(time.time()-60*60*24))

可以自己计算n年,n月,n小时,n秒。

8月 11

python 中 json读写

import json

# 读取json文件
def read_json(file_name):
    json_file = open("%s" % file_name, "rb")
    get_json = json.load(json_file)
    json_file.close()
    return get_json

# 写入json文件
def write_json(file_name, json_context):
    json_file = open("%s" % file_name, "wb")
    to_json = json.dumps(json_context)
    json_file.write(to_json)
    json_file.close()
6月 23

zabbix 异常IP地址登陆告警

首先在服务器上建立白名单
比如连接是
http://www.simonzhang.net/whitelist.txt
可以访问的ip地址,一行一个
部分zabbix检查python代码如下。

login_status = 0
import urllib2
get_whitelist = urllib2.urlopen("http://www.simonzhang.net/whitelist.txt").read()
_whitelist = get_whitelist[:-1].split('\n')
get_last_list = os.popen("/usr/bin/last -10|head -10|awk ' ''{print $3}'").readlines()
for login_ip in get_last_list:
    if login_ip[:-1] not in _whitelist:
        login_status = 1
return login_status

如果有在白名单外的IP登陆则告警。因为是内网每5秒检查一下,白名单很小,所以不考虑访问频率问题。