背景
因为工作需要,每天要对系统内的多台linux服务器做巡检,主要检查的内容有CPU,内存,进程,硬盘空间等。
源码
Python/ target=_blank class=infotextkey>Python部分
paramiko模块需要自己安装
pip install paramiko
#-*- coding:utf8 -*-
import paramiko
import subprocess
import datetime
# 定义服务器列表和巡检脚本路径
servers = [
{'hostname': 'server1', 'ip': '192.168.1.254', 'username': 'root', 'password': 'root@1234'},
{'hostname': 'server2', 'ip': '192.168.1.253', 'username': 'root', 'password': 'root@1234'},
# 添加更多服务器
]
script_path = 'D:\python_project\database_export\xj.sh' # 替换为您的巡检脚本路径
# 遍历服务器列表进行巡检
for server in servers:
try:
# 建立SSH连接
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(server['ip'], username=server['username'], password=server['password'])
# 上传巡检脚本至远程服务器
sftp = ssh.open_sftp()
sftp.put(script_path, 'script.sh')
sftp.close()
# 执行巡检脚本
stdin, stdout, stderr = ssh.exec_command('chmod +x script.sh && ./script.sh')
output = stdout.read().decode()
# 打印巡检结果
print(f"Server: {server['hostname']}")
print(f"Output: {output}")
print("----------------------------------------")
#写入日志out.log
current_time = datetime.datetime.now()
logout = current_time.strftime("%Y-%m-%d.txt")
with open(logout,"a",encoding="utf-8") as file:
file.write(f"Server: {server['hostname']}rn")
file.write(f"Output: {output}")
# 关闭SSH连接
ssh.close()
#屏幕打印,如果不需要则注释并注释上面try
except paramiko.AuthenticationException as e:
print(f"FAIled to connect to {server['hostname']}: {str(e)}")
except paramiko.SSHException as e:
print(f"Error occurred while connecting to {server['hostname']}: {str(e)}")
shell部分
#!/bin/bash
function RED(){
#在页面上打印成红色
# echo -e "