Poll-monitor/SSH remote access to WSL (Windows Subsystem for Linux) Windows 2022 server and enable wsl.exe automatically during Windows 2022 server restart/reboot from remote Ubuntu 22.04 LTS
Get link
Facebook
X
Pinterest
Email
Other Apps
Poll-monitor/SSH remote access to WSL (Windows Subsystem for Linux) Windows 2022 server and enable wsl.exe automatically during Windows 2022 server restart/reboot from remote Ubuntu 22.04 LTS
Shell Script
#!/bin/bash
# Log file location
LOG_FILE="/var/log/ping_monitor.log"
SERVICE_NAME="ping_monitor.service"
# Function to log messages with timestamps
log_message() {
echo "$(date +"%Y-%m-%d %H:%M:%S") - $1" >> $LOG_FILE
}
# IP address to ping
IP_ADDRESS="A.B.C.D"
# Number of timeouts and replies to check
TIMEOUT_COUNT=2 # Adjust this as needed
REPLY_COUNT=4
# Initialize counters
timeout_counter=0
reply_counter=0
# Infinite loop to monitor the ping status
while true; do
# Ping the IP address once
ping -c 1 $IP_ADDRESS > /dev/null 2>&1
# Check the exit status of the ping command
if [ $? -ne 0 ]; then
# Increment the timeout counter if the ping fails
((timeout_counter++))
log_message "Ping to $IP_ADDRESS timed out. Count: $timeout_counter"
else
# Increment the reply counter if the ping succeeds
((reply_counter++))
log_message "Received reply from $IP_ADDRESS. Count: $reply_counter"
fi
# Check if the timeout condition is met
if [ $timeout_counter -ge $TIMEOUT_COUNT ]; then
log_message "Timeout condition met. Waiting for replies..."
# Reset the timeout counter and wait for replies
timeout_counter=0
# Wait for the replies condition
while [ $reply_counter -lt $REPLY_COUNT ]; do
ping -c 1 $IP_ADDRESS > /dev/null 2>&1
if [ $? -eq 0 ]; then
((reply_counter++))
log_message "Received reply from $IP_ADDRESS. Count: $reply_counter"
else
log_message "Ping to $IP_ADDRESS timed out."
fi
sleep 1 # Wait a second before the next ping
done
# Both conditions met; execute the command directly
log_message "Executing command on remote machine."
sshpass -p 'Administrator_Password' ssh -tt Administrator@$IP_ADDRESS "\"C:\\Program Files\\WSL\\wsl.exe\""
log_message "Command executed. Clearing log file."
# Clear the log file to save space
> $LOG_FILE # This will truncate the log file
log_message "Log file cleared. Restarting the service."
# Restart the systemd service
systemctl restart $SERVICE_NAME
log_message "Service $SERVICE_NAME restarted. Continuing to monitor..."
# Continue the monitoring loop
timeout_counter=0 # Reset timeout counter to continue monitoring
reply_counter=0 # Reset reply counter for the next cycle
fi
sleep 1 # Wait a second before the next ping
done
Comments
Post a Comment