Shell Scripting
Scripting Fundamentals
What Is a Script
Tips
For more information on writing shell scripts on Linux systems, see the Advanced Bash-Scripting Guide or the GNU Bash Reference Manual.
Advantech routers support scripting in a manner similar to general-purpose Linux operating systems. A script is essentially a text file containing a sequence of commands that the router's command-line interpreter (shell) can execute. Scripts allow you to automate tasks, manage router operations, and extend functionality without modifying the router's core firmware. They represent the simplest method for adding custom functions.
Supported Environments
Scripts on Advantech routers are written using a POSIX-compatible shell scripting language. The default shell invoked by /bin/sh is typically a version of ash (from BusyBox), but bash might also be available depending on the router model and firmware version. For most common scripting tasks, the differences between these shells are minimal when adhering to POSIX standards.
When writing scripts, you can use the standard set of Linux/Unix utilities provided by the BusyBox environment. To list available built-in commands, you can run busybox --list or press the Tab key twice in the shell. Additionally, Advantech provides several proprietary utilities specific to the router's hardware and functions (e.g., gsmsms, io, led, gsmat, status). Both the standard BusyBox commands and Advantech-specific utilities are documented in the Command Line Interface application note.
Writing and Executing a Script
File Format
Scripts should be saved as plain text files, typically with a .sh extension. It is crucial to use Unix-style line endings (LF only) rather than Windows-style line endings (CRLF), as the latter can cause execution errors on Linux. You can create scripts using a text editor on your PC and then transfer them to the router (e.g., via SCP or SFTP to directories like /root or /var/data), or create them directly on the router using built-in editors like vi, refer to Busybox vi tutorial, or the Here-Document method described below.
Shebang Line
Every script should begin with a shebang line, which specifies the interpreter that should execute the script. The standard shebang for POSIX-compatible scripts is #!/bin/sh.
Here-Document Method
The here-document syntax provides a convenient way to embed multi-line text (like a script's content) directly within another script or command. This is particularly useful when defining scripts within the router's GUI (see the Scripts in Router GUI section) or when creating script files dynamically from the console.
A here-document redirects lines following a command until a specific delimiter is encountered. The syntax is command << DELIMITER, followed by the input lines, and ending with DELIMITER on a line by itself.
Making the Script Executable
Before a script file can be run directly, it needs execute permissions. Use the chmod command to set these permissions. For example, to give the owner read, write, and execute permissions, and others read and execute permissions:chmod 755 your_script.sh
Alternatively, more restrictive permissions like chmod 700 your_script.sh (owner only) might be appropriate.
Running the Script
To execute a script located in the current directory, use its relative path:./your_script.sh
If the script is located elsewhere, provide the full path:/path/to/your_script.sh
Alternatively, you can explicitly invoke the shell to run the script, which doesn't require execute permissions:sh /path/to/your_script.sh
Redirecting Output and Error Streams
Shell scripts produce output on two main streams:
- Standard Output (stdout, file descriptor 1): Used for normal program output.
- Standard Error (stderr, file descriptor 2): Used for error messages and diagnostics.
By default, both streams are displayed on the console. When running scripts non-interactively or logging their activity, it is often desirable to capture this output into files.
Redirecting stdout
Use the > operator to redirect stdout to a file, overwriting the file if it exists:./your_script.sh > /path/to/logfile.log
Use >> to append stdout to the file:./your_script.sh >> /path/to/logfile.log
Redirecting stderr
Use 2> to redirect stderr to a file:./your_script.sh 2> /path/to/errorfile.log
Use 2>> to append stderr.
Redirecting Both stdout and stderr to the Same File
To capture all output (both normal messages and errors) in a single file, redirect stderr to the same location as stdout using the notation 2>&1. This must appear after the stdout redirection.
Syntax./your_script.sh > /path/to/logfile.log 2>&1 (Overwrite log file)./your_script.sh >> /path/to/logfile.log 2>&1 (Append to log file)
Order Matters
The order of redirections is critical. 2>&1 redirects stderr to wherever stdout is currently pointing.
- Correct (stdout and stderr go to file):
command > file.log 2>&1 - Incorrect (stderr still goes to console):
command 2>&1 > file.log(stderr is redirected to the original stdout (console) before stdout is redirected to the file).
Discarding Output
To discard output, redirect it to the special null device /dev/null.
- Discard stdout:
command > /dev/null - Discard stderr:
command 2> /dev/null - Discard both:
command > /dev/null 2>&1
Basic Script Example
Below is an example script, intended to be saved in a file named test.sh , that checks network connectivity to a target host and appends a timestamped result to a log file.
#!/bin/sh
# test.sh -- Check network connectivity and log status
# --- Configuration ---
TARGET="8.8.8.8" # IP address or hostname to ping
LOGFILE="/var/log/network_status.log" # Path to the log file
# --- End Configuration ---
# Get current timestamp
TIMESTAMP=$(date +"%Y-%m-%d %H:%M:%S")
# Optional: Exit immediately if any command fails
# set -e
# Ping the target host once (-c 1) with a timeout (e.g., -W 2 for 2 seconds)
# Redirect ping's stdout and stderr to /dev/null as we only care about exit status
if ping -c 1 -W 2 "$TARGET" > /dev/null 2>&1; then
# If ping succeeds (exit code 0), log UP status
echo "$TIMESTAMP: Network is UP (reachable $TARGET)" >> "$LOGFILE"
else
# If ping fails (non-zero exit code), log DOWN status
echo "$TIMESTAMP: Network is DOWN (cannot reach $TARGET)" >> "$LOGFILE"
fi
# Explicitly exit with success status
exit 0To run this script, first ensure it has execute permissions, then execute it using its path:
chmod +x test.sh # Or chmod 755 test.sh
./test.shThis executes the script once, performing a single connectivity check and appending the result to "$LOGFILE". Another common approach involves running the script's core logic within an infinite while true loop, typically used for continuous monitoring tasks. If the script needs to run periodically at specific intervals or at a precise time, the cron scheduling utility can be used (see Section Scheduling Scripts with cron).
Scripts in Router GUI
The router's web interface provides dedicated sections for defining custom scripts that run automatically in response to specific system events. Navigate to Configuration → Scripts, where you will find the following subpages:
- Startup Script: Executed once every time the router powers on or after a factory reset. Ideal for initial setup, configuration checks, or launching background monitoring processes.
- Up/Down IPv4 Scripts: Contains fields for an "Up" script (executed when the primary WAN IPv4 connection is established) and a "Down" script (executed when the primary WAN IPv4 connection is lost). These scripts receive connection-specific parameters (like interface name, IP address).
- Up/Down IPv6 Scripts: Similar to IPv4 scripts, but triggered by the establishment ("Up") or loss ("Down") of the primary WAN IPv6 connection, receiving relevant IPv6 parameters.
For detailed instructions on parameters passed to Up/Down scripts and specific use cases, refer to the manual for your router model.
Simple GUI Script Example
#!/bin/sh
# Define variables
PhoneNumber="+420123456789"
Message="Router event triggered SMS."
# Use the variables
sms "$PhoneNumber" "$Message"
exit 0Creating and Running a Script File via GUI Script (Here-Document)
If you need a script defined in the GUI (like the Startup Script) to create a separate, potentially more complex script file and then execute it (possibly in the background), the Here-Document method (see the Here-Document Method section) is recommended, as shown below:
#!/bin/sh
# This script (run from GUI, e.g., Startup) creates and executes /tmp/script.sh
# Define path for the script to be created (use RAM disk like /tmp or /var/run)
SCRIPT_PATH="/tmp/script.sh"
# Use cat with a here-document (EOF) to write the script content
# Note: Using 'EOF' (quoted) prevents variable expansion by *this* script.
# Variables like $Num inside the heredoc will be treated literally when written.
cat > "$SCRIPT_PATH" << 'EOF'
#!/bin/sh
# This is the content of the created script (/tmp/script.sh)
# Define variables *within this script*
Num="+420123456789"
MessageBody="Sending SMS from background script..."
# Example action: Send SMS
sms "$Num" "$MessageBody"
# Add more complex logic here...
exit 0
EOF
# End of here-document
# Make the created script executable
chmod +x "$SCRIPT_PATH"
# Execute the created script in the background
"$SCRIPT_PATH" &
exit 0 # Indicate successful completion of the startup taskVariable Expansion in Here-Documents
Note the handling of variables (like $Num) when using the here-document method:
<< EOF(Delimiter unquoted): Variables inside the here-document (e.g.,$VAR) are expanded by the outer script (the one containing thecatcommand) before the content is written to the file. The value of the variable from the outer script's context is embedded.<< 'EOF'(Delimiter quoted): The content between'EOF'delimiters is treated literally. Variables (e.g.,$VAR) are written as the literal string\$VARinto the created file. This is generally the desired behavior if the variable is intended to be defined or used within the created script itself, as demonstrated in the example above.- Escaping the dollar sign (
\\$VAR) when using the unquoted form (<< EOF) also prevents expansion by the outer script and achieves the same literal effect as quoting the delimiter, but using<< 'EOF'is often considered clearer.
Scheduling Scripts with cron
Tips
For further cron scheduling examples and advanced syntax, see crontab.guru.
The cron daemon on ICR-OS allows you to run scripts at specified times or intervals. Jobs are defined in the system crontab file /etc/crontab. In this file, each line defines a job and follows the syntax below, where the first five fields specify the schedule:
<minute> <hour> <day-of-month> <month> <day-of-week> <user> <command>
Schedule Field Definitions
*(asterisk) — matches all valid values (e.g., every minute, every hour).m-n(range) — matches any value betweenmandn(inclusive).*/s(step) — matches everysth value (e.g.,*/5in the minute field means —every 5 minutes—).v1,v2,...(list) — matches any of the comma-separated values.
Valid value ranges
- Minute:
0–59 - Hour:
0–23 - Day of month:
1–31 - Month:
1–12 - Day of week:
0–7(both0and7= Sunday)
Example Entries
- Every minute:
* * * * * root /path/to/script.sh - Every 5 minutes:
*/5 * * * * root /path/to/script.sh - Hourly at minute 0:
0 * * * * root /path/to/script.sh - Daily at 02:30 AM:
30 2 * * * root /path/to/script.sh - Monthly on the 1st at midnight:
0 0 1 * * root /path/to/script.sh - Weekly on Mondays at 03:00 AM:
0 3 * * 1 root /path/to/script.sh
Starting cron
After creating or updating /etc/crontab, start the daemon by service cron start or by crond &. To verify it's running you can use ps | grep cron.
Persistence Across Reboots
If /etc/crontab is reset on router reboot, ensure it is recreated in your Startup Script (Section Scripts in Router GUI). For example, the startup script may look like this:
#!/bin/sh
# WARNING: This overwrites the entire crontab. See AttentionBox in Sec 2.7.1.
cat << 'EOF' > /etc/crontab
*/15 * * * * root /path/to/script.sh
# Add other required system or application cron jobs here
EOF
crond &Specific Implementation Notes and Examples
Handling Incoming SMS with a Custom Script
This section describes an option for handling incoming SMS messages received by the router using a custom script. This is achieved using a script located at /var/scripts/sms.
Warning
This file path (/var/scripts/sms) resides within the router's volatile RAM filesystem. This means the script file and its contents will be lost upon router reboot or power loss.
To ensure the custom SMS handling logic persists across reboots, the /var/scripts/sms script must be recreated each time the router starts. A common method is to use the router's Startup Script functionality. Add a code block similar to the following to the Startup Script configuration page (Configuration → Scripts → Startup Script) to automatically create the /var/scripts/sms file at boot:
#!/bin/sh
# Create /var/scripts/sms using a here-document in the Startup Script
cat << 'EOF' > /var/scripts/sms
#!/bin/sh
# This is the custom SMS handler script /var/scripts/sms
# Insert your SMS-handling logic below
# Example: Log received SMS details
logger -t sms_handler "SMS received. Authorized: $1, Sender: $2, Text: $3 $4 $5 $6 $7 $8 $9"
# Add custom actions based on sender ($2) and message content ($3-$9) here...
exit 0
EOFWhen an SMS message is received and this feature is enabled (see info below), the system executes the /var/scripts/sms script, passing the following parameters:
$0— The name of the script being executed (alwayssms), set automatically by the shell.$1— A flag indicating if the sender's phone number matches one of the numbers configured in the Phone Number x fields within the router's SMS settings GUI (1for a match,0otherwise).$2— The sender's mobile phone number (MSISDN).$3...$9— The first seven words (space-separated tokens) extracted from the body of the received SMS message.
Within your /var/scripts/sms script, you can use these positional parameters ($1 through $9) to implement custom actions based on the sender and content of the SMS. This allows for creating custom SMS commands, for example, to query router status, toggle interfaces, or trigger specific application logic.
Tips
To enable the execution of the
/var/scripts/smsscript:- Cellular connection must be properly configured and enabled under Configuration → Mobile WAN.
- The Enable remote control via SMS option must be checked under Configuration → Services → SMS.
- Configuring specific Phone Number x entries on Services → SMS page is optional for enabling the script itself but affects the value of the
$1parameter.
Precedence Rule: If a Phone Number x is configured and matches the sender's number, and the received SMS message matches the format of one of the router's built-in SMS control commands (e.g.,
get ip,reboot), the built-in command will be executed instead of the custom/var/scripts/smsscript. The custom script is bypassed in this scenario.The
/var/scripts/smsfile generally does not require execute permissions.If you need to determine the phone number (MSISDN) of the SIM card currently installed in the router, you can find it by sending an SMS message from the router using the Administration → Send SMS page to another phone.
Email Configuration Notes
To send emails from your router, you need to configure an SMTP server at Configuration → Services → SMTP. Ensure the email service is accessible and functional; you may need to properly configure the firewall and NAT settings to allow outgoing SMTP traffic.
You can send a test email from the console by issuing this command:
email -t address@domain.ext -s "Test from router" -m "Just testing email functionality."Forward Incoming SMS to Email
Tips
This script relies on the custom SMS handling mechanism (Chapter Handling Incoming SMS with a Custom Script) and requires a correctly configured SMTP server (Configuration → Services → SMTP).
This example script uses the custom SMS handler (/var/scripts/sms) to automatically forward details of every incoming SMS message to a specified email address.
Startup Script
This script creates the /var/scripts/sms handler script in RAM at boot time.
#!/bin/sh
# Create the SMS handler script in RAM
cat > /var/scripts/sms << 'EOF'
#!/bin/sh
# Specify email address
EMAIL="john.doe@email.com"
# Forward incoming SMS via email
email -t "$EMAIL" \
-s "Received SMS from $2" \
-m "Authorized: $1, Text: $3 $4 $5 $6 $7 $8 $9"
EOFHow It Works
- The Startup Script uses
cat > ... << EOFto create the handler script/var/scripts/sms. - Inside the handler script:
EMAIL="john.doe@email.com": Defines the recipient email address.- The
emailutility is called to send the message. -t "$EMAIL": Sets the recipient address.-s "Received SMS from $2": Sets the subject line, including the sender's phone number ($2).-m "Authorized: $1, Text: $3 $4 $5 $6 $7 $8 $9": Sets the message body, including:- The authorization flag (
$1): 1 if the sender is in the router’s authorized list, 0 otherwise. - The sender’s phone number (
$2) is included in the subject. - The first seven words of the SMS text (
$3through$9).
- The authorization flag (
- This script forwards details of every incoming SMS, regardless of sender or content, to the specified email address.
Warning
The standard SMS handler mechanism might only provide the first 7 words of the SMS text ( $3 through $9 ). Longer messages may be truncated in the forwarded email.
Send Email on PPP Connection Established
Tips
Make sure you have correctly configured the SMTP server in Configuration → Services → SMTP. Refer to Section Email Configuration Notes.
This script sends an informational email when a PPP (Point-to-Point Protocol) connection for the WAN interface is established. It can be related to IPv4 or IPv6 addressing, depending on where the script is placed in the router's GUI: either in the Up script IPv4 field or the Up script IPv6 field under Configuration → Scripts.
IPv4 Up Script
This script should be placed in the Up script IPv4 field.
#!/bin/sh
# Specify email address
EMAIL=john.doe@email.com
# Send email using parameters passed by the system
# $1 = interface name (e.g., ppp0)
# $4 = assigned IPv4 address
email -t $EMAIL \
-s "Router has established IPv4 PPP connection." \
-m "Interface: $1; IP address: $4"How It Works
- The script defines the destination email address in the
`EMAIL`variable. - When the PPP interface establishes an IPv4 connection, the router executes this script, passing several parameters. This script uses:
`$1`— the name of the network interface (e.g.,`ppp0`).`$4`— the IP address assigned to the interface.
- The
`email`utility (typically located at`/usr/bin/email`) is called to send the notification:`-t $EMAIL`— specifies the recipient's email address.`-s "...\"`— sets the subject line of the email, including the interface name.`-m "...\"`— sets the message body, including the interface name and assigned IP address passed as parameters.
An example of a received email based on the script above:
Subject: `Router has established IPv4 PPP connection on ppp0`
Content: `Interface: ppp0; IP address: 192.0.2.100`
Configure Mobile WAN via SMS
Tips
This script relies on the custom SMS handling mechanism described in Section “Handling Incoming SMS with a Custom Script.” Ensure that mechanism is active and properly configured.
This example demonstrates the implementation of a new SMS command, which can set the Network type and the Default SIM card for the mobile WAN configuration. The command which should be sent by SMS to the router has the following syntax:
PPP <NetworkType> <DefaultSIM>
Where:
<NetworkType>specifies the desired network technology. Valid options (depending on router model support) are:AUTO: Switches Network Type of both SIM cards to automatic selection.GPRS: Switches Network Type of both SIM cards to GPRS/EDGE.UMTS: Switches Network Type of both SIM cards to UMTS/HSPA.LTE: Switches Network Type of both SIM cards to LTE.NR5G: Switches Network Type of both SIM cards to NR5G.
<DefaultSIM>specifies the default SIM card:1: sets SIM 1 as default.2: sets SIM 2 as default.
Example SMS: PPP LTE 1 (Sets network type to LTE for both SIMs and makes SIM 1 the default).
How It Works
- The startup script (shown below) creates the
/var/scripts/smshandler script in the router’s RAM filesystem using a here-document (cat > ... << EOF). This ensures the handler exists after a reboot. - The handler script (
/var/scripts/sms) is executed by the system when an SMS is received. - It first checks if the sender is authorized by verifying if the first parameter
$1is equal to1. - If authorized, it checks if the third word of the SMS (
$3) is “PPP” (case-sensitive). - If the command word matches, the script processes the fourth word (
$4, network type) and fifth word ($5, default SIM). - NetworkType: Based on the value of
$4, a series ofif/elifstatements selects the appropriatesedcommand. This command modifies/etc/settings.pppin place (-i), updating thePPP_NETTYPE=andPPP_NETTYPE2=lines with the corresponding numeric code (0 for AUTO, 1 for GPRS, 2 for UMTS, 3 for LTE, 8 for NR5G). - DefaultSIM: If
$5is “1” or “2”, anothersedcommand updates thePPP_DEFAULT_SIM=andPPP_BACKUP_SIM=lines. - Reboot: After modifying the settings file, the script immediately executes
rebootto apply the changes.
#!/bin/sh
# Create the SMS handler script in RAM
cat > /var/scripts/sms << EOF
#!/bin/sh
if [ "\$1" = "1" ]; then
if [ "\$3" = "PPP" ]; then
if [ "\$4" = "AUTO" ]; then
sed -e "s/\(PPP_NETTYPE=\).*/\10/" \
-e "s/\(PPP_NETTYPE2=\).*/\10/" \
-i /etc/settings.ppp
elif [ "\$4" = "GPRS" ]; then
sed -e "s/\(PPP_NETTYPE=\).*/\11/" \
-e "s/\(PPP_NETTYPE2=\).*/\11/" \
-i /etc/settings.ppp
elif [ "\$4" = "UMTS" ]; then
sed -e "s/\(PPP_NETTYPE=\).*/\12/" \
-e "s/\(PPP_NETTYPE2=\).*/\12/" \
-i /etc/settings.ppp
elif [ "\$4" = "LTE" ]; then
sed -e "s/\(PPP_NETTYPE=\).*/\13/" \
-e "s/\(PPP_NETTYPE2=\).*/\13/" \
-i /etc/settings.ppp
elif [ "\$4" = "NR5G" ]; then
sed -e "s/\(PPP_NETTYPE=\).*/\18/" \
-e "s/\(PPP_NETTYPE2=\).*/\18/" \
-i /etc/settings.ppp
fi
if [ "\$5" = "1" ]; then
sed -e "s/\(PPP_DEFAULT_SIM=\).*/\11/" \
-e "s/\(PPP_BACKUP_SIM=\).*/\12/" \
-i /etc/settings.ppp
elif [ "\$5" = "2" ]; then
sed -e "s/\(PPP_DEFAULT_SIM=\).*/\12/" \
-e "s/\(PPP_BACKUP_SIM=\).*/\11/" \
-i /etc/settings.ppp
fi
reboot
fi
fi
EOFSend SNMP Trap on PPP Connection Established
Tips
Make sure you have correctly configured the SNMP manager in Configuration → Services → SNMP.
This script sends an SNMP trap to the configured SNMP manager when the PPP (Point-to-Point Protocol) connection for the WAN interface is established. It can be related to IPv4 or IPv6 addressing, depending on where the script is placed in the router's GUI: either in the Up script IPv4 field or the Up script IPv6 field under Configuration → Scripts.
IPv4 Up Script
This script should be placed in the Up script IPv4 field.
#!/bin/sh
# Specify SNMP manager address
SNMP_MANAGER=192.168.1.2
snmptrap -g 3 $SNMP_MANAGERHow It Works
- The script defines the destination IP address of the SNMP manager in the
SNMP_MANAGERvariable. - When the PPP interface establishes an IPv4 connection, the router executes this script.
- The
snmptraputility sends a generic SNMP trap message:-g 3specifies sending a standard generic trap of typelinkUp(numeric value 3). This indicates that a network interface has come up.$SNMP_MANAGERprovides the IP address where the trap should be sent.
- The configured SNMP manager receives this generic
linkUptrap and can process it based on its rules. The trap itself, using only-g 3, does not contain specific information about which interface came up or its IP address. More complexsnmptrapcommands would be needed to include such details as variable bindings.
Switch Between Ethernet WAN and Mobile WAN
This script enables automatic switching between a primary Ethernet WAN connection (assumed to be eth1) and a backup Mobile WAN (PPP) connection. The PPP connection becomes active when ping tests to a defined IP address fail, indicating that the primary WAN connection is unavailable. When the primary WAN recovers, it switches back.
Caution
This script makes assumptions about network interfaces, configuration files (/etc/settings.eth), and requires careful adaptation to your specific network setup and router model. Directly manipulating routes and firewall rules requires caution.
Startup Script
#!/bin/sh
# Specify IP addresses
WAN_PING=192.168.2.1
WAN_GATEWAY=192.168.2.1
WAN_DNS=192.168.2.1
. /etc/settings.eth
/sbin/route add $WAN_PING gw $WAN_GATEWAY
/sbin/iptables -t nat -A PREROUTING -i eth1 -j napt
/sbin/iptables -t nat -A POSTROUTING -o eth1 -p ! esp -j MASQUERADE
LAST=1
while true
do
ping -c 1 $WAN_PING
PING=$?
if [ $PING != $LAST ]; then
LAST=$PING
if [ $PING = 0 ]; then
/etc/init.d/ppp stop
sleep 3
/sbin/route add default gw $WAN_GATEWAY
echo "nameserver $WAN_DNS" > /etc/resolv.conf
/usr/sbin/conntrack -F
/etc/scripts/ip-up - - - $ETH2_IPADDR
else
/etc/scripts/ip-down - - - $ETH2_IPADDR
/usr/sbin/conntrack -F
/sbin/route del default gw $WAN_GATEWAY
/etc/init.d/ppp start
fi
fi
sleep 1
doneHow It Works
- The script defines IP addresses for ping testing (
WAN_PING), the primary WAN gateway (WAN_GATEWAY), and DNS (WAN_DNS). These likely need customization. . /etc/settings.eth: Sources variables from the Ethernet settings file (e.g.,$ETH2_IPADDRused later, assuming this relates to the primary WAN interfaceeth1). The exact contents and relevance of this file depend on the router configuration.- Initial Network Setup
- Adds a static route for the
WAN_PINGtarget via theWAN_GATEWAY. This ensures ping tests go through the correct interface when the primary WAN is assumed to be up initially. - Adds
iptablesNAT rules for theeth1interface. ThePREROUTINGrule uses-j napt, which is non-standard (standard Linux typically uses-j DNATtargets here if needed). ThePOSTROUTINGrule enables standard MASQUERADE (Source NAT) for outgoing traffic oneth1, excluding ESP protocol packets (common for VPN passthrough). The effectiveness of-j naptdepends on its implementation in the router's firmware.
- Adds a static route for the
- Monitoring Loop:
LAST=1: Initializes the state variable assuming the connection is initially down (non-zero ping status), ensuring the script potentially triggers a switch on the first successful ping if the WAN is already up at boot.while true: Enters an infinite loop for continuous monitoring.ping -c 1 $WAN_PING: Sends one ping packet to the target address.PING=$?: Captures the exit status of thepingcommand (0 for success, non-zero for failure).if [ $PING != $LAST ]: Checks if the connectivity status has changed since the last check. This edge-triggered approach prevents actions from repeating every second if the state remains stable.LAST=$PING: Updates the stored status for the next comparison.- If WAN came UP (
PING = 0): Executes commands to switch back to the primary Ethernet WAN./etc/init.d/ppp stop: Stops the Mobile WAN (PPP) connection.sleep 3: Pauses briefly to allow the PPP connection to terminate cleanly./sbin/route add default gw $WAN_GATEWAY: Adds the default route via the primary WAN gateway.echo "nameserver $WAN_DNS" > /etc/resolv.conf: Sets the DNS server configuration to use the primary WAN's DNS./usr/sbin/conntrack -F: Flushes the connection tracking table to remove potentially stale entries related to the PPP connection./etc/scripts/ip-up - - - $ETH2_IPADDR: Executes the standard system IP-up script, potentially for the Ethernet interface (eth1). The parameters passed (eth1,$ETH2_IPADDR, etc.) are examples and depend on what the actualip-upscript expects.
- If WAN went DOWN (
PING != 0): Executes commands to switch to the backup Mobile WAN (PPP) connection./etc/scripts/ip-down - - - $ETH2_IPADDR: Executes the standard system IP-down script for the Ethernet interface./usr/sbin/conntrack -F: Flushes connection tracking./sbin/route del default gw $WAN_GATEWAY: Removes the default route via the primary WAN gateway./etc/init.d/ppp start: Starts the Mobile WAN (PPP) connection. The PPP daemon is typically configured to establish its own default route and DNS settings when it connects successfully.
sleep 1: Pauses for 1 second before the next ping check. Adjust this value to balance responsiveness and system load.
Executing AT Commands on Cellular Module
Tips
Advantech routers utilize a cellular (GSM/LTE/5G) module for mobile network connectivity, which is a primary function. While the router's firmware handles most module settings for reliable operation, direct interaction via AT commands is possible using specific methods for monitoring or advanced configuration.
This section describes methods for sending AT commands directly to the router's cellular module.
AT-SMS Protocol
The AT-SMS protocol refers to a private set of AT commands supported by the routers, allowing direct access to the cellular module via SMS. This can be used for tasks like sending SMS messages or querying module status and settings remotely. Configuration related to SMS handling via AT commands can be found in the GUI under Configuration → Services → SMS. You can also refer to the AT Commands (AT-SMS) Application Note for details on the specific command syntax.
The gsmat Command (Non-exclusive Access)
For monitoring the cellular module or executing basic AT commands without disrupting the router's primary mobile connection, the gsmat command is provided.
Usage
Connect to the router via SSH or Telnet and execute gsmat followed by the desired AT command string.
# Get module information
gsmat ATI
# List all SMS messages (double quotes escaped)
gsmat AT+CMGL=\\\"ALL\\\"
# List all SMS messages (alternative: single quotes)
gsmat 'AT+CMGL="ALL"'Notes on gsmat
- This provides "Non-exclusive access", meaning the router's firmware continues managing the mobile connection simultaneously.
- It is primarily intended for monitoring. Modifying critical module settings via
gsmatis generally not recommended as it might conflict with the firmware's management. - Special characters within the AT command string, such as double quotes (
"), dollar signs ($), and semicolons (;), must be properly escaped with backslashes (\) or the entire AT command string should be enclosed in single quotes (') to prevent interpretation by the shell.
Exclusive Access
For advanced diagnostics or configuration requiring full control over the module, "Exclusive access" can be used. This method temporarily stops the router's mobile network management, allowing direct, unimpeded communication with the module.
Caution
Exclusive access stops the router's primary mobile connectivity and is intended for expert users familiar with AT commands and potential consequences. Improper use can disrupt network service or require a router reboot. Advantech may not provide support for issues arising from the use of exclusive access.
Steps for Exclusive Access
- Connect to the router via SSH or Telnet.
- Stop the Mobile WAN service (PPP daemon):
service ppp stop- Start the TCP/USB proxy (
portd) to forward a TCP port to the module's serial device. The specific TTY device (/dev/ttyUSB8,/dev/ttyS2,/dev/ttyACM8, etc.) varies depending on the router model and cellular module. You can usedmesgto identify the correct port. Port 8000 is used in this example.
# Example using common port /dev/ttyUSB8 and TCP port 8000
portd -c /dev/ttyUSB8 -t 8000 &- Connect to the specified TCP port (e.g., 8000) using a Telnet client or similar tool from your computer or another process on the router.
# Example connecting from the router itself
telnet localhost 8000- Once connected via TCP, you can send AT commands directly to the module and view the responses.
- Exclusive Access (
portd): When finished, stop theportdprocess (e.g., usingkillall portd) and restart the Mobile WAN service (service ppp start) to restore normal router operation.
How It Works Summary
- Non-exclusive Access (
gsmat): Sends a single AT command to the module via a firmware intermediary, allowing basic queries without disrupting the main connection. Requires careful shell escaping. - Exclusive Access (
portd): Stops the router's mobile connection management, runs a proxy daemon (portd) to link the module's serial port directly to a TCP port, allowing raw, interactive AT command communication via a TCP client. Requires manual steps to stop/start services and identify the correct serial port.
Schedule an Automatic Daily Reboot
Tips
This script uses the cron scheduling daemon to schedule an automatic router reboot at a specific time each day. See Section on cron scheduling for more details on cron.
This example configures the router to automatically reboot daily at 23:55 (11:55 PM).
Startup Script
Place this script in the Startup Script section of the GUI. It adds the reboot job to the system's crontab when the router boots.
#!/bin/sh
echo "55 23 * * * root /sbin/reboot" > /etc/crontab
service cron startHow It Works
echo "55 23 * * * root /sbin/reboot" > /etc/crontab: This command overwrites the main system crontab file (/etc/crontab).55 23 * * *: Defines the schedule: 55th minute, 23rd hour (11:55 PM), every day, month, and day of the week.root: Specifies the user account under which the command should run./sbin/reboot: The command to execute.
Caution
Overwriting /etc/crontab directly is generally discouraged as it removes any other system jobs. A safer approach is to add jobs to user-specific crontabs (e.g., in /etc/crontabs/root) or use a drop-in directory like /etc/cron.d/ if supported by the router's cron implementation.
service cron start: Attempts to start or restart thecrondaemon using theserviceutility. This is necessary forcronto recognize the new schedule in the crontab file. The exact command to manage thecronservice might vary (crond,busybox crond, etc.).- Once active, the
crondaemon will execute/sbin/rebootdaily at 23:55.
Voltage Drop SMS Alert
Tips
- This script monitors the router's supply voltage and sends an SMS alert if the voltage drops below a specified threshold.
- This functionality is only supported by router models capable of measuring supply voltage (Check GUI: Status → System Information → Supply Voltage).
- It uses the router's proprietary utilities (
status,led,gsmsms) and should be placed in the Startup Script to run automatically after boot. - Adjust the voltage threshold (
Umin) and recipient phone number (Num) variables as needed.
This example demonstrates how to receive an SMS notification when the supply voltage falls below a specific level.
Startup Script
Place this script in the Startup Script section of the GUI.
#!/bin/sh
mkdir -p /var/voltaged
cat > /var/voltaged/voltaged << EOF
#!/bin/sh
# Specify these power supply threshold
Umin=16.3
# Specify phone number
Num=+420123456789
old=0
while true
do
Uget=\$( status sys | awk '/^Supply Voltage/ { print \$4 }' )
if [ "\$(echo "\$Uget \$Umin" | awk '{print (\$1 < \$2)}')" -eq 1 ]; then
if [ \$old -eq 0 ]; then
led on
sms \$Num "Low voltage! Voltage is only \$Uget V!"
old=1
fi
else
led off
old=0
fi
sleep 5
done
EOF
chmod +x /var/voltaged/voltaged
sleep 60 # Let establish MWAN connection
/var/voltaged/voltaged &How It Works
- The Startup Script first creates a directory (
/var/voltaged) to hold the monitoring daemon script. - It defines the minimum voltage threshold (
Umin) and the recipient phone number (Num). - A here-document is used to write the actual monitoring logic into the
/var/voltaged/voltagedfile. - Inside the monitoring script (
voltaged):- An infinite loop (
while true) runs continuously. status sys | awk '/^Supply Voltage/ { print $4 }': Retrieves the system status and usesawkto extract the voltage value (the 4th field on the relevant line).- A basic check ensures a voltage value was actually retrieved.
echo "\$current_voltage \$UMIN_DAEMON" | awk '\{print ($1 < $2)\}': Performs a floating-point comparison usingawkto check if the current voltage is less than the threshold.awkprints1if true,0if false.- If Voltage is Low (
is_lowis 1):- It checks if an alert has already been sent (
alert_sentis 0). - If no alert was sent, it logs the low voltage event, turns the USR LED on (
led on), sends an SMS using thesmscommand, and setsalert_sentto 1 to prevent repeated SMS for the same low-voltage event.
- It checks if an alert has already been sent (
- If Voltage is OK (
is_lowis 0):- It checks if an alert was previously sent (
alert_sentis 1). - If so, it logs the recovery, turns the USR LED off (
led off), and resetsalert_sentto 0, allowing a new alert if the voltage drops again later.
- It checks if an alert was previously sent (
sleep 5: The script pauses for 5 seconds before the next voltage check.
- An infinite loop (
- The Startup Script makes the daemon script executable (
chmod +x). - It includes a
sleep 60to wait for the system (especially the Mobile WAN connection needed for SMS) to potentially initialize before starting the monitoring. - Finally, it launches the
voltagedscript in the background (&).