服务器巡检不再头疼:一键脚本批量检查,高效
时间:2026-09-16 22:51 来源:未知 人气:
手工巡检需要逐台登录服务器,耗费大量时间和精力,同时容易因操作疏漏而遗漏关键指标,导致数据不统一、风险增大;而自动化巡检利用脚本批量采集数据,实现实时监控和标准化输出,大幅提升效率并降低人为错误,从而为系统稳定运行提供坚实保障。
为了解决这些问题,我们可以使用自动化脚本来批量巡检服务器,并自动生成巡检表。如下图所示:
自动化巡检的优势
相比手工巡检,使用脚本进行自动化巡检具有以下优势:
- 批量执行:一次性检查所有服务器,提升巡检效率;
- 减少人工干预:降低人为错误,提高数据准确性;
- 标准化输出:巡检数据统一格式,方便存储和分析;
- 可扩展性:脚本可根据需求扩展,支持更多巡检项。
编写批量巡检脚本
为了让脚本更灵活,适应更多情况,我们换了个新思路:让用户自己定义要检查的项目,并用正则表达式来提取结果,同时并定义展示的模板。数据类似如下:
# 定义巡检配置项
inspection_configs=[
{
"name": "内核版本",
"command": "uname -r", # 修正命令为获取内核版本的正确命令
"regex_pattern": r"^(\d+\.\d+\.\d+-\d+-\w+)", # 精确匹配
"format_template": "内核版本: {0}"
},
....
]
解析:
- command: 是指定要执行的命令,例如上述的uname -r。
- regex_pattern:是指通过正则匹配想要的结果。
- format_template:是指在巡检表展示的数据。例如内核版本: {0},其中{0}会被填入匹配到的真实数据。
通过以下的ssh_connect函数进行远程SSH连接到服务,然后,再通过execute_inspection函数执行巡检命令。
def ssh_connect(server):
"""建立SSH连接"""
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(
hostname=server["hostname"],
port=server["port"],
username=server["username"],
password=server["password"]
)
return client
except Exception as e:
print(f"连接{server['hostname']}失败: {str(e)}")
return None
def execute_inspection(client, config):
"""执行单个巡检项并解析结果"""
stdin, stdout, stderr = client.exec_command(config["command"])
output = stdout.read().decode()
error = stderr.read().decode()
if error:
print(f"命令执行错误: {config['command']}\n{error}")
return None
#使用正则表达式提取数据
match = re.search(config["regex_pattern"], output)
if match:
return match.groups()
else:
print(f"未匹配到数据: {config['name']}")
return None
本文标签: