ITPub博客

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

Python脚本实现Linux系统日志巡检

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

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

优质文章推荐

↓ ↓ ↓ ↓ ↓

Linux系统初始化脚本

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

Linux系统初始化脚本之二

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

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

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

在当今高度互联的网络环境中,运维工程师需要面对大量设备和复杂的网络架构,确保网络的稳定性和安全性成为一项重要的任务。为了提高效率、降低错误,并及时发现潜在的问题,日志巡检发挥着重要作用。
应用场景
「日志巡检脚本」适用于各种规模的网络环境,包括企业内部网络、数据中心、云平台等。以下是几个典型的应用场景:
1、故障排查与预防:
网络设备产生的日志记录了丰富的信息,包括设备运行状态、错误信息、异常事件等。使用「日志巡检脚本」,运维工程师可以自动巡检设备日志,分析关键信息,及时发现潜在问题,并采取相应措施进行故障排查和预防。
2、安全事件监测:
网络安全对于企业和组织而言至关重要。通过自动化分析设备日志,「日志巡检脚本」能够帮助运维工程师及时发现安全事件和异常行为,如入侵尝试、异常登录等,提供及时的安全响应和处理。
3、性能优化:
设备的性能问题可能会导致网络延迟、故障和性能下降。使用「日志巡检脚本」,可以自动分析设备日志中的性能指标,如CPU利用率、内存使用情况等,及时发现潜在的性能瓶颈,进行优化和调整,提升网络性能和响应能力。
4、合规与审计:
许多行业和组织需要遵守合规要求并进行审计。「日志巡检脚本」可以帮助运维工程师自动分析设备日志,提取符合合规要求的关键信息,生成报告和日志记录,为合规性审计提供支持。

脚本示例

import paramikoimport jsonimport loggingimport concurrent.futures
# 配置文件路径CONFIG_FILE = 'devices.json'
# 日志配置LOG_FILE = 'automation.log'LOG_LEVEL = logging.INFO
# 连接超时时间(秒)CONNECT_TIMEOUT = 10
# 配置日志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 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 main(): config = read_config()
if config: with concurrent.futures.ThreadPoolExecutor() as executor: futures = [] for device in config['devices']: logging.info(f"正在检查设备 {device['host']} 的状态...") futures.append(executor.submit(check_device_status, device))
for future in concurrent.futures.as_completed(futures): future.result()
with concurrent.futures.ThreadPoolExecutor() as executor: futures = [] for device in config['devices']: logging.info(f"正在配置设备 {device['host']}...") futures.append(executor.submit(configure_device, device))
for future in concurrent.futures.as_completed(futures): future.result()
with concurrent.futures.ThreadPoolExecutor() as executor: futures = [] for device in config['devices']: logging.info(f"正在进行故障排除...") futures.append(executor.submit(troubleshoot_device, device))
for future in concurrent.futures.as_completed(futures): future.result()
logging.info("脚本执行完毕")

if __name__ == '__main__':    main()
使用方式:
1、配置设备信息:将需要巡检的设备信息配置到脚本的设备列表中,包括设备IP、用户名、密码等(生产环境最好用免密)。
2、配置巡检规则:根据需求配置巡检规则,如关键词匹配规则、巡检频率等。
3、运行脚本:在终端中执行脚本命令,脚本将自动连接设备、收集并分析设备日志,并输出巡检结果。
4、查看结果与处理:根据脚本输出的结果,运维工程师可以快速定位和处理设备的异常情况,进行故障排查、安全处理或性能优化等操作。

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

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

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



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

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

注册时间:2022-09-24

  • 博文量
    333
  • 访问量
    215236