浏览代码

给vps添加一个流量监控

蘭雅sRGB 6 年之前
父节点
当前提交
243f7f6aba
共有 1 个文件被更改,包括 65 次插入17 次删除
  1. 65 17
      netlog.sh

+ 65 - 17
netlog.sh

@@ -1,24 +1,10 @@
 #!/usr/bin/env bash
 
-INDEX_HTML=/var/www/log/index.html
-mkdir -p   /var/www/log/
 
-echo '<!DOCTYPE html><meta charset=utf-8><pre>' > ${INDEX_HTML}
-
-top -b  | head -5 >> ${INDEX_HTML}
-
-vnstat -u
-vnstat -m >> ${INDEX_HTML}
-vnstat -d >> ${INDEX_HTML}
-vnstat -h >> ${INDEX_HTML}
-
-echo ' ' >> ${INDEX_HTML}
-echo '    netlog.sh Source code:  https://git.io/fxxlb' >> ${INDEX_HTML}
-
-############# 安装使用 ################
+####### 安装使用原理 本脚本实现自动安装################
 #  apt-get install vnstat
 #  ip addr 查看网卡名称是否是 eth0,如果是网卡名是 ens3 或者 venet0
-#  编辑/etc/vnstat.conf 替换,重启vnstat服务
+#  编辑/etc/vnstat.conf 替换,重启vnstat服务(本脚本自动能自动修改网卡名)
 #  sed -i "s/eth0/ens3/g"   /etc/vnstat.conf
 #  systemctl restart vnstat
 
@@ -27,4 +13,66 @@ echo '    netlog.sh Source code:  https://git.io/fxxlb' >> ${INDEX_HTML}
 #  # netlog.sh  定时执行转html脚本,每10分钟一次,为了修改方便和多台机器用,直接到github更新
 #  */10  *   *   *  *    wget -qO- git.io/fxxlb | bash
 
-######################################
+######################################################
+
+# 输出网络流量日志到html
+output_html(){
+    INDEX_HTML=/var/www/html/index.html
+    mkdir -p   /var/www/html/
+
+    echo '<!DOCTYPE html><meta charset=utf-8><pre>' > ${INDEX_HTML}
+
+    top -b  | head -5 >> ${INDEX_HTML}
+
+    vnstat -u
+    vnstat -m >> ${INDEX_HTML}
+    vnstat -d >> ${INDEX_HTML}
+    vnstat -h >> ${INDEX_HTML}
+
+    echo ' ' >> ${INDEX_HTML}
+    echo '    netlog.sh Source code:  https://git.io/fxxlb' >> ${INDEX_HTML}
+}
+
+# 安装 vnstat 添加定期运行
+vnstat_install(){
+
+    # 判断系统 选择 apt
+    if [ ! -e '/etc/redhat-release' ]; then
+        alias apt='apt'
+    else
+        alias apt='yum'
+    fi
+
+    apt -y install vnstat nginx
+
+    #  vps网卡如果不是eth0,修改成实际网卡
+    ni=$(ls /sys/class/net | awk {print} | grep -e eth. -e ens. -e venet.)
+    if [ $ni != "eth0" ]; then
+        sed -i "s/eth0/${ni}/g"  /etc/vnstat.conf
+    fi
+
+    systemctl restart vnstat
+
+    # 设置定时运行脚本
+    crontab -l >> crontab.txt
+	echo "*/10  *   *   *  *    wget -qO- git.io/fxxlb | bash" >> crontab.txt
+	crontab crontab.txt
+	sleep 2
+	if [! -e '/etc/redhat-release' ];then
+		systemctl restart cron
+	else
+		systemctl restart crond
+	fi
+	rm -f crontab.txt
+
+}
+
+# 首次运行脚本需要安装
+if [ ! -f '/etc/vnstat.conf' ]; then
+    vnstat_install
+fi
+
+# 输出网络流量信息到html文件
+output_html
+
+