python生产nginx日志
最近在生产中使用到了elk框架,为了测试部署编写此脚本生成假数据。
import os
import random
import datetime
import sys
import time
print(sys.platform)
print(sys.argv[0])
LOG_SUM = 200_000_0
BACK_CODES_LIST = ["200", "302", "304", "400", "403", "404", "502"]
TIME_ZONE_LIST = ["-1200", "-1100", "-1000", "-0900", "-0800", "-0700", "-0600",
"-0500", "-0400", "-0300", "-0200", "-0100", "0000", "+0100",
"+0200", "+0300", "+0400", "+0500", "+0600", "+0700", "+0800",
"+0900", "+1000", "+1100"]
REQUEST_PROTOCOL = ["HTTP/1.0", "HTTP/1.1", "HTTP/2.0", "HTTP/3.0"]
REQUEST_METHOD = ["GET", "POST", "PUT", "HEAD", "DELETE", "OPTIONS", "TRACE"]
USER_AGENTS = [
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 "
"Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.164 "
"Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:90.0) Gecko/20100101 Firefox/90.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36"]
def generate_random_ip():
def get_rand_sum():
return random.randint(1, 239)
num1 = random.randint(1, 239)
while num1 == 10 or num1 == 192 or num1 == 172:
num1 = get_rand_sum()
num2 = random.randint(0, 255)
num3 = random.randint(0, 255)
num4 = random.randint(0, 254)
return "{}.{}.{}.{}".format(num1, num2, num3, num4)
def get_random_time():
timestamp = datetime.datetime.now().timestamp() - random.randint(0, 100_000_00)
date_time = datetime.datetime.fromtimestamp(timestamp)
date_time_str = date_time.strftime("%d/%b/%Y:%H:%M:%S")
return '[' + date_time_str + ']'
with open('nginx_assess_log.log', 'a') as f:
flag = 0
for flag in range(0, LOG_SUM):
f.write((generate_random_ip() + ' -- ' + get_random_time() + '\"'
+ random.choice(REQUEST_METHOD) + ' ' + '/' + ' '
+ random.choice(REQUEST_PROTOCOL) + '"' + " " +
random.choice(BACK_CODES_LIST) + " " +
random.randint(0, 2000_00).__str__() + ' "-"' + " "
+ random.choice(USER_AGENTS) + " " + '"-"' + '\n'))
flag = flag + 1
if flag == LOG_SUM:
print(flag.__str__() + " " + "pieces of data were generated in ./")
f.close()
sys.exit()
else:
print("erorr!!!")
print("Rollbacking")
f.close()
os.remove("./nginx_assess_log.log")
sys.exit(-1)