coding:utf-8
from IPy import IP, IPint, IPSet
import configparser
from scapy.all import *
import logging
import os
class CsapUtil(object):
def init(self):
pass
@staticmethod
def logger():
"""
定义1个日志输出器,将日志同时输出到控制台和文件run.log
:return:返回logger
"""
filename = 'run' + CsapUtil.LogUtil.log_time_format(format="%Y-%m-%d") + '.log'
pathname = os.path.dirname(__file__) + '/log/' + filename # 获取当前文件的所在路径
logger = logging.getLogger(__name__)
logger.setLevel(level=logging.DEBUG)
# 定义日志输出到文件的格式
handler = logging.FileHandler(pathname)
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s - %(message)s') # 输出日志的格式
handler.setFormatter(fmt=formatter)
# 定义日志打印到console的格式
console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
fmt1 = logging.Formatter('%(filename)s[line:%(lineno)d] - %(levelname)s - %(message)s') # 输出日志的格式
console.setFormatter(fmt=fmt1)
# 日志输出到文件和控制台
if not logger.handlers: # 解决日志重复打印的问题,每次初始化的时候都会添加到handlers,导致重复打印
logger.addHandler(console)
logger.addHandler(handler)
return logger
class BasicUtil(object):
def __init__(self):
pass
@staticmethod
def get_base_info(section, option, filename='base.conf'):
try:
filename = os.path.dirname(__file__) + '/config/' + filename
cf = configparser.ConfigParser()
cf.read(filename, encoding="utf-8")
return cf.get(section, option)
except Exception as e:
CsapUtil.logger().info("从配置文件{filename}中获取{section}下的{option}失败:{reason}".format(filename=filename,
section=section, option=option, reason=e))
class LogUtil(object):
def __init__(self):
pass
@staticmethod
def log_time_format(shift=0, log_type=1, format=None):
"""
将时间转换成指定的格式返回。
防火墙日志:Nov 29 07:13:58
探针日志:
:param shift:+n,向后n秒钟,-n:向前n秒钟
:param log_type:默认值为1,1:fw日志,2:nta日志, 3:绿盟日志
:param format:自定义返回的日志格式,如"%b %d %H:%M:%S %Y"
:return:返回想要的时间日志格式
"""
timestamp = int(time.time()) + shift
if log_type == 1:
if format != None:
try:
return time.strftime(format, time.localtime(timestamp))
except Exception as e:
CsapUtil.logger().info(e)
else:
return time.strftime("%b %d %H:%M:%S %Y", time.localtime(timestamp)) # Jun 15 15:20:12
elif log_type == 2:
return time.strftime("%b %d %H:%M:%S", time.localtime(timestamp)) # Jun 15 10:02:53
elif log_type == 3:
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(timestamp)) # 2020-06-15 16:48:14
else:
CsapUtil.logger().info("please check the input format")
@staticmethod
def log_send(syslog, resource, collector=[], sport=514, dport=514):
"""
日志发送
:param syslog:要发送的日志,字符串;
:param resource:日志源地址;
:param collector:采集器地址列表,['186.64.100.125']
:param sport:源端口,默认为514
:param dport:目的端口,默认为514
:return:
"""
try:
for dst in collector:
send(IP(src=resource, dst=dst) / UDP(sport=sport, dport=dport) / syslog.encode() )
# iface='Intel(R) Ethernet I210-T1 GbE NIC'
CsapUtil.logger().debug("{src}发送日志到{dst}:{msg}".format(src=resource, dst=collector, msg=syslog.encode()))
except Exception as e:
CsapUtil.logger().info(e)
class IpUtil(object):
"""
封装一些IP处理的函数
"""
@staticmethod
def ip2int(ip):
"""
将输入的IP转换成整型,ipv4和ipv6均可以
:param ip:如186.64.0.15
:return:返回3124756495
"""
try:
return IP(str(ip)).int()
except Exception as e:
CsapUtil.logger().info(e)
@staticmethod
def int2ip(ipint):
"""
输入整型转换成IP
:param ipint:
:return:
"""
try:
return str(IP(int(ipint)))
except Exception as e:
CsapUtil.logger().info(e)
if name == ‘main’:
# CsapUtil.IpUtil.ip2int(‘sdadsa’)
# CsapUtil.IpUtil.int2ip(‘dsadsa’)
print(CsapUtil.BasicUtil.get_base_info(‘info’, ‘ConsoleLevel1’))