首页 > 应用开发 > IT综合 > 服务器监控解决方案:Ward工具与远程访问部署指南
# 服务器监控解决方案:Ward工具与远程访问部署指南
在服务器运维工作中,实时掌握系统状态是确保服务稳定性的关键。传统监控工具往往配置复杂或界面不够直观,而Ward作为一款轻量级服务器监控工具,提供了简洁美观的Web界面,结合远程访问技术,可以实现随时随地监控服务器状态的需求。
## Ward监控工具部署与配置
Ward是基于Java开发的服务器监控工具,支持多种Linux发行版。以下是完整的部署流程:
```bash
#!/bin/bash
# ward_install.sh - Ward监控工具安装脚本
echo "=== Ward监控工具安装部署 ==="
# 1. 环境检查
echo "1. 检查系统环境..."
if ! command -v java &> /dev/null; then
echo "Java未安装,正在安装OpenJDK 11..."
sudo apt update
sudo apt install -y openjdk-11-jdk
fi
# 验证Java版本
java_version=$(java -version 2>&1 | head -1 | cut -d'"' -f2)
echo "Java版本: $java_version"
# 2. 下载Ward
echo "2. 下载Ward监控工具..."
WARD_VERSION="1.8.6"
WARD_URL="https://github.com/B-Software/Ward/releases/download/v${WARD_VERSION}/ward-v${WARD_VERSION}.jar"
DOWNLOAD_DIR="/opt/ward"
sudo mkdir -p $DOWNLOAD_DIR
cd $DOWNLOAD_DIR
if [ ! -f "ward-v${WARD_VERSION}.jar" ]; then
sudo wget $WARD_URL
echo "Ward下载完成"
else
echo "Ward已存在,跳过下载"
fi
# 3. 创建系统服务
echo "3. 配置系统服务..."
sudo tee /etc/systemd/system/ward.service << EOF
[Unit]
Description=Ward Server Monitoring
After=network.target
[Service]
Type=simple
User=ward
Group=ward
WorkingDirectory=/opt/ward
ExecStart=/usr/bin/java -jar ward-v${WARD_VERSION}.jar
Restart=on-failure
RestartSec=10
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=ward
# 安全配置
NoNewPrivileges=true
ProtectSystem=strict
PrivateTmp=true
ReadWritePaths=/opt/ward/logs
# 资源限制
MemoryMax=512M
CPUQuota=50%
[Install]
WantedBy=multi-user.target
EOF
# 4. 创建专用用户
echo "4. 创建专用用户..."
sudo useradd -r -s /usr/sbin/nologin ward
sudo chown -R ward:ward $DOWNLOAD_DIR
# 5. 配置Ward参数
echo "5. 配置Ward监控参数..."
sudo tee /opt/ward/application.properties << EOF
# Ward服务器配置
server.port=4000
server.address=0.0.0.0
# 监控配置
ward.monitored-servers=localhost
ward.refresh-rate=5
# 安全配置
ward.authentication.enabled=true
ward.authentication.username=admin
ward.authentication.password=\${WARD_PASSWORD:ward123456}
# 日志配置
logging.file.name=/opt/ward/logs/ward.log
logging.level.com.bsoftware.ward=INFO
# 数据保留
ward.data-retention-days=7
EOF
# 6. 设置环境变量
echo "6. 设置环境变量..."
sudo tee /etc/default/ward << 'EOF'
# Ward环境配置
WARD_PORT=4000
WARD_HOST=0.0.0.0
WARD_PASSWORD=$(openssl rand -base64 12)
JAVA_OPTS="-Xms128m -Xmx256m"
EOF
# 7. 创建日志目录
echo "7. 创建日志目录..."
sudo mkdir -p /opt/ward/logs
sudo chown ward:ward /opt/ward/logs
# 8. 启用并启动服务
echo "8. 启动Ward服务..."
sudo systemctl daemon-reload
sudo systemctl enable ward.service
sudo systemctl start ward.service
# 9. 验证安装
echo "9. 验证安装..."
sleep 3
if sudo systemctl is-active --quiet ward.service; then
echo "✓ Ward服务运行正常"
# 获取访问信息
WARD_PID=$(sudo systemctl show -p MainPID ward.service | cut -d= -f2)
LISTEN_PORT=$(sudo ss -tlnp | grep "java" | grep ":4000" | wc -l)
echo "服务PID: $WARD_PID"
echo "监听端口: 4000"
echo "访问地址: http://$(hostname -I | awk '{print $1}'):4000"
echo "默认用户名: admin"
echo "密码请查看: /etc/default/ward 中的WARD_PASSWORD"
else
echo "✗ Ward服务启动失败"
sudo systemctl status ward.service --no-pager
fi
echo ""
echo "=== Ward安装完成 ==="
```
## 安全配置与优化
增强Ward的安全性和性能:
```bash
#!/bin/bash
# ward_security_config.sh
echo "=== Ward安全加固配置 ==="
# 1. 配置防火墙
echo "1. 配置防火墙规则..."
if command -v ufw &> /dev/null; then
sudo ufw allow 4000/tcp comment "Ward监控界面"
echo "UFW防火墙规则已添加"
elif command -v firewall-cmd &> /dev/null; then
sudo firewall-cmd --permanent --add-port=4000/tcp
sudo firewall-cmd --reload
echo "FirewallD防火墙规则已添加"
else
echo "未检测到防火墙工具,请手动配置端口4000"
fi
# 2. 配置Nginx反向代理(可选)
echo "2. 配置Nginx反向代理..."
if command -v nginx &> /dev/null; then
sudo tee /etc/nginx/sites-available/ward << 'EOF'
server {
listen 80;
server_name monitor.yourdomain.com;
# 强制HTTPS重定向(如果启用SSL)
# return 301 https://$server_name$request_uri;
location / {
proxy_pass http://localhost:4000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# WebSocket支持
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
# 超时设置
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}
# 静态文件缓存
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
# 安全头部
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
}
EOF
sudo ln -sf /etc/nginx/sites-available/ward /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx
echo "Nginx反向代理配置完成"
fi
# 3. 配置SSL/TLS(使用Let's Encrypt)
echo "3. 配置SSL证书..."
read -p "是否配置SSL证书?(y/n): " configure_ssl
if [[ $configure_ssl == "y" ]] && command -v certbot &> /dev/null; then
sudo certbot --nginx -d monitor.yourdomain.com
echo "SSL证书配置完成"
fi
# 4. 设置监控告警
echo "4. 配置系统监控告警..."
sudo tee /opt/ward/monitoring/alerts.sh << 'EOF'
#!/bin/bash
# Ward监控告警脚本
THRESHOLDS=(
"cpu_usage 90"
"memory_usage 85"
"disk_usage 90"
"load_average 5"
)
check_thresholds() {
local alert_messages=()
# 检查CPU使用率
local cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d'%' -f1)
if (( $(echo "$cpu_usage > 90" | bc -l) )); then
alert_messages+=("CPU使用率过高: ${cpu_usage}%")
fi
# 检查内存使用率
local mem_info=$(free | grep Mem)
local mem_total=$(echo $mem_info | awk '{print $2}')
local mem_used=$(echo $mem_info | awk '{print $3}')
local mem_percent=$(echo "scale=2; $mem_used/$mem_total*100" | bc)
if (( $(echo "$mem_percent > 85" | bc -l) )); then
alert_messages+=("内存使用率过高: ${mem_percent}%")
fi
# 检查磁盘使用率
local disk_usage=$(df -h / | awk 'NR==2 {print $5}' | sed 's/%//')
if [ $disk_usage -gt 90 ]; then
alert_messages+=("磁盘使用率过高: ${disk_usage}%")
fi
# 如果有告警,发送通知
if [ ${#alert_messages[@]} -gt 0 ]; then
send_alert "${alert_messages[@]}"
fi
}
send_alert() {
local message="服务器监控告警:\n"
for msg in "$@"; do
message+="• $msg\n"
done
message+="\n时间: $(date '+%Y-%m-%d %H:%M:%S')\n主机: $(hostname)"
# 发送邮件通知(需要配置邮件服务器)
# echo -e "$message" | mail -s "服务器监控告警" admin@example.com
# 发送到Slack(示例)
# curl -X POST -H 'Content-type: application/json' \
# --data "{\"text\":\"$message\"}" \
# YOUR_SLACK_WEBHOOK_URL
# 记录到日志
echo "[ALERT] $(date) - $message" >> /opt/ward/logs/alerts.log
# 发送系统通知
echo -e "$message" | wall
}
# 主循环
while true; do
check_thresholds
sleep 300 # 每5分钟检查一次
done
EOF
sudo chmod +x /opt/ward/monitoring/alerts.sh
echo "告警脚本配置完成"
# 5. 配置日志轮转
echo "5. 配置日志管理..."
sudo tee /etc/logrotate.d/ward << 'EOF'
/opt/ward/logs/*.log {
daily
missingok
rotate 30
compress
delaycompress
notifempty
create 640 ward ward
sharedscripts
postrotate
systemctl reload ward > /dev/null 2>&1 || true
endscript
}
EOF
echo "=== 安全配置完成 ==="
```
## 远程访问配置
使用内网穿透工具实现安全的远程访问:
```bash
#!/bin/bash
# ward_remote_access.sh
echo "=== Ward远程访问配置 ==="
# 1. 安装内网穿透工具
echo "1. 安装内网穿透客户端..."
TOOL_DIR="/opt/remote-access"
sudo mkdir -p $TOOL_DIR
cd $TOOL_DIR
# 下载客户端(以cpolar为例)
if [ ! -f "cpolar" ]; then
echo "下载内网穿透客户端..."
# 请从官网获取实际的下载链接
# wget https://static.cpolar.com/downloads/releases/latest/cpolar-stable-linux-amd64.tar.gz
# tar -zxvf cpolar-stable-linux-amd64.tar.gz
# sudo mv cpolar /usr/local/bin/
echo "请手动下载并配置内网穿透客户端"
else
echo "客户端已存在"
fi
# 2. 配置隧道
echo "2. 配置Ward访问隧道..."
sudo tee /etc/systemd/system/ward-tunnel.service << 'EOF'
[Unit]
Description=Ward Remote Access Tunnel
After=network.target ward.service
Wants=ward.service
[Service]
Type=simple
User=ward
Group=ward
WorkingDirectory=/opt/remote-access
# 配置认证(使用环境变量或配置文件)
Environment="AUTH_TOKEN=your_actual_token_here"
Environment="TUNNEL_REGION=us"
# 启动命令 - 创建HTTP隧道
ExecStart=/usr/local/bin/cpolar http 4000 --hostname=ward-monitor --region=${TUNNEL_REGION}
Restart=on-failure
RestartSec=5
# 安全配置
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=full
[Install]
WantedBy=multi-user.target
EOF
# 3. 创建环境配置文件
echo "3. 创建环境配置文件..."
sudo tee /etc/default/ward-tunnel << 'EOF'
# 隧道配置
TUNNEL_REGION=us
WARD_LOCAL_PORT=4000
WARD_TUNNEL_HOSTNAME=ward-$(hostname -s)
# 安全配置(从安全位置读取token)
AUTH_TOKEN_FILE=/etc/ward/tunnel_token
EOF
# 4. 配置自动启动脚本
echo "4. 配置启动脚本..."
sudo tee /opt/remote-access/start-tunnel.sh << 'EOF'
#!/bin/bash
# Ward隧道启动脚本
# 加载配置
if [ -f /etc/default/ward-tunnel ]; then
. /etc/default/ward-tunnel
fi
# 读取认证token
if [ -f "$AUTH_TOKEN_FILE" ]; then
AUTH_TOKEN=$(cat "$AUTH_TOKEN_FILE")
export AUTH_TOKEN
fi
# 验证Ward服务状态
if ! systemctl is-active --quiet ward.service; then
echo "错误: Ward服务未运行"
exit 1
fi
# 验证端口监听
if ! ss -tln | grep -q ":${WARD_LOCAL_PORT} "; then
echo "错误: Ward未在端口 ${WARD_LOCAL_PORT} 监听"
exit 1
fi
# 启动隧道
echo "启动Ward远程访问隧道..."
echo "区域: ${TUNNEL_REGION}"
echo "本地端口: ${WARD_LOCAL_PORT}"
echo "主机名: ${WARD_TUNNEL_HOSTNAME}"
exec /usr/local/bin/cpolar authtoken "${AUTH_TOKEN}"
exec /usr/local/bin/cpolar http ${WARD_LOCAL_PORT} \
--hostname=${WARD_TUNNEL_HOSTNAME} \
--region=${TUNNEL_REGION} \
--log=stdout\read.nexgo.vip\map.nexgo.vip\
EOF
sudo chmod +x /opt/remote-access/start-tunnel.sh
# 5. 配置健康检查
echo "5. 配置健康检查..."
sudo tee /opt/remote-access/health-check.sh << 'EOF'
#!/bin/bash
# 隧道健康检查脚本
# 检查本地服务
check_local_service() {
local response=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:4000/health)
if [ "$response" = "200" ]; then
return 0
else
return 1
fi
}
# 检查隧道连接
check_tunnel_status() {
# 这里需要根据具体的内网穿透工具API实现
# 示例:检查隧道是否活跃
if pgrep -f "cpolar http 4000" > /dev/null; then
return 0
else
return 1
fi
}
# 发送状态报告
send_status_report() {
local status=$1
local message=$2
local report="{
\"timestamp\": \"$(date -Iseconds)\",
\"hostname\": \"$(hostname)\",
\"service\": \"ward-tunnel\",
\"status\": \"$status\",
\"message\": \"$message\",
\"cpu_usage\": \"$(top -bn1 | grep "Cpu(s)" | awk '{print $2}')\",
\"memory_usage\": \"$(free -m | awk 'NR==2{printf "%.2f%%", $3*100/$2}')\"
}"
# 发送到监控系统(示例)
# curl -X POST -H "Content-Type: application/json" \
# -d "$report" \
# https://your-monitoring-system/api/status
}qm.nexgo.vip\jk.nexgo.vip\mp.nexgo.vip\
# 主检查逻辑
if check_local_service && check_tunnel_status; then
echo "状态正常"
send_status_report "healthy" "所有服务运行正常"
exit 0
else
echo "状态异常"
send_status_report "unhealthy" "服务检查失败"
# 尝试重启服务
systemctl restart ward-tunnel.service
sleep 5
# 再次检查
if check_local_service && check_tunnel_status; then
send_status_report "recovered" "服务已恢复"
fi
exit 1
fi
EOF
sudo chmod +x /opt/remote-access/health-check.sh
# 6. 启用并启动服务
echo "6. 启动隧道服务..."
sudo systemctl daemon-reload
sudo systemctl enable ward-tunnel.service
read -p "是否立即启动隧道服务?(y/n): " start_now
if [[ $start_now == "y" ]]; then
sudo systemctl start ward-tunnel.service
echo "服务启动命令已执行"
# 等待服务启动
sleep 3
# 检查服务状态
if sudo systemctl is-active --quiet ward-tunnel.service; then
echo "✓ 隧道服务运行正常"
# 获取隧道信息
echo "检查隧道状态..."
# 这里需要根据具体工具获取隧道URL
echo "远程访问地址将在隧道建立后显示"
else
echo "✗ 隧道服务启动失败"
sudo journalctl -u ward-tunnel.service -n 20 --no-pager
fi
fi
echo ""
echo "=== 远程访问配置完成 ==="
echo "请确保已配置正确的认证令牌"
echo "配置文件位置: /etc/default/ward-tunnel"
```
## 监控仪表板自定义配置
扩展Ward的监控能力:
```yaml
# custom_monitoring_config.yaml
ward:
# 基本配置
server:
name: "生产服务器监控"
refresh_rate: 5 # 刷新间隔(秒)
theme: "dark" # 界面主题: dark/light
# 监控指标配置
metrics:
cpu:
enabled: true
detailed: true # 显示每个核心的使用率
threshold_warning: 70
threshold_critical: 90
memory:
enabled: true
show_swap: true
threshold_warning: 75
threshold_critical: 90
disk:
enabled: true
monitored_paths:
- "/"
- "/var"
- "/home"
threshold_warning: 80
threshold_critical: 95
network:
enabled: true
interfaces:
- "eth0"
- "eth1"
show_bandwidth: true
show_connections: true
processes:
enabled: true
max_display: 20
sort_by: "cpu" # cpu/memory/name
docker:
enabled: true
socket_path: "/var/run/docker.sock"
show_all_containers: true
services:
enabled: true
monitored_services:
- "nginx"
- "mysql"
- "redis"
- "docker"
# 自定义监控插件
plugins:
# 数据库监控
database_monitoring:
mysql:
enabled: true
host: "localhost"
port: 3306
username: "monitor"
queries:
- "SHOW GLOBAL STATUS"
- "SHOW PROCESSLIST"
postgresql:
enabled: false
# 应用监控
application_monitoring:
web_servers:
nginx:
status_url: "http://localhost/nginx_status"
apache:
status_url: "http://localhost/server-status"
cache_servers:
redis:
host: "localhost"
port: 6379
message_queues:
rabbitmq:
api_url: "http://localhost:15672/api"
# 告警配置
alerts:
enabled: true
notification_methods:
email:
enabled: true
smtp_server: "smtp.example.com"
recipients:
- "admin@example.com"
slack:
enabled: false
webhook_url: ""
webhook:
enabled: true
url: "https://your-alert-system.com/webhook"
rules:
- name: "高CPU使用率"
condition: "cpu_usage > 90"
duration: "5m"
severity: "critical"
- name: "内存不足"
condition: "memory_usage > 85"
duration: "10m"
severity: "warning"
- name: "磁盘空间不足"
condition: "disk_usage > 90"
duration: "1h"
severity: "critical"
# 仪表板定制
dashboard:
layout: "grid"
widgets:
- type: "cpu"
position: "top-left"
size: "medium"
- type: "memory"
position: "top-right"
size: "medium"
- type: "disk"
position: "middle-left"
size: "large"
- type: "network"
position: "middle-right"
size: "medium"
- type: "processes"
position: "bottom-left"
size: "large"
- type: "services"
position: "bottom-right"
size: "medium"
# 自定义页面
custom_pages:
- name: "数据库监控"
path: "/database"
components:
- "mysql_status"
- "query_performance"
- name: "应用状态"
path: "/applications"
components:
- "nginx_status"
- "redis_metrics"
# 数据保留策略
retention:
metrics: "30d"
logs: "7d"
alerts: "90d"
# 安全配置
security:
authentication:
required: true
session_timeout: "24h"
rate_limiting:
enabled: true
requests_per_minute: 60
cors:
enabled: true
allowed_origins:
- "https://yourdomain.com"
```
## 自动化部署与维护脚本
创建完整的运维管理脚本:
```python
#!/usr/bin/env python3
# ward_manager.py - Ward监控系统管理工具
import os
import sys
import json
import yaml
import time
import argparse
from datetime import datetime
import subprocess
import requests
from pathlib import Path
class WardManager:
def __init__(self, config_path='/etc/ward/ward_manager.yaml'):
self.config_path = config_path
self.config = self.load_config()
def load_config(self):
"""加载配置文件"""
default_config = {
'ward': {
'install_dir': '/opt/ward',
'service_name': 'ward',
'port': 4000,
'user': 'ward',
'group': 'ward'
},
'tunnel': {
'enabled': True,
'service_name': 'ward-tunnel',
'config_dir': '/opt/remote-access'
},
'backup': {
'enabled': True,
'retention_days': 30,
'backup_dir': '/var/backups/ward'
},
'monitoring': {
'health_check_interval': 300, # 5分钟
'alert_thresholds': {
'cpu': 90,
'memory': 85,
'disk': 90
}
}
}
if os.path.exists(self.config_path):
with open(self.config_path, 'r') as f:
user_config = yaml.safe_load(f)
# 合并配置
if user_config:
self.merge_configs(default_config, user_config)
return default_config
def merge_configs(self, base, update):
"""递归合并配置"""
for key, value in update.items():
if key in base and isinstance(base[key], dict) and isinstance(value, dict):
self.merge_configs(base[key], value)
else:
base[key] = value
def install_ward(self):
"""安装Ward监控工具"""
print("开始安装Ward监控工具...")
# 检查依赖
self.check_dependencies()
# 创建目录
install_dir = self.config['ward']['install_dir']
os.makedirs(install_dir, exist_ok=True)
# 下载Ward
version = "1.8.6"
jar_file = f"ward-v{version}.jar"
jar_path = os.path.join(install_dir, jar_file)
if not os.path.exists(jar_path):
print(f"下载Ward {version}...")
url = f"https://github.com/B-Software/Ward/releases/download/v{version}/{jar_file}"
self.download_file(url, jar_path)
# 配置Ward
self.configure_ward()
# 创建系统服务
self.create_system_service()
print("Ward安装完成")
def configure_remote_access(self, region='us', hostname=None):
"""配置远程访问"""
if not self.config['tunnel']['enabled']:
print("远程访问功能已禁用")
return
print("配置远程访问...")
if not hostname:
hostname = f"ward-{os.uname().nodename}"
# 创建隧道配置
tunnel_config = {
'region': region,
'hostname': hostname,
'local_port': self.config['ward']['port'],
'service_name': self.config['tunnel']['service_name']
}
config_dir = self.config['tunnel']['config_dir']
os.makedirs(config_dir, exist_ok=True)
# 保存配置
config_file = os.path.join(config_dir, 'tunnel_config.json')
with open(config_file, 'w') as f:
json.dump(tunnel_config, f, indent=2)
# 配置隧道服务
self.create_tunnel_service()
print(f"远程访问配置完成,主机名: {hostname}")
def backup_configuration(self, backup_name=None):
"""备份Ward配置"""
if not self.config['backup']['enabled']:
print("备份功能已禁用")
return
if not backup_name:
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
backup_name = f"ward_backup_{timestamp}"
backup_dir = self.config['backup']['backup_dir']
os.makedirs(backup_dir, exist_ok=True)
backup_path = os.path.join(backup_dir, backup_name)
print(f"创建备份: {backup_name}")
# 备份配置文件
config_files = [
'/opt/ward/application.properties',
'/etc/systemd/system/ward.service',
'/etc/default/ward',
'/opt/remote-access/tunnel_config.json'
]
# 创建备份压缩包
import tarfile
with tarfile.open(f"{backup_path}.tar.gz", "w:gz") as tar:
for config_file in config_files:
if os.path.exists(config_file):
tar.add(config_file)
# 备份数据库文件(如果存在)
data_dir = '/opt/ward/data'
if os.path.exists(data_dir):
tar.add(data_dir, arcname='data')
print(f"备份已保存到: {backup_path}.tar.gz")
# 清理旧备份
self.cleanup_old_backups()
def monitor_health(self):
"""监控Ward健康状态"""
print("检查Ward健康状态...")
health_checks = [
self.check_service_status,
self.check_port_listening,
self.check_resources,
self.check_web_interface
]
results = []
for check in health_checks:
try:
result = check()
results.append(result)
except Exception as e:
results.append({'check': check.__name__, 'status': 'ERROR', 'message': str(e)})
# 输出结果
print("\n=== 健康检查报告 ===")
for result in results:
status_icon = "✓" if result['status'] == 'OK' else "✗"
print(f"{status_icon} {result['check']}: {result['message']}")
# 如果有错误,发送告警
errors = [r for r in results if r['status'] != 'OK']
if errors:
self.send_alert(errors)
def check_service_status(self):
"""检查服务状态"""
service = self.config['ward']['service_name']
result = subprocess.run(
['systemctl', 'is-active', service],
capture_output=True,
text=True
)
if result.returncode == 0:
return {
'check': '服务状态',
'status': 'OK',
'message': f'服务 {service} 运行正常'
}
else:
return {
'check': '服务状态',
'status': 'ERROR',
'message': f'服务 {service} 未运行: {result.stderr}'
}
def check_port_listening(self):
"""检查端口监听"""
port = self.config['ward']['port']
result = subprocess.run(
['ss', '-tln', 'sport', f':{port}'],
capture_output=True,
text=True
)
if f':{port}' in result.stdout:
return {
'check': '端口监听',
'status': 'OK',
'message': f'端口 {port} 正在监听'
}hot.nexgo.vip\
else:
return {
'check': '端口监听',
'status': 'ERROR',
'message': f'端口 {port} 未监听'
}
def check_web_interface(self):
"""检查Web界面"""
port = self.config['ward']['port']
try:
response = requests.get(f'http://localhost:{port}/health', timeout=5)
if response.status_code == 200:
return {
'check': 'Web界面',
'status': 'OK',
'message': 'Web界面可访问'
}
else:
return {
'check': 'Web界面',
'status': 'ERROR',
'message': f'Web界面返回状态码: {response.status_code}'
}
except requests.RequestException as e:
return {
'check': 'Web界面',
'status': 'ERROR',
'message': f'Web界面访问失败: {str(e)}'
}
def main():
parser = argparse.ArgumentParser(description='Ward监控系统管理工具')
parser.add_argument('action', choices=[
'install', 'configure', 'start', 'stop', 'restart',
'status', 'backup', 'monitor', 'update'
], help='要执行的操作')
parser.add_argument('--region', default='us', help='隧道区域')
parser.add_argument('--hostname', help='自定义主机名')
parser.add_argument('--config', default='/etc/ward/ward_manager.yaml',
help='配置文件路径')
args = parser.parse_args()
manager = WardManager(args.config)
if args.action == 'install':
manager.install_ward()
if args.hostname or args.region != 'us':
manager.configure_remote_access(args.region, args.hostname)
elif args.action == 'configure':
manager.configure_remote_access(args.region, args.hostname)
elif args.action == 'backup':
manager.backup_configuration()
elif args.action == 'monitor':
manager.monitor_health()
elif args.action in ['start', 'stop', 'restart', 'status']:
service = manager.config['ward']['service_name']
subprocess.run(['systemctl', args.action, service])
if manager.config['tunnel']['enabled']:
tunnel_service = manager.config['tunnel']['service_name']
subprocess.run(['systemctl', args.action, tunnel_service])
elif args.action == 'update':
print("更新功能开发中...")
if __name__ == '__main__':
main()
```
## 总结与最佳实践
通过Ward监控工具结合远程访问方案,可以实现:
1. **实时监控**:CPU、内存、磁盘、网络等关键指标可视化
2. **远程访问**:安全隧道技术实现随时随地访问
3. **告警通知**:阈值触发及时通知运维人员
4. **历史分析**:数据保留支持趋势分析和故障排查
实施建议:
- 生产环境建议配置SSL/TLS加密
- 定期备份配置和监控数据
- 设置合理的监控阈值和告警规则
- 结合其他监控工具形成完整监控体系
- 定期审查访问日志和安全配置
这种方案特别适合中小型团队或项目,在保证安全性的前提下,以较低成本实现专业的服务器监控能力。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/19545/viewspace-3105264/ ,如需转载,请注明出处,否则将追究法律责任。