#!/bin/bash
set -e

# 下载地址
URL='https://github.com/prometheus/node_exporter/releases/download/v1.8.2'
# node_exporter 名称
node_exporter_name='node_exporter-1.8.2.linux-amd64'
# node_exporter 工作目录
node_exporter_path='/usr/local/node_exporter'

# 下载 node_exporter
wget ${URL}/${node_exporter_name}.tar.gz && tar -xzf ${node_exporter_name}.tar.gz -C /usr/local/
# 修改目录名
mv /usr/local/${node_exporter_name} ${node_exporter_path}

# 修改属主权限
chown -R root:root ${node_exporter_path}

# 添加至服务，并开机自启
cat >/usr/lib/systemd/system/node_exporter.service <<EOF
[Unit]
Description=Node Exporter
After=network.target
Wants=network-online.target

[Service]
Type=simple
User=root
ExecStart=${node_exporter_path}/node_exporter --web.listen-address=:9101
Restart=on-failure
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target
EOF

# 重新加载守护进程，并立刻启动 node_exporter 服务
systemctl daemon-reload
systemctl enable --now node_exporter
systemctl status node_exporter && sleep 3s && ss -ntpl | grep node_exporter
