import paramiko
import json
import logging
from datetime import datetime
import os
import traceback
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("huawei_inspection.log"),
logging.StreamHandler()
]
)
devices = [
{
"host": "192.168.1.1",
"username": "admin",
"password": "Admin@123",
"port": 22,
"device_type": "Huawei"
}
]
commands = [
"display cpu-usage",
"display memory-usage",
"display interface",
"display current-configuration | include sysname",
"display version",
"display health",
]
def collect_data(host, username, password, port, device_type="Huawei"):
ssh = paramiko.SSHClient()
try:
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(
host,
port=port,
username=username,
password=password,
timeout=10,
auth_timeout=10
)
data = {
"host": host,
"device_type": device_type,
"timestamp": str(datetime.now()),
"commands_output": {}
}
for cmd in commands:
try:
stdin, stdout, stderr = ssh.exec_command(cmd, timeout=15)
output = stdout.read().decode('utf-8', errors='ignore').strip()
error = stderr.read().decode('utf-8', errors='ignore').strip()
data["commands_output"][cmd] = {
"output": output,
"error": error
}
if error:
logging.warning(f"Command '{cmd}' on {host} produced error: {error}")
except Exception as cmd_error:
logging.error(f"Error executing command '{cmd}' on {host}: {cmd_error}")
data["commands_output"][cmd] = {
"output": "",
"error": str(cmd_error)
}
return data
except paramiko.AuthenticationException:
logging.error(f"Authentication failed for {host}")
return None
except paramiko.SSHException as ssh_error:
logging.error(f"SSH connection to {host} failed: {ssh_error}")
return None
except Exception as e:
logging.error(f"Unexpected error connecting to {host}: {e}")
logging.error(traceback.format_exc())
return None
finally:
try:
ssh.close()
except:
pass
def main():
os.makedirs("inspection_data", exist_ok=True)
results = []
for device in devices:
logging.info(f"开始采集设备: {device['host']}")
device_data = collect_data(**device)
if device_data:
results.append(device_data)
logging.info(f"成功采集设备 {device['host']} 的数据")
else:
logging.error(f"无法采集设备 {device['host']} 的数据")
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
output_file = f"inspection_data/huawei_inspection_{timestamp}.json"
try:
with open(output_file, "w", encoding='utf-8') as f:
json.dump(results, f, ensure_ascii=False, indent=2)
logging.info(f"数据已保存到 {output_file}")
except Exception as e:
logging.error(f"保存数据时发生错误: {e}")
if __name__ == "__main__":
main()