ITPub博客

首页 > 数据库 > 数据库开发技术 > Python脚本实现Linux系统日志分析

Python脚本实现Linux系统日志分析

原创 数据库开发技术 作者:运维book思议 时间:2023-06-20 12:21:22 0 删除 编辑

先放个链接,万一有人关注呢

优质文章推荐

↓ ↓ ↓ ↓ ↓

Linux系统初始化脚本

能够监控100台服务器的磁盘利用率的脚本——16行代码实现

Linux系统初始化脚本之二

Linux系统巡检脚本——快速获取当前系统信息

Linux远程执行脚本——Python运维脚本

哪个Linux发行版会成为CentOS的平替?

运维工程师经常需要处理大量的日志数据,以监控系统状态、诊断故障、分析性能等。然而,手动处理这些日志数据是一项耗时且容易出错的任务。为了解决这个问题,日志分析脚本应运而生。
应用场景
1、故障排除: 
当系统出现故障或异常时,日志分析脚本可以帮助运维工程师快速定位问题的根本原因。通过分析相关日志,查找错误信息和异常行为,识别故障发生的时间和范围,从而加快故障排除的过程。
2、性能优化: 
通过分析系统和应用程序的日志,日志分析脚本可以帮助运维工程师发现性能瓶颈和优化机会。它可以识别响应时间过长的请求、频繁出现的错误、资源利用率异常等问题,并提供相应的建议和优化策略,从而提高系统的性能和稳定性。
3、安全监测: 
日志分析脚本可以对安全事件和威胁进行监测和分析。通过对安全日志和审计日志的分析,它可以识别潜在的安全漏洞、异常登录行为、恶意活动等,并生成警报或报告,帮助运维工程师及时采取措施,保护系统的安全。
4、日志审计和合规性: 
对于需要进行日志审计和合规性监测的行业,日志分析脚本是一种强大的工具。它可以对日志数据进行完整性检查、检测异常事件、生成合规性报告等,帮助运维工程师满足监管和合规性要求。

脚本示例

import paramikoimport jsonimport loggingimport osfrom concurrent.futures import ThreadPoolExecutor
# 配置文件路径CONFIG_FILE = 'devices.json'
# 日志配置LOG_FILE = 'automation.log'LOG_LEVEL = logging.INFO
# 并发线程数CONCURRENT_THREADS = 5
# 连接超时时间(秒)CONNECT_TIMEOUT = 10
# 备份目录BACKUP_DIR = 'backup'
# 邮件配置SMTP_HOST = 'smtp.example.com'SMTP_PORT = 587SMTP_USERNAME = 'your_username'SMTP_PASSWORD = 'your_password'MAIL_FROM = 'from@example.com'MAIL_TO = 'to@example.com'
# 配置日志logging.basicConfig(filename=LOG_FILE, level=LOG_LEVEL)
# 读取设备信息配置文件def read_config(): try: with open(CONFIG_FILE, 'r') as file: config = json.load(file) return config except FileNotFoundError: logging.error(f'配置文件 {CONFIG_FILE} 未找到') except json.JSONDecodeError: logging.error(f'配置文件 {CONFIG_FILE} 解析错误')
return None
# 创建备份目录def create_backup_dir(): if not os.path.exists(BACKUP_DIR): os.makedirs(BACKUP_DIR) logging.info(f'创建备份目录 {BACKUP_DIR}')
# 备份配置文件def backup_config(device): client = connect_device(device) if client: config_file = device['config_file'] backup_file = os.path.join(BACKUP_DIR, f'{device["host"]}_{config_file}') command = f'copy {config_file} {backup_file}'
output = execute_command(client, command) if output: logging.info(f"设备 {device['host']} 配置文件备份成功: {backup_file}") else: logging.error(f"设备 {device['host']} 配置文件备份失败")
# 连接设备def connect_device(device): client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try: client.connect( hostname=device['host'], username=device['username'], key_filename=device['key_filename'], timeout=CONNECT_TIMEOUT ) return client except paramiko.AuthenticationException: logging.error(f"无法连接设备 {device['host']}: 身份验证失败") except paramiko.SSHException as e: logging.error(f"无法连接设备 {device['host']}: {str(e)}") except Exception as e: logging.error(f"无法连接设备 {device['host']}: {str(e)}")
return None
# 执行命令def execute_command(client, command): try: stdin, stdout, stderr = client.exec_command(command, timeout=CONNECT_TIMEOUT) output = stdout.read().decode('utf-8') error = stderr.read().decode('utf-8') client.close()
if error: logging.error(f"命令执行出错: {error}") return None
return output.strip() except Exception as e: logging.error(f"命令执行出错: {str(e)}") return None
# 检查设备状态def check_device_status(device): client = connect_device(device)
if client: output = execute_command(client, 'show interfaces') if output: logging.info(f"设备 {device['host']} 状态正常") logging.info(output)
# 配置设备def configure_device(device): client = connect_device(device)
if client: config_commands = [ 'interface eth0', 'ip address 192.168.1.1 255.255.255.0', 'no shutdown' ]
for command in config_commands: execute_command(client, command)
logging.info(f"设备 {device['host']} 配置已更新")
# 故障排除def troubleshoot_device(device): client = connect_device(device)
if client: output = execute_command(client, 'show logs') if output: logging.info(f"设备 {device['host']} 故障排除日志:") logging.info(output)
# 发送邮件def send_email(subject, message): import smtplib from email.mime.text import MIMEText
msg = MIMEText(message) msg['Subject'] = subject msg['From'] = MAIL_FROM msg['To'] = MAIL_TO
try: with smtplib.SMTP(SMTP_HOST, SMTP_PORT) as server: server.starttls() server.login(SMTP_USERNAME, SMTP_PASSWORD) server.sendmail(MAIL_FROM, MAIL_TO, msg.as_string()) logging.info("邮件发送成功") except Exception as e: logging.error(f"邮件发送失败: {str(e)}")
# 主函数def main(): config = read_config()
if config: create_backup_dir()
with ThreadPoolExecutor(max_workers=CONCURRENT_THREADS) as executor: for device in config['devices']: logging.info(f"正在备份设备 {device['host']} 的配置文件...") executor.submit(backup_config, device)
logging.info(f"正在检查设备 {device['host']} 的状态...") executor.submit(check_device_status, device)
logging.info(f"正在配置设备 {device['host']}...") executor.submit(configure_device, device)
logging.info(f"正在对设备 {device['host']} 进行故障排除...") executor.submit(troubleshoot_device, device)
send_email("自动化运维脚本执行完成", "脚本执行完成,请查看日志文件") logging.info("自动化运维脚本执行完成")
# 执行主函数if __name__ == '__main__':    main()

通过日志分析脚本,运维工程师可以将繁琐的日志处理任务交给自动化工具来完成,从而将更多的时间和精力投入到系统优化和问题解决上。这样,他们能够更好地应对系统故障、提升系统性能、确保系统安全,并满足合规性要求。日志分析脚本成为运维工程师的得力助手,为运维工作流程带来了便捷和效率的提升。

结束!如有不足之处,欢迎指正!

来不及解释了,快上车!(加我微信拉你进群):

欢迎新的小伙伴加入!在这里,我们鼓励大家积极参与群内讨论和交流,分享自己的见解和经验,一起学习和成长。同时,也欢迎大家提出问题和建议,让我们不断改进和完善这个平台。


原文作者:运维book思议;如有侵权,请联系管理员删除。

请登录后发表评论 登录
全部评论

注册时间:2022-09-24

  • 博文量
    333
  • 访问量
    215236