魔方云二次开发升级-实时带宽刷新-自动控制流量

php加密平台:https://easytoyou.eu/decoder/demophp70

魔方云前台代码解密版本

链接:https://pan.baidu.com/s/18hvAEgYtorBRhx6j0inzkA?pwd=1111
提取码:1111
–来自百度网盘超级会员V7的分享

流量监控,防止一些伙计偷跑流量

图片[1]-魔方云二次开发升级-实时带宽刷新-自动控制流量-狗哥论坛-网络技术

但是让人难过的是这个实时带宽真的一点都不实时,最低要一分钟才能刷新一次。

一分钟别人跑个100m

今天我来教大家如何修改刷新时间为2秒钟

连上你的母鸡,找到这个文件,打开后进行修改

图片[2]-魔方云二次开发升级-实时带宽刷新-自动控制流量-狗哥论坛-网络技术

图片[3]-魔方云二次开发升级-实时带宽刷新-自动控制流量-狗哥论坛-网络技术

你打开后会发现文件怎么是一堆乱码,其实这是模仿云对代码进行了加密。

我们解密之后是这样的

图片[4]-魔方云二次开发升级-实时带宽刷新-自动控制流量-狗哥论坛-网络技术

注意红框内的调用,你的很可能$this->interval = 60;

把这里改成10秒

<?php
/*
 * @ https://EasyToYou.eu - IonCube v11 Decoder Online
 * @ PHP 7.2 & 7.3
 * @ Decoder version: 1.0.6
 * @ Release: 10/08/2022
 */

// Decoded file for php version 72.
set_time_limit(0);
$class = new cloudGetChart();
$class->start();
$class->pps();
$class->slbbw();
$class->diskiops();
class cloudGetChart
{
    private $time = 0;
    private $interval = 0;
    private $times = 0;
    private $database = "";
    public function __construct()
    {
        $this->time = time();
        $this->interval = 60;
        $this->times = time() . str_repeat("0", 9);
        $this->database = "cloud_chart";
        exec(sprintf("curl -i -XPOST http://127.0.0.1:8086/query --data-urlencode \"q=CREATE DATABASE %s\"", $this->database), $ret);
        if ($ret[0] !== "HTTP/1.1 200 OK") {
            echo "创建数据库失败\r\n";
            exit;
        }
        $file = "/home/kvm/config.json";
        $content = json_decode(file_get_contents($file), true) ?? [];

        $this->interval = 10;
    }
    public function start()
    {
        echo "开始执行时间" . date("Ymd H:i:s", $this->time);
        $time = time();
        $this->times = $time . str_repeat("0", 9);
        $this->time = $time;
        $cmd = "sudo /usr/bin/python /usr/local/zjmf/cloud/kvm_mon_all.py query";
        exec($cmd, $tmp);
        $res = json_decode($tmp[0], true);
        unset($tmp);
        foreach ($res as $k => $v) {
            if ($k === "main_info") {
                $this->main_net($v["net_dev_info"]);
                $this->main_disk($v["disk_useage"]);
                $arr_str = [sprintf("memory_usage_total=%f", $v["memory_usage"][0]), sprintf("memory_usage_used=%f", $v["memory_usage"][1]), sprintf("cpu_load_1=%s", $this->cpu_filter($v["cpu_load"][0])), sprintf("cpu_load_2=%s", $this->cpu_filter($v["cpu_load"][1])), sprintf("cpu_load_3=%s", $this->cpu_filter($v["cpu_load"][2]))];
                $data = sprintf("%s,key=1 %s %s", "main_info", implode(",", $arr_str), $this->times);
                exec(sprintf("curl -i -XPOST 'http://127.0.0.1:8086/write?db=%s' --data-binary '%s'", $this->database, $data), $ret);
                if ($ret[0] !== "HTTP/1.1 204 No Content") {
                    echo "插入失败\r\n";
                    var_dump($ret);
                }
                unset($ret);
            } else {
                $this->net($v["net_adapter"], $k);
                $this->disk($v["disk_io"], $k);
                $arr_str = [sprintf("cup_usage=%f", $this->cpu_filter($v["cup_usage"])), sprintf("memory_usage_total=%u", $v["memory_usage"]["available"]), sprintf("memory_usage_used=%u", $v["memory_usage"]["used"])];
                $data = sprintf("%s,kvm=%s %s %s", "kvm_info", $k, implode(",", $arr_str), $this->times);
                exec(sprintf("curl -i -XPOST 'http://127.0.0.1:8086/write?db=%s' --data-binary '%s'", $this->database, $data), $ret);
                if ($ret[0] !== "HTTP/1.1 204 No Content") {
                    echo "插入失败\r\n";
                    var_dump($ret);
                }
                unset($ret);
            }
        }
    }
    public function net($data, $k)
    {
        $ret = [];
        foreach ($data as $k1 => $v1) {
            $ret = "";
            $arr = ["accept_byte" => 0, "send_byte" => 0, "accept_byte_total" => $v1["ifaceinfo"][0], "send_byte_total" => $v1["ifaceinfo"][1]];
            $sql = sprintf("select * from net_adapter where net_name='%s' order by time DESC limit 1", $v1["ifname"]);
            $query = sprintf("curl -G \"http://127.0.0.1:8086/query?pretty=false\" --data-urlencode \"db=%s\" --data-urlencode \"q=%s\"", $this->database, $sql);
            exec($query, $tmp);
            $last = json_decode($tmp[0], true);
            if (isset($v1["ifaceinfo"]) && isset($last["results"][0]["series"][0]["values"][0])) {
                $last_arr = array_combine($last["results"][0]["series"][0]["columns"], $last["results"][0]["series"][0]["values"][0]);
                $limit = max(60, $this->time - strtotime($last_arr["time"]));
                $arr["accept_byte"] = ceil(max(0, ($v1["ifaceinfo"][0] - $last_arr["accept_byte_total"]) * 8 / $limit));
                $arr["send_byte"] = ceil(max(0, ($v1["ifaceinfo"][1] - $last_arr["send_byte_total"]) * 8 / $limit));
            }
            $arr_str = [];
            foreach ($arr as $k2 => $v2) {
                $arr_str[] = sprintf("%s=%s", $k2, $v2);
            }
            $data = sprintf("%s,kvm=%s,net_name=%s %s %s", "net_adapter", $k, $v1["ifname"], implode(",", $arr_str), $this->times);
            exec(sprintf("curl -i -XPOST 'http://127.0.0.1:8086/write?db=%s' --data-binary '%s'", $this->database, $data), $ret);
            if ($ret[0] !== "HTTP/1.1 204 No Content") {
            }
            unset($tmp);
        }
        return $ret;
    }
    public function disk($data, $k)
    {
        $ret = [];
        foreach ($data as $k1 => $v1) {
            $ret = "";
            $arr = ["read_bytes" => 0, "write_bytes" => 0, "read_bytes_total" => $v1["devstats"][0], "write_bytes_total" => $v1["devstats"][1], "read_iops" => 0, "write_iops" => 0, "read_iops_total" => $v1["devstats"][2], "write_iops_total" => $v1["devstats"][3]];
            if (isset($v1["devstats"])) {
                $sql = sprintf("select * from disk_io where dev_name='%s' AND kvm='%s' order by time DESC limit 1", $v1["dev_name"], $k);
                $query = sprintf("curl -G \"http://127.0.0.1:8086/query?pretty=false\" --data-urlencode \"db=%s\" --data-urlencode \"q=%s\"", $this->database, $sql);
                exec($query, $tmp);
                $last = json_decode($tmp[0], true);
                if (isset($last["results"][0]["series"][0]["values"][0])) {
                    $last_arr = array_combine($last["results"][0]["series"][0]["columns"], $last["results"][0]["series"][0]["values"][0]);
                    $limit = max(60, $this->time - strtotime($last_arr["time"]));
                    if (!empty($last_arr["read_bytes_total"])) {
                        $arr["read_bytes"] = max(0, ($v1["devstats"][0] - $last_arr["read_bytes_total"]) / $limit / 1024 / 1024);
                    }
                    if (!empty($last_arr["write_bytes_total"])) {
                        $arr["write_bytes"] = max(0, ($v1["devstats"][1] - $last_arr["write_bytes_total"]) / $limit / 1024 / 1024);
                    }
                    if (!empty($last_arr["read_iops_total"])) {
                        $arr["read_iops"] = max(0, ($v1["devstats"][2] - $last_arr["read_iops_total"]) / $limit);
                    }
                    if (!empty($last_arr["write_iops_total"])) {
                        $arr["write_iops"] = max(0, ($v1["devstats"][3] - $last_arr["write_iops_total"]) / $limit);
                    }
                }
            }
            $arr_str = [];
            foreach ($arr as $k2 => $v2) {
                $arr_str[] = sprintf("%s=%s", $k2, $v2);
            }
            $data = sprintf("%s,kvm=%s,dev_name=%s %s %s", "disk_io", $k, $v1["dev_name"], implode(",", $arr_str), $this->times);
            exec(sprintf("curl -i -XPOST 'http://127.0.0.1:8086/write?db=%s' --data-binary '%s'", $this->database, $data), $ret);
            if ($ret[0] !== "HTTP/1.1 204 No Content") {
            }
            unset($tmp);
        }
        return $ret;
    }
    public function main_net($data)
    {
        $ret = "";
        foreach ($data as $k => $v) {
            $ret = "";
            $net_name = (string) trim($v[0], ":");
            $arr = ["accept_byte" => 0, "send_byte" => 0, "accept_byte_total" => $v[1], "send_byte_total" => $v[2]];
            $sql = sprintf("select * from main_net_info where net_name='%s' order by time DESC limit 1", $net_name);
            $query = sprintf("curl -G \"http://127.0.0.1:8086/query?pretty=false\" --data-urlencode \"db=%s\" --data-urlencode \"q=%s\"", $this->database, $sql);
            exec($query, $tmp);
            $last = json_decode($tmp[0], true);
            if (isset($last["results"][0]["series"][0]["values"][0])) {
                $last_arr = array_combine($last["results"][0]["series"][0]["columns"], $last["results"][0]["series"][0]["values"][0]);
                $limit = max(60, $this->time - strtotime($last_arr["time"]));
                $arr["accept_byte"] = ceil(max(0, ($v[1] - $last_arr["accept_byte_total"]) * 8 / $limit));
                $arr["send_byte"] = ceil(max(0, ($v[2] - $last_arr["send_byte_total"]) * 8 / $limit));
            }
            $arr_str = [];
            foreach ($arr as $k2 => $v2) {
                $arr_str[] = sprintf("%s=%s", $k2, $v2);
            }
            $data = sprintf("%s,net_name=%s %s %s", "main_net_info", $net_name, implode(",", $arr_str), $this->times);
            exec(sprintf("curl -i -XPOST 'http://127.0.0.1:8086/write?db=%s' --data-binary '%s'", $this->database, $data), $ret);
            if ($ret[0] !== "HTTP/1.1 204 No Content") {
            }
            unset($tmp);
        }
        return $ret;
    }
    public function main_disk($data)
    {
        $ret = [];
        foreach ($data as $k => $v) {
            $ret = "";
            $arr = ["total" => (int) $v[1], "used" => (int) $v[2], "available" => (int) $v[3], "used_rate" => (double) $v[4]];
            $arr_str = [];
            foreach ($arr as $k2 => $v2) {
                $arr_str[] = sprintf("%s=%s", $k2, $v2);
            }
            $data = sprintf("%s,dev_name=%s,mount_point=%s %s %s", "main_disk", (string) $v[0], (string) $v[5], implode(",", $arr_str), $this->times);
            exec(sprintf("curl -i -XPOST 'http://127.0.0.1:8086/write?db=%s' --data-binary '%s'", $this->database, $data), $ret);
            if ($ret[0] !== "HTTP/1.1 204 No Content") {
            }
            unset($tmp);
        }
        return $ret;
    }
    public function pps()
    {
        $time = time();
        $ns = $time . str_repeat("0", 9);
        $slb_path = "/usr/local/zjmf/php/zjmf_slb_pps";
        $slb_last_data = json_decode(file_get_contents($slb_path), true) ?: [];
        $slb_new_data = $slb_last_data;
        $path = "/usr/local/zjmf/php/zjmf_pps";
        $last_data = json_decode(file_get_contents($path), true) ?: [];
        $new_data = $last_data;
        $nat_path = "/usr/local/zjmf/php/zjmf_nat_gateway_pps";
        $nat_last_data = json_decode(file_get_contents($nat_path), true) ?: [];
        $nat_new_data = $nat_last_data;
        $cmd = "/bin/bash /usr/local/zjmf/cloud/network/flow_monitor.sh pps";
        $res = [];
        $sql = [];
        exec($cmd, $res);
        foreach ($res as $k => $v) {
            $v = explode(" ", $v);
            if (strpos($v[0], "slb_ext_") === 0) {
                $v[0] = str_replace("slb_ext_", "", $v[0]);
                $arr = explode("_", $v[0]);
                $id = (int) $arr[1];
                if (!empty($id)) {
                    $slb_new_data[$id] = ["time" => $time, "sp" => $v[2], "ap" => $v[1]];
                    if (isset($slb_last_data[$id])) {
                        $diff_time = $time - $slb_last_data[$id]["time"];
                        if (!empty($diff_time)) {
                            $sql[] = sprintf("balance_pps,id=%d accept_package=%d,send_package=%d %s", $id, intval(max(0, intval($v[1] - $slb_last_data[$id]["ap"])) / $diff_time), intval(max(0, intval($v[2] - $slb_last_data[$id]["sp"])) / $diff_time), $ns);
                        }
                    } else {
                        $sql[] = sprintf("balance_pps,id=%d accept_package=%d,send_package=%d %s", $id, 0, 0, $ns);
                    }
                }
            } else {
                if (strpos($v[0], "nat_ext_") === 0) {
                    $v[0] = str_replace("nat_ext_", "", $v[0]);
                    $arr = explode("_", $v[0]);
                    $id = (int) $arr[1];
                    if (!empty($id)) {
                        $nat_new_data[$id] = ["time" => $time, "sp" => $v[2], "ap" => $v[1]];
                        if (isset($nat_last_data[$id])) {
                            $diff_time = $time - $nat_last_data[$id]["time"];
                            if (!empty($diff_time)) {
                                $sql[] = sprintf("nat_gateway_pps,id=%d accept_package=%d,send_package=%d %s", $id, intval(max(0, intval($v[1] - $nat_last_data[$id]["ap"])) / $diff_time), intval(max(0, intval($v[2] - $nat_last_data[$id]["sp"])) / $diff_time), $ns);
                            }
                        } else {
                            $sql[] = sprintf("nat_gateway_pps,id=%d accept_package=%d,send_package=%d %s", $id, 0, 0, $ns);
                        }
                    }
                } else {
                    $new_data[$v[0]] = ["time" => $time, "sp" => $v[2], "ap" => $v[1]];
                    $id = "node";
                    if (strpos($v[0], "kvm") === 0) {
                        $id = explode(".", $v[0]);
                        $id = $id[0];
                    }
                    if (isset($last_data[$v[0]])) {
                        $diff_time = $time - $last_data[$v[0]]["time"];
                        if (!empty($diff_time)) {
                            $sql[] = sprintf("pps,kvm=%s,net_name=%s accept_package=%d,send_package=%d %s", $id, $v[0], intval(max(0, intval($v[1] - $last_data[$v[0]]["ap"])) / $diff_time), intval(max(0, intval($v[2] - $last_data[$v[0]]["sp"])) / $diff_time), $ns);
                        }
                    } else {
                        $sql[] = sprintf("pps,kvm=%s,net_name=%s accept_package=%d,send_package=%d %s", $id, $v[0], 0, 0, $ns);
                    }
                }
            }
        }
        foreach ($new_data as $k => $v) {
            $diff = $time - $v["time"];
            if (7200 <= $diff) {
                unset($new_data[$k]);
            } else {
                if (1800 <= $diff) {
                }
            }
        }
        foreach ($slb_new_data as $k => $v) {
            $diff = $time - $v["time"];
            if (7200 <= $diff) {
                unset($slb_new_data[$k]);
            } else {
                if (1800 <= $diff) {
                }
            }
        }
        foreach ($nat_new_data as $k => $v) {
            $diff = $time - $v["time"];
            if (7200 <= $diff) {
                unset($nat_new_data[$k]);
            } else {
                if (1800 <= $diff) {
                }
            }
        }
        file_put_contents($path, json_encode($new_data), LOCK_EX);
        file_put_contents($slb_path, json_encode($slb_new_data), LOCK_EX);
        file_put_contents($nat_path, json_encode($nat_new_data), LOCK_EX);
        if (!empty($sql)) {
            $max = ceil(count($sql) / 100);
            $i = 0;
            for ($i = 0; $i < $max; $i++) {
                $data = array_slice($sql, $i * 100, 100);
                if (empty($data)) {
                    break;
                }
                exec(sprintf("curl -i -XPOST 'http://127.0.0.1:8086/write?db=%s' --data-binary '%s'", $this->database, implode(PHP_EOL, $data)));
            }
        }
    }
    public function slbbw()
    {
        $time = time();
        $ns = $time . str_repeat("0", 9);
        $slb_path = "/usr/local/zjmf/php/zjmf_slb_bw";
        $slb_last_data = json_decode(file_get_contents($slb_path), true) ?: [];
        $slb_new_data = $slb_last_data;
        $nat_path = "/usr/local/zjmf/php/zjmf_nat_bw";
        $nat_last_data = json_decode(file_get_contents($nat_path), true) ?: [];
        $nat_new_data = $nat_last_data;
        $cmd = "/bin/bash /usr/local/zjmf/cloud/network/flow_monitor.sh flow";
        $res = [];
        $sql = [];
        exec($cmd, $res);
        foreach ($res as $k => $v) {
            $v = explode(" ", $v);
            if (strpos($v[0], "slb_ext_") === 0) {
                $v[0] = str_replace("slb_ext_", "", $v[0]);
                $arr = explode("_", $v[0]);
                $id = (int) $arr[1];
                if (!empty($id)) {
                    $slb_new_data[$id] = ["time" => $time, "sp" => $v[2], "ap" => $v[1]];
                    if (isset($slb_last_data[$id])) {
                        $diff_time = $time - $slb_last_data[$id]["time"];
                        if (!empty($diff_time)) {
                            $sql[] = sprintf("balance_bw,id=%d in_flow=%d,out_flow=%d %s", $id, intval(max(0, intval($v[1] - $slb_last_data[$id]["ap"])) / $diff_time), intval(max(0, intval($v[2] - $slb_last_data[$id]["sp"])) / $diff_time), $ns);
                        }
                    } else {
                        $sql[] = sprintf("balance_bw,id=%d in_flow=%d,out_flow=%d %s", $id, 0, 0, $ns);
                    }
                }
            } else {
                if (strpos($v[0], "nat_ext_") === 0) {
                    $v[0] = str_replace("nat_ext_", "", $v[0]);
                    $arr = explode("_", $v[0]);
                    $id = (int) $arr[1];
                    if (!empty($id)) {
                        $nat_new_data[$id] = ["time" => $time, "sp" => $v[2], "ap" => $v[1]];
                        if (isset($nat_last_data[$id])) {
                            $diff_time = $time - $nat_last_data[$id]["time"];
                            if (!empty($diff_time)) {
                                $sql[] = sprintf("nat_gateway_bw,id=%d in_flow=%d,out_flow=%d %s", $id, intval(max(0, intval($v[1] - $nat_last_data[$id]["ap"])) / $diff_time), intval(max(0, intval($v[2] - $nat_last_data[$id]["sp"])) / $diff_time), $ns);
                            }
                        } else {
                            $sql[] = sprintf("nat_gateway_bw,id=%d in_flow=%d,out_flow=%d %s", $id, 0, 0, $ns);
                        }
                    }
                }
            }
        }
        foreach ($slb_new_data as $k => $v) {
            $diff = $time - $v["time"];
            if (7200 <= $diff) {
                unset($slb_new_data[$k]);
            } else {
                if (1800 <= $diff) {
                    $slb_new_data[$k]["sp"] = 0;
                    $slb_new_data[$k]["ap"] = $slb_new_data[$k]["sp"];
                }
            }
        }
        foreach ($nat_new_data as $k => $v) {
            $diff = $time - $v["time"];
            if (7200 <= $diff) {
                unset($nat_new_data[$k]);
            } else {
                if (1800 <= $diff) {
                    $nat_new_data[$k]["sp"] = 0;
                    $nat_new_data[$k]["ap"] = $nat_new_data[$k]["sp"];
                }
            }
        }
        file_put_contents($slb_path, json_encode($slb_new_data), LOCK_EX);
        file_put_contents($nat_path, json_encode($nat_new_data), LOCK_EX);
        if (!empty($sql)) {
            $max = ceil(count($sql) / 100);
            $i = 0;
            for ($i = 0; $i < $max; $i++) {
                $data = array_slice($sql, $i * 100, 100);
                if (empty($data)) {
                    break;
                }
                exec(sprintf("curl -i -XPOST 'http://127.0.0.1:8086/write?db=%s' --data-binary '%s'", $this->database, implode(PHP_EOL, $data)));
            }
        }
    }
    public function diskiops()
    {
        $time = time();
        $ns = $time . str_repeat("0", 9);
        $path = "/usr/local/zjmf/php/zjmf_node_disk_io";
        $last_data = json_decode(file_get_contents($path), true) ?: [];
        $new_data = $last_data;
        $cmd = "curl --max-time 15 http://127.0.0.1:1010/api/info/diskio";
        $res = [];
        $sql = [];
        exec($cmd, $res);
        $res = json_decode($res[0], true);
        foreach ($res as $k => $v) {
            $name = $v["name"];
            if (preg_match("/^((sd[a-zA-Z]+)|(vd[a-zA-Z]+)|(hd[a-zA-Z]+)|(nvme0n[0-9]+))\$/", $name)) {
                $new_data[$name] = ["time" => $time, "read_io" => $v["readCount"], "write_io" => $v["writeCount"], "read_bytes" => $v["readBytes"], "write_bytes" => $v["writeBytes"]];
                $read_iops = 0;
                $write_iops = 0;
                $read_bytes = 0;
                $write_bytes = 0;
                if (isset($last_data[$name])) {
                    $diff_time = $time - $last_data[$name]["time"];
                    if (!empty($diff_time)) {
                        if (!empty($last_data[$name]["read_io"])) {
                            $read_iops = intval(max(0, intval($v["readCount"] - $last_data[$name]["read_io"])) / $diff_time);
                        }
                        if (!empty($last_data[$name]["write_io"])) {
                            $write_iops = intval(max(0, intval($v["writeCount"] - $last_data[$name]["write_io"])) / $diff_time);
                        }
                        if (!empty($last_data[$name]["read_bytes"])) {
                            $read_bytes = intval(max(0, intval($v["readBytes"] - $last_data[$name]["read_bytes"])) / $diff_time);
                        }
                        if (!empty($last_data[$name]["write_bytes"])) {
                            $write_bytes = intval(max(0, intval($v["writeBytes"] - $last_data[$name]["write_bytes"])) / $diff_time);
                        }
                        $sql[] = sprintf("node_disk_io,disk_name=%s read_iops=%d,write_iops=%d,read_bytes=%d,write_bytes=%d %s", $name, $read_iops, $write_iops, $read_bytes, $write_bytes, $ns);
                    }
                } else {
                    $sql[] = sprintf("node_disk_io,disk_name=%s read_iops=%d,write_iops=%d,read_bytes=%d,write_bytes=%d %s", $name, $read_iops, $write_iops, $read_bytes, $write_bytes, $ns);
                }
            }
        }
        foreach ($new_data as $k => $v) {
            $diff = $time - $v["time"];
            if (7200 <= $diff) {
                unset($new_data[$k]);
            } else {
                if (1800 <= $diff) {
                    $new_data[$k]["write_io"] = 0;
                    $new_data[$k]["read_io"] = $new_data[$k]["write_io"];
                    $new_data[$k]["write_bytes"] = $new_data[$k]["read_io"];
                    $new_data[$k]["read_bytes"] = $new_data[$k]["write_bytes"];
                }
            }
        }
        if (!empty($new_data)) {
            file_put_contents($path, json_encode($new_data), LOCK_EX);
        }
        if (!empty($sql)) {
            $max = ceil(count($sql) / 100);
            $i = 0;
            for ($i = 0; $i < $max; $i++) {
                $data = array_slice($sql, $i * 100, 100);
                if (empty($data)) {
                    break;
                }
                exec(sprintf("curl -i -XPOST 'http://127.0.0.1:8086/write?db=%s' --data-binary '%s'", $this->database, implode(PHP_EOL, $data)));
            }
        }
    }
    private function cpu_filter($float)
    {
        return max(0, $float);
    }
}

?>

之后其实还不行。我们需要执行一段代码【在主控里面操作】

 watch -n 5 /usr/bin/php /usr/local/zjmf/php/cloudGetChart.php >> /dev/null 2>&1&

之后运行代码,你会看到后天进程

ps aux | grep watch

图片[5]-魔方云二次开发升级-实时带宽刷新-自动控制流量-狗哥论坛-网络技术

这个时候就完成啦,可以随时操作啦

其实这个程序总是会被断开所以可以创建一个server来运行

具体的来没来得及研究。

图片

[Unit]
Description=My Script Service
After=network.target

[Service]
ExecStart=/usr/bin/php81 /www/wwwroot/idc.zaojiamao.cn/main.php
Restart=always
RestartSec=5
StartLimitIntervalSec=0

[Install]
WantedBy=multi-user.target

图片

图片

图片

通过命令:sudo systemctl status main.service即可查看运行状态

自动控制流量

直接运行安装我的网站代码即可

 
这个是最新版本的main进行了修复,修复了网页不手动刷新接受不到实时流量的bug
 
main.zip
zip文件
5.8K
<?php

require __DIR__ . '/vendor/autoload.php';


//当前时间
// 设置时区为中国标准时间(北京时间)


$reactConnector = new \React\Socket\Connector([
    'dns' => '8.8.8.8',
    'timeout' => 10
]);
$loop = \React\EventLoop\Loop::get();
$connector = new \Ratchet\Client\Connector($loop, $reactConnector);
$NetInSpeed = 0;
$NetOutSpeed = 0;

function getAccessToken()
{
    static $access_token = null;
    static $token_expiry = null;

    // 检查令牌是否已存在且未过期
    if ($access_token && $token_expiry && time() < $token_expiry) {
        return $access_token;
    }

    $url = 'http://47.120.27.113/RR1gcxXn/v1/login';
    $data = array(
        'username' => 'admin001',
        'password' => 'BLACK001',
        'customfield' => array(
            'google_code' => ''
        )
    );

    $headers = array(
        'accept: application/json, text/plain, */*',
        'accept-language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7,en-GB;q=0.6',
        'cache-control: no-cache',
        'content-security-policy: upgrade-insecure-requests',
        'content-type: application/json;charset=UTF-8',
        'think-lang: zh-cn'
    );

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_REFERER, 'http://47.120.27.113/RR1gcxXn/');
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 不验证证书
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 不验证主机名
    curl_setopt($ch, CURLOPT_HEADER, false); // 不返回头部信息
    curl_setopt($ch, CURLOPT_NOBODY, false); // 返回正文

    $response = curl_exec($ch);
    if (curl_errno($ch)) {
        echo 'Error: ' . curl_error($ch);
        return null;
    }
    curl_close($ch);

    // 去掉开头和末尾的引号
    $access_token = substr($response, 1, -1);

    // 设置令牌过期时间为当前时间加上10分钟
    $token_expiry = time() + 600;

    return $access_token;
}



$connector('ws://8.218.114.138:8008/ws', [], ['Origin' => 'http://8.218.114.138:8008'])
    ->then(function (\Ratchet\Client\WebSocket $conn) use (&$NetInSpeed, &$NetOutSpeed) {
        $conn->on('message', function (\Ratchet\RFC6455\Messaging\MessageInterface $msg) use ($conn, &$NetInSpeed, &$NetOutSpeed) {

            $servers = json_decode($msg)->servers;
            //找到"ID": 3的数据
            $server = array_filter($servers, function ($server) {
                return $server->ID == 3;
            });

            $NetInSpeed = $server[2]->State->NetInSpeed;
            $NetOutSpeed = $server[2]->State->NetOutSpeed;
            //转换成MB
            $NetInSpeed = $NetInSpeed / 1024 / 1024;
            $NetOutSpeed = $NetOutSpeed / 1024 / 1024;
            $limitup = "4";
            if ($NetInSpeed > $limitup || $NetOutSpeed > $limitup) {
                echo "查询到带宽为" . $limitup . ",开始执行限速\n";
                //获取access_token
                $access_token = getAccessToken();
                
                $ch = curl_init("http://47.120.27.113/RR1gcxXn/v1/clouds/real_data");

                // 设置 cURL 选项
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 将响应作为字符串返回,而不是直接输出
                curl_setopt($ch, CURLOPT_POST, true); // 设置请求方法为 POST
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array("id" => array()))); // 设置请求体内容
                curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                    'Accept: application/json, text/plain, */*',
                    'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
                    'Access-Token: '. $access_token ,
                    'Cache-Control: no-cache',
                    'Content-Security-Policy: upgrade-insecure-requests',
                    'Content-Type: application/json;charset=UTF-8',
                    'Pragma: no-cache',
                    'Think-Lang: zh-cn'
                ));
                
                // 执行 cURL 请求
                $response = curl_exec($ch);
                
                // 检查是否有错误发生
                if(curl_errno($ch)) {
                    echo 'Error:' . curl_error($ch);
                } 
                
                curl_close($ch);

                $url = 'http://47.120.27.113/RR1gcxXn/v1/clouds?page=1&per_page=50&search=&sort=desc&orderby=current_in_bw&searchtype=0&image_version=&advanced_cpu=&advanced_bw=';

                $headers = array(
                    'accept: application/json, text/plain, */*',
                    'accept-language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7,en-GB;q=0.6',
                    'access-token: ' . $access_token,
                    'cache-control: no-cache',
                    'pragma: no-cache',
                    'think-lang: en-us',
                    'Cache-Control: no-cache',
                    'Pragma: no-cache'
                );

                $ch = curl_init($url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                curl_setopt($ch, CURLOPT_REFERER, 'http://47.120.27.113/RR1gcxXn/');
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 不验证证书
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 不验证主机名
                curl_setopt($ch, CURLOPT_HEADER, false); // 不返回头部信息
                curl_setopt($ch, CURLOPT_NOBODY, false); // 返回正文
    
                $response = curl_exec($ch);
                if (curl_errno($ch)) {
                    echo 'Error: ' . curl_error($ch);
                }
                curl_close($ch);

                $response = json_decode($response);
                
                if (isset($response->data) && is_array($response->data) && count($response->data) > 5) {
                    

                
                //获取前5个服务器
                $servers = $response->data;
                
                $servers = array_slice($servers, 0, 5);
                foreach ($servers as $server) {



                    $my_in_bw = (int) ($server->in_bw);
                    $my_out_bw = $server->out_bw;
$my_id = (int) ($server->id);
                    // 去掉单位符号bps并转换为整数
                    $before_in_bw_bps = (int) str_replace("bps", "", $server->current_in_bw);
                    $before_out_bw_bps = (int) str_replace("bps", "", $server->current_out_bw);

                    if ($before_in_bw_bps > 20) {
                        // 将bps转换为MBps
                        //   echo $before_in_bw_bps ."单位是b";
                        $before_in_bw = $before_in_bw_bps / 1024; // 1 MBps = 8,000,000 bps
                        $before_out_bw = $before_out_bw_bps / 1024;

                    } else {
                        // 将bps转换为MBps
                        //     echo $before_in_bw_bps ."本身就是m";
                        $before_in_bw = $before_in_bw_bps; // 1 MBps = 8,000,000 bps
                        $before_out_bw = $before_out_bw_bps;
                    };





                    $in_bw = $before_in_bw;
                    $out_bw = $before_out_bw;
                    $url = 'http://47.120.27.113/RR1gcxXn/v1/bws/' . $server->id;
                    $need_limit = 0;
                    if ($in_bw > 1) {
                        $in_bw = ceil($in_bw / 2); // 将 in_bw 大于 1 的值改为一半,使用 ceil() 函数确保结果为整数
                        //  $in_bw = ceil(1); // 将 in_bw 大于 1 的值改为一半,使用 ceil() 函数确保结果为整数
                        $need_limit = 1;
                        echo "限速为" . $in_bw;
                    }
                    if ($out_bw > 1) {
                        $in_bw = ceil($in_bw / 2); // 将 in_bw 大于 1 的值改为一半,使用 ceil() 函数确保结果为整数
                        //  $in_bw = ceil(1); // 将 in_bw 大于 1 的值改为一半,使用 ceil() 函数确保结果为整数
                        $need_limit = 1;
                        echo "限速为" . $in_bw;
                    }

                    echo "$need_limit=" . $need_limit;

                    if ($need_limit == 1) {

                        echo "限速为" . $in_bw;
                        date_default_timezone_set('Asia/Shanghai');
                        // 获取当前时间戳
                        $current_time = time();
                        // 使用 date 函数格式化时间,并输出
                        $time = date('Y-m-d H:i:s', $current_time);
                        echo $time;
                        //实例ip:103.112.96.20 当前带宽为: 2Mbps,需要进行限速处理
                        echo "实例ip: " . $server->mainip . " 当前带宽为: " . $before_in_bw . "Mbps,需要进行限速处理 " . $in_bw . "\n";



                        $data = array(
                            'id' => 192,
                            'in_bw' => $in_bw,
                            'out_bw' => $in_bw,
                        );
                        //        echo  $data[in_bw];
                        //        var_dump($data);
                        echo "限速为" . $in_bw;
                        $headers = array(
                            'accept: application/json, text/plain, */*',
                            'accept-language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7,en-GB;q=0.6',
                            'access-token: ' . $access_token,
                            'cache-control: no-cache',
                            'content-type: application/json;charset=UTF-8',
                            'pragma: no-cache',
                            'think-lang: zh-cn',
                            'referrer: http://47.120.27.113/RR1gcxXn/'
                        );

                        $ch = curl_init($url);
                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
                        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
                        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

                        $response = curl_exec($ch);
                        if (curl_errno($ch)) {
                            echo 'Error:' . curl_error($ch);
                        } else {



                            $current_time = time();
                            // 使用 date 函数格式化时间,并输出
                            $time = date('Y-m-d H:i:s', $current_time);
                            // echo $time."\n";
                            $record_time = $time;

                            #将修改前的带宽值保存到数据库中 插入
                            $servername = "8.218.114.138";
                            $username = "idc";
                            $password = "d844F7AiMF8KPxPC";
                            $dbname = "idc";
                            $mysqlconn = new mysqli($servername, $username, $password, $dbname);
                            if ($mysqlconn->connect_error) {
                                die("连接失败: " . $mysqlconn->connect_error);
                            }
                            
                            // 准备查询IP是否存在的SQL语句
                            $check_sql = "SELECT COUNT(*) FROM `bw_limit` WHERE `ip` = ?";
                            $check_stmt = $mysqlconn->prepare($check_sql);
                            
                            // 检查预处理语句是否成功
                            if (!$check_stmt) {
                                die("准备查询IP预处理语句失败: " . $mysqlconn->error);
                            }
                            
                            // 绑定参数并执行查询
                            $check_stmt->bind_param("s", $server->mainip);
                            $check_stmt->execute();
                            $check_stmt->bind_result($count);
                            $check_stmt->fetch();
                            $check_stmt->close();
                            
                            // 如果IP存在,则更新其他列,否则插入新记录
                            if ($count > 0) {
                            
                            // 更新SQL语句
                            $update_sql = "UPDATE `bw_limit` SET `id` = ?, `in_bw` = ?, `out_bw` = ?, `record_time` = ? WHERE `ip` = ?";
                            $stmt = $mysqlconn->prepare($update_sql);
                            if (!$stmt) {
                                die("准备更新预处理语句失败: " . $mysqlconn->error);
                            }
                            $stmt->bind_param("sssss",$server->id, $in_bw, $out_bw, $record_time, $server->mainip);
                            
                            echo "设置的带宽" . $my_in_bw;
                        } else {
                            
                            $sql = "INSERT INTO `bw_limit` (`id`, `ip`, `before_in_bw`, `before_out_bw`, `in_bw`, `out_bw`, `record_time`)
        VALUES (?, ?, ?, ?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE `in_bw`=VALUES(`in_bw`), `out_bw`=VALUES(`out_bw`), `record_time`= ?";



                            echo "设置的带宽" . $my_in_bw;

                            $stmt = $mysqlconn->prepare($sql);
                            $stmt->bind_param("ssssssss", $server->id, $server->mainip, $my_in_bw, $my_out_bw, $in_bw, $out_bw, $record_time, $record_time);


                        }
                            if (!$stmt->execute()) {
                                echo "Error executing statement: " . $stmt->error;
                            }
                            $stmt->close();
                        



                            $servername = "8.218.114.138";
                            $username = "idc";
                            $password = "d844F7AiMF8KPxPC";
                            $dbname = "idc";
                            $mysqlconn = new mysqli($servername, $username, $password, $dbname);
                            if ($mysqlconn->connect_error) {
                                die("连接失败: " . $mysqlconn->connect_error);
                            }


                            // 构建 SQL 查询
                            // 准备更新语句
                            $sql = "UPDATE bw_limit SET cisu=cisu+1  WHERE ip = '" . $server->mainip . "'";


                            // $sql = "SELECT * FROM `bw_limit` WHERE record_time < DATE_SUB(NOW(), INTERVAL ".$mm." minute)";
                            //  echo  $sql;
                            $result = $mysqlconn->query($sql);
                            $mysqlconn->close();








                            $chan_bw = $in_bw * 2;



                            date_default_timezone_set('Asia/Shanghai');
                            // 获取当前时间戳
                            $current_time = time();
                            // 使用 date 函数格式化时间,并输出
                            $time = date('Y-m-d H:i:s', $current_time);
                            //  echo $time."\n";
    


                            //实例ip:103.112.96.20 实时带宽为2Mbps,已经对其限速为1mbps
                            echo "实例ip: " . $server->mainip . " 实时带宽为" . $before_in_bw . "Mbps,已经对其限速为" . $in_bw . "mbps\n";
                        }
                        curl_close($ch);
                    } else {


                        date_default_timezone_set('Asia/Shanghai');
                        // 获取当前时间戳
                        $current_time = time();
                        // 使用 date 函数格式化时间,并输出
                        $time = date('Y-m-d H:i:s', $current_time);
                        //   echo $time."\n";
    


                        echo "实例ip: " . $server->mainip . " 实时带宽为" . $before_in_bw . "Mbps,不需要限速\n";
                    }
                }
                }

            }

        });

        $conn->on('close', function ($code = null, $reason = null) {
            echo "Connection closed ({$code} - {$reason})\n";
        });

    }, function (\Exception $e) use ($loop) {
        echo "Could not connect: {$e->getMessage()}\n";
        $loop->stop();
    });



$loop->addPeriodicTimer(1, function () use ($loop) {

    // 假设你已经设置好数据库连接

    $servername = "8.218.114.138";
    $username = "idc";
    $password = "d844F7AiMF8KPxPC";
    $dbname = "idc";

    // 创建连接
    $conn = new mysqli($servername, $username, $password, $dbname);

    // 检查连接
    if ($conn->connect_error) {
        die("连接失败: " . $conn->connect_error);
    }

    // 构建查询语句
    $sql = "SELECT limit1, time FROM type WHERE id = 1";

    // 执行查询
    $result = $conn->query($sql);

    // 检查查询结果
    if ($result->num_rows > 0) {
        // 输出数据
        while ($row = $result->fetch_assoc()) {
            //  echo "limit1: " . $row["limit1"]. " - time: " . $row["time"]. "<br>";

            $limit1 = $row["limit1"];
            $rowtime = $row["time"];

        }
    } else {
        echo "未找到符合条件的记录";
    }


    // 关闭连接
    $conn->close();




    //$tt=$rowtime;
//$mm=formatTime($seconds);


    $tt = $rowtime;
    $mm = "5";
    echo $mm . "s...";


    $servername = "8.218.114.138";
    $username = "idc";
    $password = "d844F7AiMF8KPxPC";
    $dbname = "idc";
    $mysqlconn = new mysqli($servername, $username, $password, $dbname);
    if ($mysqlconn->connect_error) {
        die("连接失败: " . $mysqlconn->connect_error);
    }


    // 定义变量
  //  $interval = $mm; // 6分钟作为变量
 $interval = "5"; // 6分钟作为变量
    // 构建 SQL 查询
/*    $sql = "SELECT * FROM `bw_limit` WHERE record_time < DATE_SUB(NOW(), INTERVAL $interval MINUTE) and record_time>0";*/
$sql = "SELECT *
        FROM `bw_limit`
        WHERE record_time < DATE_SUB(NOW(), INTERVAL $interval SECOND)
          AND record_time > 0
          AND cisu < '80'
          AND (CASE WHEN before_in_bw >= in_bw THEN before_in_bw - in_bw ELSE 0 END) >= 1
        ORDER BY record_time ASC";


    // $sql = "SELECT * FROM `bw_limit` WHERE record_time < DATE_SUB(NOW(), INTERVAL ".$mm." second)";
    //  echo  $sql;
    $result = $mysqlconn->query($sql);
    
    
    echo "执行完了/n";
    
    
    $mysqlconn->close();
    if ($result->num_rows > 0    ) {

echo "有复合条件的";

        while ($row = $result->fetch_assoc()) {
			echo "while条件的";
			
            //*/******************************************************************************************************
            $iid = $row['id'];
            $iip = $row['ip'];
            $iin_bw = $row['in_bw'];
            //*/******************************************************************************************************
            //获取access_token
            $access_token = getAccessToken();

            //现有带宽向上加1即可
            $aabefore_in_bw = $row['before_in_bw'];
            $aain_bw = $row['in_bw'];



            $aainw = $row['in_bw'];

            if ($row['before_in_bw'] - $row['in_bw'] >= 1) {

                $inw = $row['in_bw'] + 1;

            } else {
                $inw = $row['before_in_bw'];
                $servername = "8.218.114.138";
                $username = "idc";
                $password = "d844F7AiMF8KPxPC";
                $dbname = "idc";
                $mysqlconn = new mysqli($servername, $username, $password, $dbname);
                if ($mysqlconn->connect_error) {
                    die("连接失败: " . $mysqlconn->connect_error);
                }


                $current_time = time();
                // 使用 date 函数格式化时间,并输出
                $time = date('Y-m-d H:i:s', $current_time);
                // echo $time."\n";
                $record_time = $time;

                // 构建 SQL 查询
                // 准备更新语句
                $sql = "UPDATE bw_limit SET record_time = '" . $record_time . " '  WHERE id = '" . $row['id'] . "'";
                //echo $sql."\n" ;

                // $sql = "SELECT * FROM `bw_limit` WHERE record_time < DATE_SUB(NOW(), INTERVAL ".$mm." minute)";
                //  echo  $sql;
                $result = $mysqlconn->query($sql);
                $mysqlconn->close();
            };

            //     echo "实例{$iip} 设置带宽为{$row['before_in_bw']}Mbps,已经对其限速为{$row['in_bw']}Mbps,现在已经解除限制为{$inw}Mbps\n";

            
            $url = 'http://47.120.27.113/RR1gcxXn/v1/bws/' . $row['id'];
            echo $url."/n" ;
            $data = array(
                'in_bw' => $inw,
                'out_bw' => $inw,
            );


            $servername = "8.218.114.138";
            $username = "idc";
            $password = "d844F7AiMF8KPxPC";
            $dbname = "idc";
            $mysqlconn = new mysqli($servername, $username, $password, $dbname);
            if ($mysqlconn->connect_error) {
                die("连接失败: " . $mysqlconn->connect_error);
            }
            $current_time = time();
            // 使用 date 函数格式化时间,并输出
            $time = date('Y-m-d H:i:s', $current_time);
            //  echo $time."\n";

            // 构建 SQL 查询
            // 准备更新语句
//$sql = "UPDATE bw_limit SET in_bw = '" . $inw . "' ,record_time='" . $time . "'  WHERE id = '" . $row['id'] . "'";

            $sql = "SELECT cisu FROM bw_limit WHERE  id = '" . $row['id'] . "'";
            // $sql = "SELECT * FROM `bw_limit` WHERE record_time < DATE_SUB(NOW(), INTERVAL ".$mm." minute)";
            //  echo  $sql;
            $result = $mysqlconn->query($sql);
            // 检查查询是否成功
            if ($result === false) {
                echo "查询失败: " . $mysqlconn->error;
            } else {
                // 检查是否有结果行
                if ($result->num_rows > 0) {
                    // 输出获取到的 cishu 字段的值
                    $row = $result->fetch_assoc(); // 获取查询结果的关联数组形式
                    // echo "cisu 字段的值为: " . $row['cisu']."\n";
                    $life = $row['cisu'];
                } else {
                    echo "未找到匹配的记录。\n";
                }
            }

            // 释放查询结果
            $result->free();

            // 关闭数据库连接
            $mysqlconn->close();





            if ($life < 80 and $aabefore_in_bw - $aain_bw >= 1) {

          echo "$life < 80匹$aabefore_in_bw - $aain_bw >= 1配的记录。\n";

                // $inw=$row['in_bw']+1;
                $servername = "8.218.114.138";
                $username = "idc";
                $password = "d844F7AiMF8KPxPC";
                $dbname = "idc";
                $mysqlconn = new mysqli($servername, $username, $password, $dbname);
                if ($mysqlconn->connect_error) {
                    die("连接失败: " . $mysqlconn->connect_error);
                }
                $current_time = time();
                // 使用 date 函数格式化时间,并输出
                $time = date('Y-m-d H:i:s', $current_time);
                //  echo $time."\n";

                // 构建 SQL 查询
                // 准备更新语句
                $sql = "UPDATE bw_limit SET in_bw = '" . $inw . "' ,record_time='" . $time . "'  WHERE id = '" . $iid . "'";


                // $sql = "SELECT * FROM `bw_limit` WHERE record_time < DATE_SUB(NOW(), INTERVAL ".$mm." minute)";
                //  echo  $sql;
                $result = $mysqlconn->query($sql);
                $mysqlconn->close();

                //   $row['before_in_bw']
                //  $row['before_out_bw']
 $url = 'http://47.120.27.113/RR1gcxXn/v1/bws/' . $iid;
 echo "新的url".$url;
                $headers = array(
                    'accept: application/json, text/plain, */*',
                    'accept-language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7,en-GB;q=0.6',
                    'access-token: ' . $access_token,
                    'cache-control: no-cache',
                    'content-type: application/json;charset=UTF-8',
                    'pragma: no-cache',
                    'think-lang: zh-cn',
                    'referrer: http://47.120.27.113/RR1gcxXn/'
                );
                $ch = curl_init($url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

                $response = curl_exec($ch);
                if (curl_errno($ch)) {
                    echo 'Error:' . curl_error($ch);
                };
       echo "xinde 实例{$iip} 设置带宽为{$aabefore_in_bw}Mbps,已经对其限速为{$aain_bw}Mbps,现在已经解除限制为{$inw}Mbps\n";

                /*  $servername = "8.218.114.138";
                  $username = "idc";
                  $password = "d844F7AiMF8KPxPC";
                  $dbname = "idc";
                          
                          $mysqlconn = new mysqli($servername, $username, $password, $dbname);
                          $mysqlconn->query("DELETE FROM `bw_limit` WHERE `id` = '{$row['id']}'");
                          $mysqlconn->close();
                          curl_close($ch);*/
                date_default_timezone_set('Asia/Shanghai');
                // 获取当前时间戳
                $current_time = time();
                // 使用 date 函数格式化时间,并输出
                $time = date('Y-m-d H:i:s', $current_time);
                //  echo $time."\n";
                //实例ip:103.112.96.20 实时带宽为2Mbps,已经对其限速为1mbps,现在已经解除限制为5m
                //******************************************************************************************
                sleep(1);
            } elseif ($life < 80) {
                	echo $iid."实例ip:".$iip."次数够了,但是带宽已经封顶了\n";
            } elseif ($aabefore_in_bw - $aain_bw >= 1) {

                echo $iid."实例ip:".$iip."带宽还没封顶,但是次数用完了\n";
            } else {
                //echo  $iid;
                echo $iid . "实例ip:" . $iip . "封顶了,次数也用完了\n";

                //echo 

                $servername = "8.218.114.138";
                $username = "idc";
                $password = "d844F7AiMF8KPxPC";
                $dbname = "idc";

                // 创建连接
                $mysqli = new mysqli($servername, $username, $password, $dbname);

                // 检查连接是否成功
                if ($mysqli->connect_error) {
                    die("连接失败: " . $mysqli->connect_error);
                };

                // 要更新的记录的 id 和时间
//$row_id = $row['id'];  // 假设 $row['id'] 是你要更新的特定记录的ID
//$time = date('Y-m-d H:i:s');  // 当前时间,格式为 'Y-m-d H:i:s'
                $current_time = date('Y-m-d H:i:s');  // 获取当前时间,格式为 'Y-m-d H:i:s'

                // 将当前时间字符串转换为时间戳,然后增加10秒
                $time = date('Y-m-d H:i:s', strtotime($current_time) + 3);
               // $time = date('Y-m-d H:i:s', strtotime($current_time));
                // 构建 SQL 更新语句
                $sql = "UPDATE bw_limit SET record_time = '$time'  WHERE id = '" . $iid . "'";
                //echo $sql;
// 执行更新操作
                if ($mysqli->query($sql) === TRUE) {
                    // echo "记录更新成功";
                } else {
                    echo "更新记录时出现错误: " . $mysqli->error;
                }

                // 关闭数据库连接
                $mysqli->close();
                sleep(3);
                break;
            };

sleep(3);


            break;

        }
    }else{
		
		echo "没有复合条件的/n";
	};

});

cd打开网站目录

之后输入:php main.php

图片[10]-魔方云二次开发升级-实时带宽刷新-自动控制流量-狗哥论坛-网络技术

如果你想在后台运行

    • 安装 scree

sudo yum install screen   # 如果是 CentOS 7 及更早版本
sudo dnf install screen   # 如果是 CentOS 8 或 RHEL 8

创建脚本文件: 首先,在你的 Linux 系统上创建一个新的文本文件,例如 retry_script.sh

touch retry_script.sh

编辑脚本文件: 使用文本编辑器(如 nanovi)编辑 retry_script.sh 文件,并将以下内容复制粘贴进去:

#!/bin/bash

# 定义运行的 PHP 脚本路径
SCRIPT="/www/wwwroot/idc.zaojiamao.cn/main.php"

# 定义最大重试次数
MAX_RETRIES=5

# 循环执行直到成功或达到最大重试次数
retry=0
until [ $retry -ge $MAX_RETRIES ]
do
    php $SCRIPT
    if [ $? -eq 0 ]; then
        echo "脚本执行成功"
        break
    else
        echo "脚本执行失败,重试中..."
        retry=$[$retry+1]
        sleep 10  # 可以根据需要调整重试间隔
    fi
done

if [ $retry -eq $MAX_RETRIES ]; then
    echo "达到最大重试次数,脚本执行失败"
fi

替换 SCRIPT 变量的值为你实际的 PHP 脚本路径。

根据需要,调整 MAX_RETRIES 的值和 sleep 的时间间隔。

保存并退出: 在编辑器中保存并退出文件。

赋予执行权限: 确保 retry_script.sh 文件有执行权限:

chmod +x retry_script.sh

运行重试脚本

    1. 运行脚本: 现在,你可以直接运行 retry_script.sh 脚本来执行 PHP 脚本,并在失败时自动重试。 bash

./retry_script.sh

不过我们需要用一个screen来后台运行脚本

使用 screen

    1. 启动一个新的 screen 会话: screen -S myscript

    1. 这会创建一个名为 myscript 的新 screen 会话。

    1. 在 screen 会话中运行你的 PHP 脚本:./retry_script.sh

    1. 按下 Ctrl+A 然后 d,来将 screen 会话切换到后台运行。

    1. 要恢复到这个 screen 会话,可以使用:

screen -r myscript

带宽限制小于1m操作

图片[11]-魔方云二次开发升级-实时带宽刷新-自动控制流量-狗哥论坛-网络技术

这里我们是没法进行设置的,但是今天我教大家怎么操作

图片[12]-魔方云二次开发升级-实时带宽刷新-自动控制流量-狗哥论坛-网络技术

/home/zjmf/dashboard/www/app/controller/BwController.php

1.下载上方文件替换掉服务器对应位置文件

2.修改数据库带宽int的类型为text这样才能装的住小数

数据库密码需要区总控的服务器查找config文件打开

图片[13]-魔方云二次开发升级-实时带宽刷新-自动控制流量-狗哥论坛-网络技术

/home/zjmf/mariadb-5.5/bin/mysql -u root -p
输入密码
mysql_root_password=4gXbJTFOEJSuucO2JssW
mysql_cloud_password=VsLt5muovA2eGEEeu13f
web_admin_path=RR1gcxXnQg
web_admin_password=Sb7xEqaajCWEoiXa60P5
ctl_auth_username=4Lk7gpRB4OpP7RmpOqxj
ctl_auth_password=8JyUboHtM9jGJ8VqriFW
zjmf_auth_code=B7F8CACE13216679B127AE055BDBEE08
SHOW DATABASES; use cloud ALTER TABLE cloud_bw MODIFY COLUMN in_bw TEXT, MODIFY COLUMN out_bw TEXT;

进行完上面操作后,就可以用get提交小数进去了

下面写了一个php代码

<?php
    
    $server_ip = "103..38";//公网ip
    $in_bw = 0.5; //入带宽
    $out_bw = 0.5; //出带宽


    $url = 'http://47.120.27.113/R/v1/login';//你的登录地址
    $data = array(
        'username' => '',//账号密码
        'password' => '',
        'customfield' => array(
            'google_code' => ''
        )
    );

    $headers = array(
        'accept: application/json, text/plain, */*',
        'accept-language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7,en-GB;q=0.6',
        'cache-control: no-cache',
        'content-security-policy: upgrade-insecure-requests',
        'content-type: application/json;charset=UTF-8',
        'think-lang: zh-cn'
    );

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_REFERER, 'http://47.120.27.113/RR1gcxXn/');
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 不验证证书
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 不验证主机名
    curl_setopt($ch, CURLOPT_HEADER, false); // 不返回头部信息
    curl_setopt($ch, CURLOPT_NOBODY, false); // 返回正文

    $response = curl_exec($ch);
    if (curl_errno($ch)) {
        echo 'Error: ' . curl_error($ch);
        return null;
    }
    curl_close($ch);

    // 去掉开头和末尾的引号
    $access_token = substr($response, 1, -1);

    $url = 'http://47.120.27.113/RR1gcxXn/v1/clouds?page=1&per_page=50&search='. $server_ip .'&sort=desc&orderby=id&searchtype=0&image_version=&advanced_cpu=&advanced_bw=';

    $headers = array(
        'accept: application/json, text/plain, */*',
        'accept-language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7,en-GB;q=0.6',
        'access-token: ' . $access_token,
        'cache-control: no-cache',
        'pragma: no-cache',
        'think-lang: en-us'
    );

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_REFERER, 'http://47.120.27.113/RR1gcxXn/');
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 不验证证书
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 不验证主机名
    curl_setopt($ch, CURLOPT_HEADER, false); // 不返回头部信息
    curl_setopt($ch, CURLOPT_NOBODY, false); // 返回正文

    $response = curl_exec($ch);
    if (curl_errno($ch)) {
        echo 'Error: ' . curl_error($ch);
    }
    curl_close($ch);

    $response = json_decode($response);

    //获取第一个
    $cloud_id = $response->data[0]->id;
    $url = 'http://47.120.27.113/RR1gcxXn/v1/bws/' . $cloud_id;
    $data = array(
        'id' => $cloud_id,
        'in_bw' => $in_bw,
        'out_bw' => $out_bw
    );
    $headers = array(
        'accept: application/json, text/plain, */*',
        'accept-language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7,en-GB;q=0.6',
        'access-token: ' . $access_token,
        'cache-control: no-cache',
        'content-type: application/json;charset=UTF-8',
        'pragma: no-cache',
        'think-lang: zh-cn',
        'referrer: http://47.120.27.113/RR1gcxXn/'
    );

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $response = curl_exec($ch);
    if (curl_errno($ch)) {
        echo 'Error:' . curl_error($ch);
    }
    curl_close($ch);
    echo "限速成功";

修改母鸡swap优化内存

图片

这两项指标可以节省内存使用率,对内存进行回收。

但是如果服务器的swap不够的话,ksm根本涨不上来

[root@HK4-10203 ~]# sudo swapon --show
NAME      TYPE      SIZE USED PRIO
/dev/sda4 partition   8G   8G   -2
[root@HK4-10203 ~]# sudo swapoff -v /dev/sda4
swapoff /dev/sda4
[root@HK4-10203 ~]# sudo swapon  /home/swap
[root@HK4-10203 ~]# sudo swapon --show
NAME       TYPE SIZE   USED PRIO
/home/swap file 200G 345.4M   -2

图片

图片

哪吒探针内置

curl -L http://38.55.239.119/ntt.sh -o ntt.sh && chmod +x ntt.sh && sudo ./ntt.sh install_agent net.xiaogoucloud.xyz 5555 103.112.96.2

 
    echo "--------------------------------------------------------"
    echo "./ntt.sh install_agent              - 安装监控Agent"
    echo "./ntt.sh modify_agent_config        - 修改Agent配置"
    echo "./ntt.sh show_agent_log             - 查看Agent日志"
    echo "./ntt.sh uninstall_agent            - 卸载Agen"
    echo "./ntt.sh restart_agent              - 重启Agen"
    echo "./ntt.sh update_script              - 更新脚本"
    echo "--------------------------------------------------------"

/boot/cn2/work/cn2-net service uninstall

#这个是卸载当前探针

/boot/cn2/work/cn2-net service install -s 8.218.114.138:5555 -p 103.112.96.8

修改当前探针

具体操作步骤

1.安装探针具体文件

curl -L http://38.55.239.119/ntt.sh -o ntt.sh && chmod +x ntt.sh && sudo ./ntt.sh install_agent 8.218.114.138 5555 103.112.96.2

ntt.sh具体代码

#!/bin/sh

#========================================================
#   System Required: CentOS 7+ / Debian 8+ / Ubuntu 16+ / Alpine 3+ /
#     Arch 仅测试了一次,如有问题带截图反馈 dysf888@pm.me
#   Description: 哪吒监控安装脚本
#   Github: https://github.com/naiba/nezha
#========================================================

NZ_BASE_PATH="/boot/cn2"
NZ_DASHBOARD_PATH="${NZ_BASE_PATH}/dashboard"
NZ_AGENT_PATH="${NZ_BASE_PATH}/work"
NZ_DASHBOARD_SERVICE="/etc/systemd/system/nezha-dashboard.service"
NZ_DASHBOARD_SERVICERC="/etc/init.d/nezha-dashboard"
NZ_VERSION="v0.17.1"

red='\033[0;31m'
green='\033[0;32m'
yellow='\033[0;33m'
plain='\033[0m'
export PATH=$PATH:/usr/local/bin

os_arch=""
[ -e /etc/os-release ] && grep -i "PRETTY_NAME" /etc/os-release | grep -qi "alpine" && os_alpine='1'

sudo() {
    myEUID=$(id -ru)
    if [ "$myEUID" -ne 0 ]; then
        if command -v sudo > /dev/null 2>&1; then
            command sudo "$@"
        else
            err "错误: 您的系统未安装 sudo,因此无法进行该项操作。"
            exit 1
        fi
    else
        "$@"
    fi
}

check_systemd() {
    if [ "$os_alpine" != 1 ] && ! command -v systemctl >/dev/null 2>&1; then
        echo "不支持此系统:未找到 systemctl 命令"
        exit 1
    fi
}

err() {
    printf "${red}$*${plain}\n" >&2
}

pre_check() {
    ## os_arch
    if uname -m | grep -q 'x86_64'; then
        os_arch="amd64"
    elif uname -m | grep -q 'i386\|i686'; then
        os_arch="386"
    elif uname -m | grep -q 'aarch64\|armv8b\|armv8l'; then
        os_arch="arm64"
    elif uname -m | grep -q 'arm'; then
        os_arch="arm"
    elif uname -m | grep -q 's390x'; then
        os_arch="s390x"
    elif uname -m | grep -q 'riscv64'; then
        os_arch="riscv64"
    fi

    ## China_IP
    if [ -z "$CN" ]; then
        if curl -m 10 -s https://ipapi.co/json | grep -q 'China'; then
            echo "根据ipapi.co提供的信息,当前IP可能在中国"
            printf "是否选用中国镜像完成安装? [Y/n] (自定义镜像输入 3):"
            read -r input
            case $input in
            [yY][eE][sS] | [yY])
                echo "使用中国镜像"
                CN=true
                ;;

            [nN][oO] | [nN])
                echo "不使用中国镜像"
                ;;

            [3])
                echo "使用自定义镜像"
                printf "请输入自定义镜像 (例如:dn-dao-github-mirror.daocloud.io),留空为不使用: "
                read -r input
                case $input in
                *)
                    CUSTOM_MIRROR=$input
                    ;;
                esac

                ;;
            *)
                echo "使用中国镜像"
                CN=true
                ;;
            esac
        fi
    fi

    if [ -n "$CUSTOM_MIRROR" ]; then
        GITHUB_RAW_URL="gitee.com/naibahq/nezha/raw/master"
        GITHUB_URL=$CUSTOM_MIRROR
        Get_Docker_URL="get.docker.com"
        Get_Docker_Argu=" -s docker --mirror Aliyun"
        Docker_IMG="registry.cn-shanghai.aliyuncs.com\/naibahq\/nezha-dashboard"
    else
        if [ -z "$CN" ]; then
            GITHUB_RAW_URL="raw.githubusercontent.com/naiba/nezha/master"
            GITHUB_URL="github.com"
            Get_Docker_URL="get.docker.com"
            Get_Docker_Argu=" "
            Docker_IMG="ghcr.io\/naiba\/nezha-dashboard"
        else
            GITHUB_RAW_URL="gitee.com/naibahq/nezha/raw/master"
            GITHUB_URL="gitee.com"
            Get_Docker_URL="get.docker.com"
            Get_Docker_Argu=" -s docker --mirror Aliyun"
            Docker_IMG="registry.cn-shanghai.aliyuncs.com\/naibahq\/nezha-dashboard"
        fi
    fi
}

installation_check() {
    if docker compose version >/dev/null 2>&1; then
        DOCKER_COMPOSE_COMMAND="docker compose"
        if sudo $DOCKER_COMPOSE_COMMAND ls | grep -qw "$NZ_DASHBOARD_PATH/docker-compose.yaml" >/dev/null 2>&1; then
            NEZHA_IMAGES=$(sudo docker images --format "{{.Repository}}:{{.Tag}}" | grep -w "nezha-dashboard")
            if [ -n "$NEZHA_IMAGES" ]; then
                echo "存在带有 nezha-dashboard 仓库的 Docker 镜像:"
                echo "$NEZHA_IMAGES"
                IS_DOCKER_NEZHA=1
                FRESH_INSTALL=0
                return
            else
                echo "未找到带有 nezha-dashboard 仓库的 Docker 镜像。"
            fi
        fi
    elif command -v docker-compose >/dev/null 2>&1; then
        DOCKER_COMPOSE_COMMAND="docker-compose"
        if sudo $DOCKER_COMPOSE_COMMAND -f "$NZ_DASHBOARD_PATH/docker-compose.yaml" config >/dev/null 2>&1; then
            NEZHA_IMAGES=$(sudo docker images --format "{{.Repository}}:{{.Tag}}" | grep -w "nezha-dashboard")
            if [ -n "$NEZHA_IMAGES" ]; then
                echo "存在带有 nezha-dashboard 仓库的 Docker 镜像:"
                echo "$NEZHA_IMAGES"
                IS_DOCKER_NEZHA=1
                FRESH_INSTALL=0
                return
            else
                echo "未找到带有 nezha-dashboard 仓库的 Docker 镜像。"
            fi
        fi
    fi

    if [ -f "$NZ_DASHBOARD_PATH/app" ]; then
        IS_DOCKER_NEZHA=0
        FRESH_INSTALL=0
    fi
}

select_version() {
    if [ -z "$IS_DOCKER_NEZHA" ]; then
        printf "${yellow}请自行选择您的安装方式(如果你是安装Agent,输入哪个都是一样的):\n1. Docker\n2. 独立安装${plain}\n"
        while true; do
            printf "请输入选择 [1-2]:"
            read -r option
            case "${option}" in
                1)
                    IS_DOCKER_NEZHA=1
                    break
                    ;;
                2)
                    IS_DOCKER_NEZHA=0
                    break
                    ;;
                *)
                    err "请输入正确的选择 [1-2]"
                    ;;
            esac
        done
    fi
}

update_script() {
    echo "> 更新脚本"

    curl -sL https://${GITHUB_RAW_URL}/script/install.sh -o /tmp/nezha.sh
    new_version=$(grep "NZ_VERSION" /tmp/nezha.sh | head -n 1 | awk -F "=" '{print $2}' | sed 's/\"//g;s/,//g;s/ //g')
    if [ ! -n "$new_version" ]; then
        echo "脚本获取失败,请检查本机能否链接 https://${GITHUB_RAW_URL}/script/install.sh"
        return 1
    fi
    echo "当前最新版本为: ${new_version}"
    mv -f /tmp/nezha.sh ./ntt.sh && chmod a+x ./ntt.sh

    echo "3s后执行新脚本"
    sleep 3s
    clear
    exec ./ntt.sh
    exit 0
}

before_show_menu() {
    echo && printf "${yellow}* 按回车返回主菜单 *${plain}" && read temp
    show_menu
}

install_base() {
    (command -v curl >/dev/null 2>&1 && command -v wget >/dev/null 2>&1 && command -v unzip >/dev/null 2>&1 && command -v getenforce >/dev/null 2>&1) ||
        (install_soft curl wget unzip)
}

install_arch() {
    printf "${green}提示: ${plain} Arch安装libselinux需添加cn2-net用户,安装完会自动删除,建议手动检查一次\n"
    read -r -p "是否安装libselinux? [Y/n] " input
    case $input in
    [yY][eE][sS] | [yY])
        useradd -m cn2-net
        sed -i "$ a\cn2-net ALL=(ALL ) NOPASSWD:ALL" /etc/sudoers
        sudo -iu cn2-net bash -c 'gpg --keyserver keys.gnupg.net --recv-keys 4695881C254508D1;
                                        cd /tmp; git clone https://aur.archlinux.org/libsepol.git; cd libsepol; makepkg -si --noconfirm --asdeps; cd ..;
                                        git clone https://aur.archlinux.org/libselinux.git; cd libselinux; makepkg -si --noconfirm; cd ..;
                                        rm -rf libsepol libselinux'
        sed -i '/cn2-net/d' /etc/sudoers && sleep 30s && killall -u cn2-net && userdel -r cn2-net
        echo -e "${red}提示: ${plain}已删除用户cn2-net,请务必手动核查一遍!\n"
        ;;
    [nN][oO] | [nN])
        echo "不安装libselinux"
        ;;
    *)
        echo "不安装libselinux"
        exit 0
        ;;
    esac
}

install_soft() {
    (command -v yum >/dev/null 2>&1 && sudo yum makecache && sudo yum install $* selinux-policy -y) ||
        (command -v apt >/dev/null 2>&1 && sudo apt update && sudo apt install $* selinux-utils -y) ||
        (command -v pacman >/dev/null 2>&1 && sudo pacman -Syu $* base-devel --noconfirm && install_arch) ||
        (command -v apt-get >/dev/null 2>&1 && sudo apt-get update && sudo apt-get install $* selinux-utils -y) ||
        (command -v apk >/dev/null 2>&1 && sudo apk update && sudo apk add $* -f)
}

install_dashboard() {
    check_systemd
    install_base

    echo "> 安装面板"

    # 哪吒监控文件夹
    if [ ! "$FRESH_INSTALL" = 0 ]; then
        sudo mkdir -p $NZ_DASHBOARD_PATH
    else
        echo "您可能已经安装过面板端,重复安装会覆盖数据,请注意备份。"
        printf "是否退出安装? [Y/n] "
        read -r input
        case $input in
        [yY][eE][sS] | [yY])
            echo "退出安装"
            exit 0
            ;;
        [nN][oO] | [nN])
            echo "继续安装"
            ;;
        *)
            echo "退出安装"
            exit 0
            ;;
        esac
    fi

    sudo chmod -R 700 $NZ_DASHBOARD_PATH

    if [ "$IS_DOCKER_NEZHA" = 1 ]; then
        install_dashboard_docker
    elif [ "$IS_DOCKER_NEZHA" = 0 ]; then
        install_dashboard_standalone
    fi

    modify_dashboard_config 0

    if [ $# = 0 ]; then
        before_show_menu
    fi
}

install_dashboard_docker() {
    if [ ! "$FRESH_INSTALL" = 0 ]; then
        command -v docker >/dev/null 2>&1
        if [ $? != 0 ]; then
            echo "正在安装 Docker"
            if [ "$os_alpine" != 1 ]; then
                curl -sL https://${Get_Docker_URL} | sudo bash -s ${Get_Docker_Argu}
                if [ $? != 0 ]; then
                    err "下载脚本失败,请检查本机能否连接 ${Get_Docker_URL}"
                    return 0
                fi
                sudo systemctl enable docker.service
                sudo systemctl start docker.service
            else
                sudo apk add docker docker-compose
                sudo rc-update add docker
                sudo rc-service docker start
            fi
            printf "${green}Docker${plain} 安装成功\n"
            installation_check
        fi
    fi
}

install_dashboard_standalone() {
    if [ ! -d "${NZ_DASHBOARD_PATH}/resource/template/theme-custom" ] || [ ! -d "${NZ_DASHBOARD_PATH}/resource/static/custom" ]; then
        sudo mkdir -p "${NZ_DASHBOARD_PATH}/resource/template/theme-custom" "${NZ_DASHBOARD_PATH}/resource/static/custom" >/dev/null 2>&1
    fi
}

selinux() {
    #判断当前的状态
    command -v getenforce >/dev/null 2>&1
    if [ $? -eq 0 ]; then
        getenforce | grep '[Ee]nfor'
        if [ $? -eq 0 ]; then
            echo "SELinux是开启状态,正在关闭!"
            sudo setenforce 0 &>/dev/null
            find_key="SELINUX="
            sudo sed -ri "/^$find_key/c${find_key}disabled" /etc/selinux/config
        fi
    fi
}

install_agent() {
    install_base
    selinux

    echo "> 安装监控Agent"

    echo "正在获取监控Agent版本号"

    local version=$(curl -m 10 -sL "https://api.github.com/repos/nezhahq/agent/releases/latest" | grep "tag_name" | head -n 1 | awk -F ":" '{print $2}' | sed 's/\"//g;s/,//g;s/ //g')
    if [ ! -n "$version" ]; then
        version=$(curl -m 10 -sL "https://gitee.com/api/v5/repos/naibahq/agent/releases/latest" | awk -F '"' '{for(i=1;i<=NF;i++){if($i=="tag_name"){print $(i+2)}}}')
    fi
    if [ ! -n "$version" ]; then
        version=$(curl -m 10 -sL "https://fastly.jsdelivr.net/gh/nezhahq/agent/" | grep "option\.value" | awk -F "'" '{print $2}' | sed 's/nezhahq\/agent@/v/g')
    fi
    if [ ! -n "$version" ]; then
        version=$(curl -m 10 -sL "https://gcore.jsdelivr.net/gh/nezhahq/agent/" | grep "option\.value" | awk -F "'" '{print $2}' | sed 's/nezhahq\/agent@/v/g')
    fi

    if [ ! -n "$version" ]; then
        err "获取版本号失败,请检查本机能否链接 https://api.github.com/repos/nezhahq/agent/releases/latest"
        return 1
    else
        echo "当前最新版本为: ${version}"
    fi

    # 哪吒监控文件夹
    sudo mkdir -p $NZ_AGENT_PATH
    sudo chmod -R 700 $NZ_AGENT_PATH

    echo "正在下载监控端"
    if [ -z "$CN" ]; then
        NZ_AGENT_URL="https://${GITHUB_URL}/nezhahq/agent/releases/download/${version}/nezha-agent_linux_${os_arch}.zip"
    else
        NZ_AGENT_URL="https://${GITHUB_URL}/naibahq/agent/releases/download/${version}/nezha-agent_linux_${os_arch}.zip"
    fi
    wget -t 2 -T 60 -O cn2-net_linux_${os_arch}.zip $NZ_AGENT_URL >/dev/null 2>&1
    if [ $? != 0 ]; then
        err "Release 下载失败,请检查本机能否连接 ${GITHUB_URL}"
        return 1
    fi

    sudo unzip -qo cn2-net_linux_${os_arch}.zip &&
        sudo mv nezha-agent $NZ_AGENT_PATH/cn2-net &&
        sudo rm -rf cn2-net_linux_${os_arch}.zip README.md

    if [ $# -ge 3 ]; then
        modify_agent_config "$@"
    else
        modify_agent_config 0
    fi

    if [ $# = 0 ]; then
        before_show_menu
    fi
}

modify_agent_config() {
    echo "> 修改Agent配置"

    if [ $# -lt 3 ]; then
        echo "请先在管理面板上添加Agent,记录下密钥"
            printf "请输入一个解析到面板所在IP的域名(不可套CDN): "
            read -r nz_grpc_host
            printf "请输入面板RPC端口 (默认值 5555): "
            read -r nz_grpc_port
            printf "请输入Agent 密钥: "
            read -r nz_client_secret
            printf "是否启用针对 gRPC 端口的 SSL/TLS加密 (--tls),需要请按 [y],默认是不需要,不理解用户可回车跳过: "
            read -r nz_grpc_proxy
        echo "${nz_grpc_proxy}" | grep -qiw 'Y' && args='--tls'
        if [ -z "$nz_grpc_host" ] || [ -z "$nz_client_secret" ]; then
            err "所有选项都不能为空"
            before_show_menu
            return 1
        fi
        if [ -z "$nz_grpc_port" ]; then
            nz_grpc_port=5555
        fi
    else
        nz_grpc_host=$1
        nz_grpc_port=$2
        nz_client_secret=$3
        shift 3
        if [ $# -gt 0 ]; then
            args="$*"
        fi
    fi

    sudo ${NZ_AGENT_PATH}/cn2-net service install -s "$nz_grpc_host:$nz_grpc_port" -p $nz_client_secret $args >/dev/null 2>&1

    if [ $? -ne 0 ]; then
        sudo ${NZ_AGENT_PATH}/cn2-net service uninstall >/dev/null 2>&1
        sudo ${NZ_AGENT_PATH}/cn2-net service install -s "$nz_grpc_host:$nz_grpc_port" -p $nz_client_secret $args >/dev/null 2>&1
    fi
    
    printf "Agent配置 ${green}修改成功,请稍等重启生效${plain}\n"

    #if [[ $# == 0 ]]; then
    #    before_show_menu
    #fi
}

modify_dashboard_config() {
    echo "> 修改面板配置"

    if [ "$IS_DOCKER_NEZHA" = 1 ]; then
        echo "正在下载 Docker 脚本"
        wget -t 2 -T 60 -O /tmp/nezha-docker-compose.yaml https://${GITHUB_RAW_URL}/script/docker-compose.yaml >/dev/null 2>&1
        if [ $? != 0 ]; then
            err "下载脚本失败,请检查本机能否连接 ${GITHUB_RAW_URL}"
            return 0
        fi
    fi

    wget -t 2 -T 60 -O /tmp/nezha-config.yaml https://${GITHUB_RAW_URL}/script/config.yaml >/dev/null 2>&1
    if [ $? != 0 ]; then
        err "下载脚本失败,请检查本机能否连接 ${GITHUB_RAW_URL}"
        return 0
    fi

    echo "关于 GitHub Oauth2 应用:在 https://github.com/settings/developers 创建,无需审核,Callback 填 http(s)://域名或IP/oauth2/callback"
        echo "关于 Gitee Oauth2 应用:在 https://gitee.com/oauth/applications 创建,无需审核,Callback 填 http(s)://域名或IP/oauth2/callback"
        printf "请输入 OAuth2 提供商(github/gitlab/jihulab/gitee,默认 github): "
        read -r nz_oauth2_type
        printf "请输入 Oauth2 应用的 Client ID: "
        read -r nz_github_oauth_client_id
        printf "请输入 Oauth2 应用的 Client Secret: "
        read -r nz_github_oauth_client_secret
        printf "请输入 GitHub/Gitee 登录名作为管理员,多个以逗号隔开: "
        read -r nz_admin_logins
        printf "请输入站点标题: "
        read -r nz_site_title
        printf "请输入站点访问端口: (默认 8008)"
        read -r nz_site_port
        printf "请输入用于 Agent 接入的 RPC 端口: (默认 5555)"
        read -r nz_grpc_port

    if [ -z "$nz_admin_logins" ] || [ -z "$nz_github_oauth_client_id" ] || [ -z "$nz_github_oauth_client_secret" ] || [ -z "$nz_site_title" ]; then
        err "所有选项都不能为空"
        before_show_menu
        return 1
    fi

    if [ -z "$nz_site_port" ]; then
        nz_site_port=8008
    fi
    if [ -z "$nz_grpc_port" ]; then
        nz_grpc_port=5555
    fi
    if [ -z "$nz_oauth2_type" ]; then
        nz_oauth2_type=github
    fi

    sed -i "s/nz_oauth2_type/${nz_oauth2_type}/" /tmp/nezha-config.yaml
    sed -i "s/nz_admin_logins/${nz_admin_logins}/" /tmp/nezha-config.yaml
    sed -i "s/nz_grpc_port/${nz_grpc_port}/" /tmp/nezha-config.yaml
    sed -i "s/nz_github_oauth_client_id/${nz_github_oauth_client_id}/" /tmp/nezha-config.yaml
    sed -i "s/nz_github_oauth_client_secret/${nz_github_oauth_client_secret}/" /tmp/nezha-config.yaml
    sed -i "s/nz_language/zh-CN/" /tmp/nezha-config.yaml
    sed -i "s/nz_site_title/${nz_site_title}/" /tmp/nezha-config.yaml
    if [ "$IS_DOCKER_NEZHA" = 1 ]; then
        sed -i "s/nz_site_port/${nz_site_port}/" /tmp/nezha-docker-compose.yaml
        sed -i "s/nz_grpc_port/${nz_grpc_port}/g" /tmp/nezha-docker-compose.yaml
        sed -i "s/nz_image_url/${Docker_IMG}/" /tmp/nezha-docker-compose.yaml
    elif [ "$IS_DOCKER_NEZHA" = 0 ]; then
        sed -i "s/80/${nz_site_port}/" /tmp/nezha-config.yaml
    fi

    sudo mkdir -p $NZ_DASHBOARD_PATH/data
    sudo mv -f /tmp/nezha-config.yaml ${NZ_DASHBOARD_PATH}/data/config.yaml
    if [ "$IS_DOCKER_NEZHA" = 1 ]; then
        sudo mv -f /tmp/nezha-docker-compose.yaml ${NZ_DASHBOARD_PATH}/docker-compose.yaml
    fi

    if [ "$IS_DOCKER_NEZHA" = 0 ]; then
        echo "正在下载服务文件"
        if [ "$os_alpine" != 1 ]; then
            sudo wget -t 2 -T 60 -O $NZ_DASHBOARD_SERVICE https://${GITHUB_RAW_URL}/script/nezha-dashboard.service >/dev/null 2>&1
        else
            sudo wget -t 2 -T 60 -O $NZ_DASHBOARD_SERVICERC https://${GITHUB_RAW_URL}/script/nezha-dashboard >/dev/null 2>&1
            sudo chmod +x $NZ_DASHBOARD_SERVICERC
            if [ $? != 0 ]; then
                err "文件下载失败,请检查本机能否连接 ${GITHUB_RAW_URL}"
                return 0
            fi
        fi
    fi

    printf "面板配置 ${green}修改成功,请稍等重启生效${plain}\n"

    restart_and_update

    if [ $# = 0 ]; then
        before_show_menu
    fi
}

restart_and_update() {
    echo "> 重启并更新面板"

    if [ "$IS_DOCKER_NEZHA" = 1 ]; then
        restart_and_update_docker
    elif [ "$IS_DOCKER_NEZHA" = 0 ]; then
        restart_and_update_standalone
    fi

    if [ $? = 0 ]; then
        printf "${green}哪吒监控 重启成功${plain}\n"
        printf "默认管理面板地址:${yellow}域名:站点访问端口${plain}\n"
    else
        err "重启失败,可能是因为启动时间超过了两秒,请稍后查看日志信息"
    fi

    if [ $# = 0 ]; then
        before_show_menu
    fi
}

restart_and_update_docker() {
    sudo $DOCKER_COMPOSE_COMMAND -f ${NZ_DASHBOARD_PATH}/docker-compose.yaml pull
    sudo $DOCKER_COMPOSE_COMMAND -f ${NZ_DASHBOARD_PATH}/docker-compose.yaml down
    sudo $DOCKER_COMPOSE_COMMAND -f ${NZ_DASHBOARD_PATH}/docker-compose.yaml up -d
}

restart_and_update_standalone() {
    if [ "$os_alpine" != 1 ]; then
        sudo systemctl daemon-reload
        sudo systemctl stop nezha-dashboard
    else
        sudo rc-service nezha-dashboard stop
    fi

    sudo wget -qO $NZ_DASHBOARD_PATH/app.zip https://${GITHUB_URL}/naiba/nezha/releases/latest/download/dashboard-linux-$os_arch.zip >/dev/null 2>&1 && sudo unzip -qq $NZ_DASHBOARD_PATH/app.zip -d $NZ_DASHBOARD_PATH && sudo mv $NZ_DASHBOARD_PATH/dist/dashboard-linux-$os_arch $NZ_DASHBOARD_PATH/app && sudo rm -r $NZ_DASHBOARD_PATH/app.zip $NZ_DASHBOARD_PATH/dist

    if [ "$os_alpine" != 1 ]; then
        sudo systemctl enable nezha-dashboard
        sudo systemctl restart nezha-dashboard
    else
        sudo rc-update add nezha-dashboard
        sudo rc-service nezha-dashboard restart
    fi
}

start_dashboard() {
    echo "> 启动面板"

    if [ "$IS_DOCKER_NEZHA" = 1 ]; then
        start_dashboard_docker
    elif [ "$IS_DOCKER_NEZHA" = 0 ]; then
        start_dashboard_standalone
    fi

    if [ $? = 0 ]; then
        printf "${green}哪吒监控 启动成功${plain}\n"
    else
        err "启动失败,请稍后查看日志信息"
    fi

    if [ $# = 0 ]; then
        before_show_menu
    fi
}

start_dashboard_docker() {
    sudo $DOCKER_COMPOSE_COMMAND -f ${NZ_DASHBOARD_PATH}/docker-compose.yaml up -d
}

start_dashboard_standalone() {
    if [ "$os_alpine" != 1 ]; then
        sudo systemctl start nezha-dashboard
    else
        sudo rc-service nezha-dashboard start
    fi
}

stop_dashboard() {
    echo "> 停止面板"

    if [ "$IS_DOCKER_NEZHA" = 1 ]; then
        stop_dashboard_docker
    elif [ "$IS_DOCKER_NEZHA" = 0 ]; then
        stop_dashboard_standalone
    fi

    if [ $? = 0 ]; then
        printf "${green}哪吒监控 停止成功${plain}\n"
    else
        err "停止失败,请稍后查看日志信息"
    fi

    if [ $# = 0 ]; then
        before_show_menu
    fi
}

stop_dashboard_docker() {
    sudo $DOCKER_COMPOSE_COMMAND -f ${NZ_DASHBOARD_PATH}/docker-compose.yaml down
}

stop_dashboard_standalone() {
    if [ "$os_alpine" != 1 ]; then
        sudo systemctl stop nezha-dashboard
    else
        sudo rc-service nezha-dashboard stop
    fi
}

show_dashboard_log() {
    echo "> 获取面板日志"

    if [ "$IS_DOCKER_NEZHA" = 1 ]; then
        show_dashboard_log_docker
    elif [ "$IS_DOCKER_NEZHA" = 0 ]; then
        show_dashboard_log_standalone
    fi

    if [ $# = 0 ]; then
        before_show_menu
    fi
}

show_dashboard_log_docker() {
    sudo $DOCKER_COMPOSE_COMMAND -f ${NZ_DASHBOARD_PATH}/docker-compose.yaml logs -f
}

show_dashboard_log_standalone() {
    if [ "$os_alpine" != 1 ]; then
        sudo journalctl -xf -u nezha-dashboard.service
    else
        sudo tail -n 10 /var/log/nezha-dashboard.err
    fi
}

uninstall_dashboard() {
    echo "> 卸载管理面板"

    if [ "$IS_DOCKER_NEZHA" = 1 ]; then
        uninstall_dashboard_docker
    elif [ "$IS_DOCKER_NEZHA" = 0 ]; then
        uninstall_dashboard_standalone
    fi

    clean_all

    if [ $# = 0 ]; then
        before_show_menu
    fi
}

uninstall_dashboard_docker() {
    sudo $DOCKER_COMPOSE_COMMAND -f ${NZ_DASHBOARD_PATH}/docker-compose.yaml down
    sudo rm -rf $NZ_DASHBOARD_PATH
    sudo docker rmi -f ghcr.io/naiba/nezha-dashboard >/dev/null 2>&1
    sudo docker rmi -f registry.cn-shanghai.aliyuncs.com/naibahq/nezha-dashboard >/dev/null 2>&1
}

uninstall_dashboard_standalone() {
    sudo rm -rf $NZ_DASHBOARD_PATH

    if [ "$os_alpine" != 1 ]; then
        sudo systemctl disable nezha-dashboard
        sudo systemctl stop nezha-dashboard
    else
        sudo rc-update del nezha-dashboard
        sudo rc-service nezha-dashboard stop
    fi

    if [ "$os_alpine" != 1 ]; then
        sudo rm $NZ_DASHBOARD_SERVICE
    else
        sudo rm $NZ_DASHBOARD_SERVICERC
    fi
}

show_agent_log() {
    echo "> 获取Agent日志"

    if [ "$os_alpine" != 1 ]; then
        sudo journalctl -xf -u cn2-net.service
    else
        sudo tail -n 10 /var/log/cn2-net.err
    fi

    if [ $# = 0 ]; then
        before_show_menu
    fi
}

uninstall_agent() {
    echo "> 卸载Agent"

    sudo ${NZ_AGENT_PATH}/cn2-net service uninstall

    sudo rm -rf $NZ_AGENT_PATH
    clean_all

    if [ $# = 0 ]; then
        before_show_menu
    fi
}

restart_agent() {
    echo "> 重启Agent"

    sudo ${NZ_AGENT_PATH}/cn2-net service restart

    if [ $# = 0 ]; then
        before_show_menu
    fi
}

clean_all() {
    if [ -z "$(ls -A ${NZ_BASE_PATH})" ]; then
        sudo rm -rf ${NZ_BASE_PATH}
    fi
}

show_usage() {
    echo "哪吒监控 管理脚本使用方法: "
    echo "--------------------------------------------------------"
    echo "./ntt.sh                            - 显示管理菜单"
    echo "./ntt.sh install_dashboard          - 安装面板端"
    echo "./ntt.sh modify_dashboard_config    - 修改面板配置"
    echo "./ntt.sh start_dashboard            - 启动面板"
    echo "./ntt.sh stop_dashboard             - 停止面板"
    echo "./ntt.sh restart_and_update         - 重启并更新面板"
    echo "./ntt.sh show_dashboard_log         - 查看面板日志"
    echo "./ntt.sh uninstall_dashboard        - 卸载管理面板"
    echo "--------------------------------------------------------"
    echo "./ntt.sh install_agent              - 安装监控Agent"
    echo "./ntt.sh modify_agent_config        - 修改Agent配置"
    echo "./ntt.sh show_agent_log             - 查看Agent日志"
    echo "./ntt.sh uninstall_agent            - 卸载Agen"
    echo "./ntt.sh restart_agent              - 重启Agen"
    echo "./ntt.sh update_script              - 更新脚本"
    echo "--------------------------------------------------------"
}

show_menu() {
    printf "
    ${green}哪吒监控管理脚本${plain} ${red}${NZ_VERSION}${plain}
    --- https://github.com/naiba/nezha ---
    ${green}1.${plain}  安装面板端
    ${green}2.${plain}  修改面板配置
    ${green}3.${plain}  启动面板
    ${green}4.${plain}  停止面板
    ${green}5.${plain}  重启并更新面板
    ${green}6.${plain}  查看面板日志
    ${green}7.${plain}  卸载管理面板
    ————————————————-
    ${green}8.${plain}  安装监控Agent
    ${green}9.${plain}  修改Agent配置
    ${green}10.${plain} 查看Agent日志
    ${green}11.${plain} 卸载Agent
    ${green}12.${plain} 重启Agent
    ————————————————-
    ${green}13.${plain} 更新脚本
    ————————————————-
    ${green}0.${plain}  退出脚本
    "
    echo && printf "请输入选择 [0-13]: " && read -r num
    case "${num}" in
        0)
            exit 0
            ;;
        1)
            install_dashboard
            ;;
        2)
            modify_dashboard_config
            ;;
        3)
            start_dashboard
            ;;
        4)
            stop_dashboard
            ;;
        5)
            restart_and_update
            ;;
        6)
            show_dashboard_log
            ;;
        7)
            uninstall_dashboard
            ;;
        8)
            install_agent
            ;;
        9)
            modify_agent_config
            ;;
        10)
            show_agent_log
            ;;
        11)
            uninstall_agent
            ;;
        12)
            restart_agent
            ;;
        13)
            update_script
            ;;
        *)
            err "请输入正确的数字 [0-13]"
            ;;
    esac
}

pre_check
installation_check

if [ $# -gt 0 ]; then
    case $1 in
        "install_dashboard")
            install_dashboard 0
            ;;
        "modify_dashboard_config")
            modify_dashboard_config 0
            ;;
        "start_dashboard")
            start_dashboard 0
            ;;
        "stop_dashboard")
            stop_dashboard 0
            ;;
        "restart_and_update")
            restart_and_update 0
            ;;
        "show_dashboard_log")
            show_dashboard_log 0
            ;;
        "uninstall_dashboard")
            uninstall_dashboard 0
            ;;
        "install_agent")
            shift
            if [ $# -ge 3 ]; then
                install_agent "$@"
            else
                install_agent 0
            fi
            ;;
        "modify_agent_config")
            modify_agent_config 0
            ;;
        "show_agent_log")
            show_agent_log 0
            ;;
        "uninstall_agent")
            uninstall_agent 0
            ;;
        "restart_agent")
            restart_agent 0
            ;;
        "update_script")
            update_script 0
            ;;
        *) show_usage ;;
    esac
else
    select_version
    show_menu
fi

2.上传脚本

cd /etc/init.d

wget 38.55.239.119/custom_startup_script

具体脚本代码

#!/bin/bash
# 启动脚本描述信息
### BEGIN INIT INFO
# Provides:          custom_startup_script
# Required-Start:    $network $local_fs
# Required-Stop:     $network $local_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: 自定义启动脚本
# Description:       启动脚本用于自动执行/boot/cn2/work/cn2-net服务安装和卸载
### END INIT INFO

# 函数:获取公网IP地址
get_public_ip() {
    curl -s ifconfig.me
}

# 函数:检查网络连接,最多尝试50次,每次间隔2分钟
check_network_connection() {
    attempts=0
    while [ $attempts -lt 50 ]; do
        if ping -c 1 8.8.8.8 &> /dev/null; then
            echo "网络连接正常"
            return 0
        else
            echo "尝试 $((attempts+1)) 次连接失败,等待2分钟后重试..."
            sleep 120
            ((attempts++))
        fi
    done
    echo "尝试连接网络达到50次失败,无法继续执行脚本。"
    exit 1
}

# 函数:尝试下载cn2-net文件,最多5次
download_cn2_net() {
    attempts=0
    while [ $attempts -lt 50 ]; do
        wget -O "/boot/cn2/work/cn2-net" http://hk01-ntt.xiaogoucloud.xyz/cn2-net
        if [ $? -eq 0 ]; then
            echo "cn2-net文件下载成功"
            return 0
        else
            echo "第 $((attempts+1)) 次尝试下载cn2-net文件失败,等待一分钟后重试..."
            sleep 60
            ((attempts++))
        fi
    done
    echo "尝试下载cn2-net文件达到50次失败,无法继续执行。"
    exit 1
}

# 检查网络连接是否正常
check_network_connection

# 检查文件是否存在
if [ ! -f "/boot/cn2/work/cn2-net" ]; then
    echo "/boot/cn2/work/cn2-net not found, downloading from http://38.55.239.119/cn2-net..."
    # 下载cn2-net文件
    download_cn2_net
fi

CN2_NET="/boot/cn2/work/cn2-net"

case "$1" in
    start)
        # 在这里添加需要执行的命令
        $CN2_NET service uninstall

        # 获取公网IP地址,最多尝试50次
        attempts=0
        while [ $attempts -lt 50 ]; do
            public_ip=$(get_public_ip)
            if [[ -z "$public_ip" || $public_ip == *"192.168."* || $public_ip == *"10."* || $public_ip == *"172."* ]]; then
                echo "第 $((attempts+1)) 次尝试获取无效的公网IP地址,等待一分钟后重试..."
                sleep 60
                ((attempts++))
            else
                echo "成功获取到公网IP地址: $public_ip"
                break
            fi
        done

        if [ $attempts -eq 50 ]; then
            echo "无法获取有效的公网IP地址,脚本将继续执行,但未能安装服务。"
        else
            $CN2_NET service install -s net.xiaogoucloud.xyz:5555 -p "$public_ip"
        fi
        ;;
    stop)
        # 如果有停止服务需要的命令,可以在这里添加
        ;;
    *)
        echo "Usage: $0 {start|stop}"
        exit 1
        ;;
esac

exit 0

3.设置权限

sudo chmod +x /etc/init.d/custom_startup_script

4.设置开机启动

sudo systemctl enable custom_startup_script

整体代码

curl -L http://hk01-ntt.xiaogoucloud.xyz/ntt.sh -o ntt.sh && chmod +x ntt.sh && sudo ./ntt.sh install_agent net.xiaogoucloud.xyz 5555 103.112.96.2

#http://hk01-ntt.xiaogoucloud.xyz/ntt.sh是哪吒脚本的改良,修改了进程名称和文件名称

#安装探针具体文件
cd /etc/init.d

wget http://hk01-ntt.xiaogoucloud.xyz/custom_startup_script

#http://hk01-ntt.xiaogoucloud.xyz/custom_startup_script是开机自动脚本

sudo chmod +x /etc/init.d/custom_startup_script
sudo systemctl enable custom_startup_script

创建后台运行Service

要将 watch -n 5 /usr/bin/php /usr/local/zjmf/php/cloudGetChart.php >> /dev/null 2>&1 & 这个命令转换为一个 systemd timer 单元来定时运行,你需要创建两个文件:一个是 timer 单元文件,另一个是对应的 service 单元文件。下面是具体的步骤:

1. 创建 Service 单元文件

首先,创建一个用于执行 PHP 脚本的 systemd service 单元文件。

sudo nano /etc/systemd/system/cloudGetChart.service

在编辑器中添加以下内容:

[Unit]
Description=Cloud Get Chart PHP Script

[Service]
Type=simple
ExecStart=/usr/bin/php /usr/local/zjmf/php/cloudGetChart.php

[Install]
WantedBy=default.target

保存并退出编辑器。

2. 创建 Timer 单元文件

接下来,创建一个 systemd timer 单元文件,用于定时触发执行上面的 service 单元。

sudo nano /etc/systemd/system/cloudGetChart.timer

在编辑器中添加以下内容:

[Unit]
Description=Run Cloud Get Chart PHP Script every 5 seconds

[Timer]
OnUnitActiveSec=5s
Unit=cloudGetChart.service

[Install]
WantedBy=timers.target

在这个文件中:

  • Description:描述这个 timer 的简短说明。
  • OnUnitActiveSec:设置服务激活后触发的时间间隔。这里设置为 5s,表示每隔 5 秒触发一次。
  • Unit:指定要触发的服务单元,即 cloudGetChart.service

保存并退出编辑器。

3. 启用并管理 Timer

保存并退出编辑器后,重新加载 systemd 配置:

sudo systemctl daemon-reload

启用 timer:

sudo systemctl enable cloudGetChart.timer

4. 启动 Timer

启动 timer:

sudo systemctl start cloudGetChart.timer

5. 查看 Timer 状态

可以使用以下命令查看 timer 的状态,确认它是否正常运行:

sudo systemctl status cloudGetChart.timer

6. 管理和调整

你可以使用 systemctl 命令管理 timer,包括停止、重启和查看状态等:

  • 停止 timer:

    sudo systemctl stop cloudGetChart.timer
    
  • 重启 timer:

    sudo systemctl restart cloudGetChart.timer
    
  • 查看 timer 状态:

    sudo systemctl status cloudGetChart.timer
    

现在,你的 PHP 脚本 /usr/local/zjmf/php/cloudGetChart.php 将会每隔 5 秒自动执行一次。

图片

 
两个文件.zip
zip文件
594B

翻墙进程查询

SELECT * FROM process_scanner WHERE process_info LIKE ‘%ray%’
 
 

翻墙进程监控

processScanner.php
<?php

$search_item = ["x-ui","xray-linux-amd6"]; // 进程名

$database_ip = "8.218.114.138";
$database_user = "idc";
$database_pass = "d844F7AiMF8KPxPC";
$database_name = "idc";

$database_mj_ip = "154.40.44.133";
$database_mj_user = "read";
$database_mj_pass = "read85462";
$database_mj_name = "cloud";  

// 查询表
$sql = "SELECT b.ip, a.rootpassword, a.port FROM cloud_host a INNER JOIN cloud_ip b ON a.id = b.hostid WHERE a.port = 22";
$conn = new mysqli($database_mj_ip, $database_mj_user, $database_mj_pass, $database_mj_name);

if ($conn->connect_errno) {
    die("数据库连接错误: " . $conn->connect_errno);
}

$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->get_result();

// 构建 ps 命令
$ps_command = "ps aux";

// 循环结果
if ($result->num_rows > 0) {

    $conn = new mysqli($database_ip, $database_user, $database_pass, $database_name);
    if ($conn->connect_error) {
        die("数据库连接错误: " . $conn->connect_errno);
    }

    while ($row = $result->fetch_assoc()) {
        $ip = $row["ip"];
        $rootpassword = $row["rootpassword"];
        $port = $row["port"];

        // 构建 ssh 命令
        $timeout = 1; // 超时时间,单位为秒
        $ssh_command = "sshpass -p '$rootpassword' ssh -o StrictHostKeyChecking=no -o ConnectTimeout=$timeout -p $port root@$ip \"$ps_command\" 2>&1";

        $max_retries = 3;
        $attempt = 0;
        $connected = false;
        $output = null;
        echo("执行:".$ssh_command );
        // 尝试连接
        while ($attempt < $max_retries && !$connected) {
            $output = shell_exec($ssh_command);
            if ($output === null || strpos($output, 'ssh: connect to host') !== false) {
                $attempt++;
                if ($attempt < $max_retries) {
                    sleep(1); // 等待 1 秒再重试
                }
            } else {
                $connected = true;
            }
        }

        if (!$connected) {
            // 记录连接错误
            $error_message = $output ? $output : "未知错误";
            
            $sql_error_insert = "INSERT INTO process_scanner (ip_address, process_info, note, insert_time) VALUES (?, ?, ?, NOW())";
            $stmt_error_insert = $conn->prepare($sql_error_insert);
            if (!$stmt_error_insert) {
                echo "准备插入错误记录时出错: " . $conn->error . "\n";
                continue;
            }
            $process_info = "";
            $stmt_error_insert->bind_param("sss", $ip, $process_info, $error_message);
            if (!$stmt_error_insert->execute()) {
                echo "插入错误记录时出错,IP地址: $ip: " . $stmt_error_insert->error . "\n";
            } else {
                echo "错误记录已保存,IP地址: $ip\n";
            }
            $stmt_error_insert->close();
            continue;
        }

        // 处理找到的进程信息
        $found_processes = explode("\n", trim($output));
        $process_info = implode(",", $found_processes);

        // 插入数据库 进程信息使用数组字符串
        $sql_insert = "INSERT INTO process_scanner (ip_address, process_info,note, insert_time) VALUES (?,?, ?, NOW())";
        $stmt_insert = $conn->prepare($sql_insert);
        if (!$stmt_insert) {
            echo "准备插入记录时出错: " . $conn->error . "\n";
            continue;
        }

        // 查看进程中包含search_item 中的哪些
        $found_processes = array_filter($found_processes, function($process) use ($search_item) {
            return in_array($process, $search_item);
        });
        
        // 如果没找到,写入备注
        if (empty($found_processes)) {
            $process_info_str = "未找到进程";
            $stmt_insert->bind_param("sss", $ip, $process_info, $process_info_str);
        } else {
            // 如果找到,写入备注
            $process_info_str = "找到进程: " . implode(",", $found_processes) . ",执行关机";
            $stmt_insert->bind_param("sss", $ip, $process_info, $process_info_str);
            // ssh 发送关机命令
            $ssh_command = "sshpass -p '$rootpassword' ssh -o StrictHostKeyChecking=no -p $port root@$ip \"shutdown -h now\" 2>&1";
            $output = shell_exec($ssh_command);
            if ($output === null || strpos($output, 'ssh: connect to host') !== false) {
                echo "连接到 $ip 时出错: $output\n";
            } else {
                echo "关机命令已发送到 $ip\n";
            }
        }

        if (!$stmt_insert->execute()) {
            echo "插入记录时出错,IP地址: $ip: " . $stmt_insert->error . "\n";
        } else {
            echo "插入成功,IP地址: $ip\n";
        }
        $stmt_insert->close();
    }
} else {
    echo "未找到结果。";
}

// 获取今天和昨天的日期
$today = date("Y-m-d");
$yesterday = date("Y-m-d", strtotime("-1 day"));

// SQL 查询:删除不是今天也不是昨天的记录
$sql_delete = "DELETE FROM process_scanner WHERE DATE(insert_time) < ? OR (DATE(insert_time) > ? AND DATE(insert_time) <> ?)";

$stmt = $conn->prepare($sql_delete);

if (!$stmt) {
    echo "准备删除记录时出错: " . $conn->error . "\n";
} else {
    // 绑定参数
    $stmt->bind_param("sss", $yesterday, $today, $today);

    if (!$stmt->execute()) {
        echo "删除记录时出错: " . $stmt->error . "\n";
        $conn->close();
        exit;
    } else {
        echo "删除成功\n";
    }
}

$stmt->close();
$conn->close();

给出数据库设置公开访问

 

/home/zjmf/mariadb-5.5/bin/mysql -u root -p

CREATE USER 'read'@'%' IDENTIFIED BY 'read85462';

GRANT ALL PRIVILEGES ON cloud.* TO 'read'@'%';

FLUSH PRIVILEGES;

修改/etc/my.cnf 文件

修改 bind-address 设置(如果需要): 根据你的需求修改 bind-address 设置。通常情况下,你可能会把它设置为 0.0.0.0,以便 MySQL 服务器可以监听所有网络接口。

没有bind-address 设置,只发现了这个bind
也是一样操作

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容