首页 > 数据库 > 数据库开发技术 > Python脚本实现Linux系统日志分析
先放个链接,万一有人关注呢
↓ ↓ ↓ ↓ ↓
脚本示例
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 configexcept 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 clientexcept 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 Nonereturn 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 smtplibfrom email.mime.text import MIMETextmsg = MIMEText(message)msg['Subject'] = subjectmsg['From'] = MAIL_FROMmsg['To'] = MAIL_TOtry: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思议;如有侵权,请联系管理员删除。