adding initial files for watchcat script

This commit is contained in:
Russel Yasol
2024-05-31 19:50:55 +08:00
parent 96566daeea
commit a1598a7206
8 changed files with 607 additions and 181 deletions

View File

@@ -0,0 +1,60 @@
#!/bin/sh
# Function to create and run the Watchcat script
create_and_run_watchcat_script() {
local ip=$1
local timeout=$2
local failure_count=$3
local script_path="/usrdata/simpleadmin/script/watchcat.sh"
# Create the script with the watchcat logic
sudo cat << EOF > $script_path
#!/bin/sh
failures=0
while :; do
if ping -c 1 $ip > /dev/null 2>&1; then
failures=0
else
failures=\$((failures + 1))
if [ "\$failures" -ge "$failure_count" ]; then
echo "Rebooting system due to \$failures consecutive ping failures."
/sbin/reboot
exit 0
fi
fi
sleep $timeout
done
EOF
# Make the watchcat script executable
chmod +x $script_path
# Create a JSON to be fetched later
echo "{\"enabled\": true, \"track_ip\": \"$ip\", \"ping_timeout\": $timeout, \"ping_failure_count\": $failure_count}" > /usrdata/simpleadmin/script/watchcat.json
# Check if the script was created successfully
if [ -f "$script_path" ]; then
# Make the script executable
chmod +x "$script_path"
# Run the script in the background
# nohup /bin/sh "$script_path" &
/bin/sh "$script_path" &
echo "Watchcat script created and running."
else
echo "Failed to create the Watchcat script."
echo "Please check the script path: $script_path"
fi
}
# Check if the script is called with the required parameters
if [ "$#" -ne 3 ]; then
echo "Usage: $0 <IP> <timeout> <failure_count>"
exit 1
fi
# Call the function with the provided arguments
create_and_run_watchcat_script "$1" "$2" "$3"

View File

@@ -0,0 +1,32 @@
#!/bin/sh
# Function to remove the Watchcat script and JSON file
remove_watchcat_script() {
local script_path="/usrdata/simpleadmin/script/watchcat.sh"
local json_path="/usrdata/simpleadmin/script/watchcat.json"
# Mount as read-write
mount -o remount,rw /
# Remove the watchcat script if it exists
if [ -f "$script_path" ]; then
rm "$script_path"
echo "Removed $script_path"
else
echo "$script_path does not exist"
fi
# Remove the JSON file if it exists
if [ -f "$json_path" ]; then
rm "$json_path"
echo "Removed $json_path"
else
echo "$json_path does not exist"
fi
# Mount as read-only
mount -o remount,ro /
}
# Call the function to remove the scripts
remove_watchcat_script

View File

@@ -4,15 +4,14 @@
echo "Content-type: application/json" echo "Content-type: application/json"
echo "" echo ""
# This script fetches the watchCat parameters from the /tmp/watchCatParams.json file and returns it as JSON # This script fetches the watchCat parameters from the /tmp/watchcat.json and returns it as JSON
# Example content of /tmp/watchcat:
# {"watchcat": {"enabled": true, "track_ip": "1.1.1.1", "ping_timeout": 30, "ping_failure_count": 10}}
# Check if the file exists # Check if the file exists
if [ -f /tmp/watchCatParams.json ]; then if [ -f /tmp/watchcat.json ]; then
# Read the file and return the content cat /tmp/watchcat.json
cat /tmp/watchCatParams.json
else else
# Return an empty JSON object # return an empty JSON object
echo "{}" echo "{}"
fi fi
exit 0

View File

@@ -48,6 +48,9 @@ if [ -n "${setTTL}" ]; then
ttlenabled=false ttlenabled=false
ttlvalue=0 ttlvalue=0
fi fi
log_debug "Starting service to apply rules"
/usrdata/simplefirewall/ttl-override start
fi fi
echo "Content-type: text/text" echo "Content-type: text/text"

View File

@@ -0,0 +1,72 @@
#!/bin/bash
# Decode URL-encoded strings
function urldecode() {
local data=${1//+/ }
printf '%b' "${data//%/\\x}"
}
# Parse QUERY_STRING
QUERY_STRING=$(echo "${QUERY_STRING}" | sed 's/;//g')
if [ "${QUERY_STRING}" ]; then
export IFS="&"
for cmd in ${QUERY_STRING}; do
if [[ "$cmd" == *"="* ]]; then
key=$(echo $cmd | awk -F '=' '{print $1}')
value=$(echo $cmd | awk -F '=' '{print $2}')
eval $key=$(urldecode $value)
fi
done
fi
# Set default values
WATCHCAT_ENABLED=${WATCHCAT_ENABLED:-"disable"}
TRACK_IP=${TRACK_IP:-"1.1.1.1"}
PING_TIMEOUT=${PING_TIMEOUT:-30}
PING_FAILURE_COUNT=${PING_FAILURE_COUNT:-3}
# Validate input
if ! [[ "$WATCHCAT_ENABLED" =~ ^(enable|disable)$ ]]; then
echo "Content-type: text/plain"
echo ""
echo "Invalid value for WATCHCAT_ENABLED. Use 'enable' or 'disable'."
exit 1
fi
if ! [[ "$TRACK_IP" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]]; then
echo "Content-type: text/plain"
echo ""
echo "Invalid IP address format for TRACK_IP."
exit 1
fi
if ! [[ "$PING_TIMEOUT" =~ ^[0-9]+$ ]] || [ "$PING_TIMEOUT" -le 0 ]; then
echo "Content-type: text/plain"
echo ""
echo "PING_TIMEOUT must be a positive integer."
exit 1
fi
if ! [[ "$PING_FAILURE_COUNT" =~ ^[0-9]+$ ]] || [ "$PING_FAILURE_COUNT" -le 0 ]; then
echo "Content-type: text/plain"
echo ""
echo "PING_FAILURE_COUNT must be a positive integer."
exit 1
fi
# Implement the Watchcat logic
if [ "$WATCHCAT_ENABLED" == "enable" ]; then
echo "Content-type: text/plain"
echo ""
echo "Watchcat is enabled. Tracking IP: $TRACK_IP, Ping timeout: $PING_TIMEOUT seconds, Ping failure count: $PING_FAILURE_COUNT"
# Call the create script here and use the needed parameters
sudo /usrdata/simpleadmin/script/create_watchcat.sh "$TRACK_IP" "$PING_TIMEOUT" "$PING_FAILURE_COUNT"
else
echo "Content-type: text/plain"
echo ""
echo "Watchcat is disabled."
# Call the remove script here
sudo /usrdata/simpleadmin/script/remove_watchcat.sh
fi
exit 0

View File

@@ -128,7 +128,7 @@
class="btn btn-primary me-md-2" class="btn btn-primary me-md-2"
type="button" type="button"
x-on:click="startCellScan()" x-on:click="startCellScan()"
:disabled='isLoading === true || cellScanMode === "Unspecified" || cellScanMode === "Select Scan Mode"' :disabled="isLoading === true || cellScanMode === 'Unspecified' || cellScanMode === 'Select Scan Mode'"
x-text="isCellScanning ? 'Scanning... Please wait.' : 'Start Cell Scan'" x-text="isCellScanning ? 'Scanning... Please wait.' : 'Start Cell Scan'"
></button> ></button>
<button <button

View File

@@ -4,12 +4,6 @@
<meta charset="utf-8" /> <meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Simple Admin</title> <title>Simple Admin</title>
<!-- <link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH"
crossorigin="anonymous"
/> -->
<!-- Import all the bootstrap css files from css folder --> <!-- Import all the bootstrap css files from css folder -->
<link rel="stylesheet" href="css/styles.css" /> <link rel="stylesheet" href="css/styles.css" />
<link rel="stylesheet" href="css/bootstrap.min.css" /> <link rel="stylesheet" href="css/bootstrap.min.css" />
@@ -23,8 +17,8 @@
<style> <style>
.form-switch .form-check-input { .form-switch .form-check-input {
width: 3em; width: 2.4em;
height: 1.5em; height: 1.2em;
} }
</style> </style>
</head> </head>
@@ -104,7 +98,8 @@
role="switch" role="switch"
id="watchCatSwitch" id="watchCatSwitch"
x-model="watchCatStatus" x-model="watchCatStatus"
disabled :disabled="!isFormComplete"
x-on:change="setWatchCatSettings"
/> />
</div> </div>
</div> </div>
@@ -147,7 +142,7 @@
aria-label="Ping Timeout" aria-label="Ping Timeout"
aria-describedby="inputGroup-sizing-default" aria-describedby="inputGroup-sizing-default"
placeholder="Enter Ping Timeout in Seconds." placeholder="Enter Ping Timeout in Seconds."
x-model="cooldown" x-model="pingTimeout"
/> />
</div> </div>
@@ -158,113 +153,7 @@
aria-label="Sizing example input" aria-label="Sizing example input"
aria-describedby="inputGroup-sizing-default" aria-describedby="inputGroup-sizing-default"
placeholder="Enter Ping Failure Amount." placeholder="Enter Ping Failure Amount."
x-model="failures" x-model="pingFailureCount"
/>
</div>
</div>
</div>
<div class="row mt-3 mb-5 align-content-center mx-4">
<div class="col">
<div class="mt-3">
<label>Sim Auto Switch</label>
</div>
</div>
<div class="col-5">
<div class="mt-2">
<div class="form-check form-switch form-switch-lg">
<input
class="form-check-input"
type="checkbox"
role="switch"
id="simAutoSwitch"
x-model="simAutoSwitchStatus"
disabled
/>
</div>
</div>
</div>
</div>
<div class="row mt-3 mb-3 align-items-center mx-4">
<div class="col">
<div class="mt-3 mb-4">
<label> Select Preferred SIM </label>
</div>
<div class="mt-3 mb-4">
<label> SIM 1 APN </label>
</div>
<div class="mt-3 mb-4">
<label> SIM 2 APN </label>
</div>
<div class="mt-3 mb-4">
<label> Failover Interval </label>
</div>
<div class="mt-3 mb-4">
<label> Scheduled SIM Hot Swap</label>
</div>
</div>
<div class="col-5">
<div class="mt-3 mb-3">
<select
class="form-select"
aria-label="Select Sim"
x-model="preferredSim"
>
<option selected>Select SIM</option>
<option value="1">SIM 1</option>
<option value="2">SIM 2</option>
</select>
</div>
<div class="mt-3 mb-3">
<input
type="number"
class="form-control"
aria-label="SIM 1 APN"
aria-describedby="inputGroup-sizing-default"
placeholder="Input APN for SIM 1. (Optional)"
x-model="sim1APN"
/>
</div>
<div class="mt-3 mb-3">
<input
type="number"
class="form-control"
aria-label="SIM 2 APN"
aria-describedby="inputGroup-sizing-default"
placeholder="Input APN for SIM 2. (Optional)"
x-model="sim2APN"
/>
</div>
<div class="mt-3 mb-3 d-flex align-items-center">
<select
class="form-select"
aria-label="Failover Interval"
>
<option selected>Failover Interval</option>
<option value="5">5</option>
<option value="10">10</option>
<option value="15">15</option>
<option value="20">20</option>
</select>
<label class="mx-3">Minutes</label>
</div>
<div class="mt-3 mb-3">
<input
type="time"
class="form-control"
aria-label="Scheduled SIM Hot Swap"
aria-describedby="inputGroup-sizing-default"
x-model="scheduledSIMHotSwap"
/> />
</div> </div>
</div> </div>
@@ -272,89 +161,109 @@
</div> </div>
</div> </div>
<div class="card-footer"> <div class="card-footer">
<!-- Setting a low ping timeout and ping failure count may cause
intermittent disconnections due to high sensitivity. <br />
Select appropriate values for both based on your needs.<br /> -->
Still under development. Coming soon... Still under development. Coming soon...
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<div class="row mt-3 mb-3">
<div class="col">
<div class="card">
<div class="card-header">Simple Watchcat Logs</div>
<div class="card-body">
<div class="card-text">
<div class="form-floating">
<textarea
class="form-control"
placeholder="Leave a comment here"
id="floatingTextarea2"
style="height: 100px"
x-text="response"
readonly
></textarea>
<label for="floatingTextarea2">Logs</label>
</div>
</div>
</div>
<div class="card-footer">
No log is provided when successfully enabling the watchcat.
</div>
</div>
</div>
</div>
</div> </div>
</main> </main>
<script src="js/dark-mode.js"></script> <script src="js/dark-mode.js"></script>
<script> <script>
function simpleWatchCat() { function simpleWatchCat() {
return { return {
watchCatStatus: "", watchCatStatus: false, // Initialize as false (not enabled)
trackIP: "", trackIP: "",
cooldown: "", pingTimeout: "",
failures: "", pingFailureCount: "",
response: "", response: "",
formCompleted: false,
simAutoSwitchStatus: "",
scheduledSIMHotSwap: "",
sim1APN: "",
sim2APN: "",
preferredSim: "",
simFormCompleted: false,
modifyWatchCatScript() {
// If one of the params is empty then use their corresponding default values
if (this.IpDNS === "") {
this.IpDNS = "1.1.1.1";
} else if (this.cooldown === "") {
this.cooldown = "30";
} else if (this.failures === "") {
this.failures = "5";
} else if (this.action === "") {
this.action = "Reboot";
}
setWatchCatSettings() {
fetch( fetch(
"/cgi-bin/get_atcommand?" + "/cgi-bin/watchcat_maker?" +
new URLSearchParams({ new URLSearchParams({
status: this.status, WATCHCAT_ENABLED: this.watchCatStatus ? "enable" : "disable",
IpDNS: this.IpDNS, TRACK_IP: this.trackIP,
cooldown: this.cooldown, PING_TIMEOUT: this.pingTimeout,
failures: this.failures, PING_FAILURE_COUNT: this.pingFailureCount,
action: this.action,
}) })
) )
.then((response) => { .then((response) => response.text()) // Convert response to text
return res.text();
})
.then((data) => { .then((data) => {
this.response = data; this.response = data; // Store the response data
console.log(data); // Log the response for debugging
})
.then(() => {
this.fetchWatchCatSettings();
})
.catch((error) => {
console.error("Error:", error); // Handle any errors
this.response = "An error occurred.";
}); });
}, },
formCompletedChecker() { // Computed property to check if the form is complete
this.formCompleted = get isFormComplete() {
this.watchCatStatus !== "" && return (
this.trackIP !== "" && this.trackIP !== "" &&
this.cooldown !== "" && this.pingTimeout !== "" &&
this.failures !== ""; this.pingFailureCount !== ""
);
}, },
simFormCompletedChecker() { // Fetch the current watchcat settings
if ( fetchWatchCatSettings() {
this.simAutoSwitchStatus !== "" && fetch("/cgi-bin/get_watchcat_status")
this.scheduledSIMHotSwap !== "" && .then((response) => {
this.preferredSim !== "" if (!response.ok) {
) { throw new Error("Network response was not ok");
this.simFormCompleted = true;
} else {
this.simFormCompleted = false;
} }
return response.json(); // Parse response as JSON
})
.then((data) => {
console.log(data); // Log the parsed data for debugging
// Check if the JSON is not empty
if (data) {
this.watchCatStatus = data.enabled === true;
this.trackIP = data.track_ip;
this.pingTimeout = data.ping_timeout;
this.pingFailureCount = data.ping_failure_count;
}
})
.catch((error) => {
console.error("Error:", error); // Handle any errors
this.response = "An error occurred.";
});
}, },
init() { init() {
this.$watch("watchCatStatus", this.formCompletedChecker.bind(this)); this.fetchWatchCatSettings();
this.$watch("trackIP", this.formCompletedChecker.bind(this));
this.$watch("cooldown", this.formCompletedChecker.bind(this));
this.$watch("failures", this.formCompletedChecker.bind(this));
}, },
}; };
} }

View File

@@ -0,0 +1,351 @@
<!DOCTYPE html>
<html lang="en" data-bs-theme="light">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Simple Admin</title>
<!-- <link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH"
crossorigin="anonymous"
/> -->
<!-- Import all the bootstrap css files from css folder -->
<link rel="stylesheet" href="css/styles.css" />
<link rel="stylesheet" href="css/bootstrap.min.css" />
<!-- Logo -->
<link rel="simpleadmin-logo" href="favicon.ico" />
<!-- Import BootStrap Javascript -->
<script src="js/bootstrap.bundle.min.js"></script>
<script src="js/alpinejs.min.js" defer></script>
<style>
.form-switch .form-check-input {
width: 2.4em;
height: 1.2em;
}
</style>
</head>
<body>
<main>
<div class="container my-4" x-data="simpleWatchCat()">
<nav class="navbar navbar-expand-lg mt-2">
<div class="container-fluid">
<a class="navbar-brand" href="/"
><span class="mb-0 h4">Simple Admin</span></a
>
<button
class="navbar-toggler"
type="button"
data-bs-toggle="collapse"
data-bs-target="#navbarText"
aria-controls="navbarText"
aria-expanded="false"
aria-label="Toggle navigation"
>
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarText">
<ul class="navbar-nav me-auto mb-2 ml-4 mb-lg-0">
<li class="nav-item">
<a class="nav-link" href="/">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/network.html">Simple Network</a>
</li>
<li class="nav-item">
<a
class="nav-link active"
href="/settings.html"
aria-current="page"
>Simple Settings</a
>
</li>
<li class="nav-item">
<a class="nav-link" href="/sms.html">SMS</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/console">Console</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/deviceinfo.html"
>Device Information</a
>
</li>
</ul>
<span class="navbar-text">
<button class="btn btn-link text-reset" id="darkModeToggle">
Dark Mode
</button>
</span>
</div>
</div>
</nav>
<div class="row mt-3 mb-4">
<div class="col">
<div class="card">
<div class="card-header">Simple Watchcat</div>
<div class="card-body">
<div class="card-text">
<div class="row mt-3 mb-5 align-content-center mx-4">
<div class="col">
<div class="mt-3">
<label> Enable Watchcat </label>
</div>
</div>
<div class="col-5">
<div class="mt-2">
<div class="form-check form-switch form-switch-lg">
<input
class="form-check-input"
type="checkbox"
role="switch"
id="watchCatSwitch"
x-model="watchCatStatus"
:disabled="!isFormComplete"
x:onchange="setWatchCatSettings"
/>
</div>
</div>
</div>
</div>
<div class="row mt-3 mb-3 align-items-center mx-4">
<div class="col">
<div class="mt-3 mb-4">
<label> Track IP </label>
</div>
<div class="mt-3 mb-4">
<label> Ping Request Timeout </label>
</div>
<div class="mt-3 mb-4">
<label> Ping Failure Amount </label>
</div>
</div>
<div class="col-5">
<div class="mt-3 mb-4">
<select
class="form-select"
aria-label="Select Site to Ping"
x-model="trackIP"
>
<option selected>Select IP</option>
<option value="1.1.1.1">1.1.1.1</option>
<option value="8.8.8.8">8.8.8.8</option>
<option value="9.9.9.9">9.9.9.9</option>
</select>
</div>
<div class="mt-3 mb-4">
<input
type="number"
class="form-control"
aria-label="Ping Timeout"
aria-describedby="inputGroup-sizing-default"
placeholder="Enter Ping Timeout in Seconds."
x-model="pingTimeout"
/>
</div>
<div class="mt-3 mb-4">
<input
type="number"
class="form-control"
aria-label="Sizing example input"
aria-describedby="inputGroup-sizing-default"
placeholder="Enter Ping Failure Amount."
x-model="pingFailureCount"
/>
</div>
</div>
</div>
<!-- <div class="row mt-3 mb-5 align-content-center mx-4">
<div class="col">
<div class="mt-3">
<label>Sim Auto Switch</label>
</div>
</div>
<div class="col-5">
<div class="mt-2">
<div class="form-check form-switch form-switch-lg">
<input
class="form-check-input"
type="checkbox"
role="switch"
id="simAutoSwitch"
x-model="simAutoSwitchStatus"
disabled
/>
</div>
</div>
</div>
</div> -->
<!-- <div class="row mt-3 mb-3 align-items-center mx-4">
<div class="col">
<div class="mt-3 mb-4">
<label> Select Preferred SIM </label>
</div>
<div class="mt-3 mb-4">
<label> SIM 1 APN </label>
</div>
<div class="mt-3 mb-4">
<label> SIM 2 APN </label>
</div>
<div class="mt-3 mb-4">
<label> Failover Interval </label>
</div>
<div class="mt-3 mb-4">
<label> Scheduled SIM Hot Swap</label>
</div>
</div>
<div class="col-5">
<div class="mt-3 mb-3">
<select
class="form-select"
aria-label="Select Sim"
x-model="preferredSim"
>
<option selected>Select SIM</option>
<option value="1">SIM 1</option>
<option value="2">SIM 2</option>
</select>
</div>
<div class="mt-3 mb-3">
<input
type="number"
class="form-control"
aria-label="SIM 1 APN"
aria-describedby="inputGroup-sizing-default"
placeholder="Input APN for SIM 1. (Optional)"
x-model="sim1APN"
/>
</div>
<div class="mt-3 mb-3">
<input
type="number"
class="form-control"
aria-label="SIM 2 APN"
aria-describedby="inputGroup-sizing-default"
placeholder="Input APN for SIM 2. (Optional)"
x-model="sim2APN"
/>
</div>
<div class="mt-3 mb-3 d-flex align-items-center">
<select
class="form-select"
aria-label="Failover Interval"
>
<option selected>Failover Interval</option>
<option value="5">5</option>
<option value="10">10</option>
<option value="15">15</option>
<option value="20">20</option>
</select>
<label class="mx-3">Minutes</label>
</div>
<div class="mt-3 mb-3">
<input
type="time"
class="form-control"
aria-label="Scheduled SIM Hot Swap"
aria-describedby="inputGroup-sizing-default"
x-model="scheduledSIMHotSwap"
/>
</div>
</div>
</div> -->
</div>
</div>
<div class="card-footer">
<!-- Setting a low ping timeout and ping failure count may cause
intermittent disconnections due to high sensitivity. <br />
Select appropriate values for both based on your needs.<br /> -->
Still under development. Coming soon...
</div>
</div>
</div>
</div>
<div class="row mt-3 mb-3">
<div class="col">
<div class="card">
<div class="card-header">Simple Watchcat Logs</div>
<div class="card-body">
<div class="card-text">
<div class="form-floating">
<textarea
class="form-control"
placeholder="Leave a comment here"
id="floatingTextarea2"
style="height: 100px"
x-text="response"
readonly
></textarea>
<label for="floatingTextarea2">Logs Here</label>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</main>
<script src="js/dark-mode.js"></script>
<script>
function simpleWatchCat() {
return {
watchCatStatus: false,
trackIP: "",
pingTimeout: "",
pingFailureCount: "",
response: "",
setWatchCatSettings() {
fetch(
"/cgi-bin/watchcat_maker?" +
new URLSearchParams({
WATCHCAT_ENABLED: this.watchCatStatus,
TRACK_IP: this.trackIP,
PING_TIMEOUT: this.pingTimeout,
PING_FAILURE_COUNT: this.pingFailureCount,
})
)
.then((response) => response.text()) // Convert response to text
.then((data) => {
this.response = data; // Store the response data
console.log(data); // Log the response for debugging
})
.catch((error) => {
console.error("Error:", error); // Handle any errors
this.response = "An error occurred.";
});
},
// Computed property to check if the form is complete
get isFormComplete() {
return (
this.trackIP !== "" &&
this.pingTimeout !== "" &&
this.pingFailureCount !== ""
);
},
};
}
</script>
</body>
</html>