Lua Script Function

Summary

You can execute Lua script (reference: lua.org website) on the Yamaha router. By embedding an API specialized for Yamaha routers with Lua script, you can program router settings changes and actions, depending on the status of the router. For example, you can create the following scripts:

  • Configuration program settings
  • Send an email to the administrator when a specific address cannot be communicated with
  • Changing routes when a tunnel goes down

The API specialized for Yamaha routers is published on this page. Yamaha plans to continually add to the API. The Lua version on Yamaha routers is 5.1.4 or 5.1.5. For details, see Lua Script Function Version Revision History.

For the specifications of the Lua programming language that Yamaha implements, see Lua programming language syntax and Library functions.

For the original Lua language specifications, see the Lua 5.1 Reference Manual.

Compatible Models and Firmware Revisions

The Yamaha router supports the Lua script function with the following models and firmware.

Model Firmware
RTX5000 Rev. 14.00.15 or later
FWX120 Rev. 11.03.16 or later
RTX810 Rev. 11.01.15 or later

Lua Script Function Version Revision History

The following is a table comparing the Lua script function version revision history and each model's firmware.

_RT_LUA_VERSION Change details Compatible Firmware
RTX5000 FWX120 RTX810
"1.0" Initial release Rev.14.00.15 or later Rev.11.03.16 or later Rev.11.01.15 or later
"1.01" The following functions were added:
  • BIGNUM can now be used
  • A bitwise operations library was added
  • Some mathematical library functions can now be used
v v v
"1.02" The following functions were added:
  • A hardware library was added
  • The HTTP client function (rt.httprequest function) was added
v v v
"1.03" The following functions were added:
  • Created the string.regexp function that generates regular expression objects
    The string.regexp function can now be called from regular expression syntactic sugar
  • The following functions can now use regular expression objects as patterns:
    • string.find
    • string.match
    • string.gmatch
    • string.gsub
    • string.split
    • rt.syslogwatch
  • Created string.split function that separates character strings with patterns
  • Created the each function to walk through array and argument elements
v v v
"1.04" Can now read the USB barcode reader and USB keyboard output with the hardware library v v v
"1.05" Changed the following:
  • Updated the Lua version to 5.1.5
  • Can now specify whether to insert router information at the head of an email message with the rt.mail function
v v v
"1.06" Support added for LuaSocket v v v
"1.07" rt.command supports to be specified whether command execution log is output or not. Rev.14.00.18
or later
v Rev.11.01.25
or later

The latest firmware of the Lua script function version includes a function to support earlier versions. For details, see Lua programming language syntax and Library functions.

Definition of Terms

Lua tasks ...

Specialized tasks prepared for the router OS to execute Lua script. A total of 10 tasks (*1) have been prepared: eight for the lua commands, one for execution from the DOWNLOAD button, and one for the Lua compiler. Each task is independent so the Lua task can be run at the same time up to the maximum number.

(*1) Models that do not have the DOWNLOAD button have nine tasks, excluding the task for execution from the DOWNLOAD button.

Details

1. Lua script execution methods and environment

You can execute the lua command by logging in to the router with administrator privileges or by pressing the DOWNLOAD button and starting the specified Lua script. Of the lua command options in the Lua standards, the lua command does not support the -i / - option that must be entered for script with standard input (stdin) and no parameter execution. The following are ways in which to run a Lua script.

  1. Execute the lua command from a serial console or a TELNET/SSH client
  2. Execute the lua command using a remote setup function
  3. Execute a lua command from the command execution screen on the GUI
  4. Automatic execution of the lua command using the schedule at command (execution at a set time or execution when the router starts)
  5. Hold down the DOWNLOAD button (excluding models that do not have a DOWNLOAD button)

The following are examples of lua commands.

Example 1: Executing a script file on external memory.

# lua usb1:/sample.lua

Example 2: Executing a script described on the command line.

# lua -e 'for i = 1, 10 do rt.command("no ip filter " .. i) end'

Example 3: Executing multiple scripts consecutively.

# lua -e 'rt.command("clear log")' -e 'rt.syslog("info", "run script")' usb1:/sample.lua

As the lua command is only a trigger to run the specified Lua script, it returns to the command prompt without waiting for the Lua script to finish. Therefore, you can consecutively execute the same command from the same console to run multiple Lua scripts. However, you can only run up to eight scripts at the same time. As one Lua task is allocated to one lua command in the Lua script function, the Lua tasks will only use the number of scripts running at the same time. As stated in Example 3, if multiple Lua scripts are specified with one lua command, multiple Lua scripts will execute in one task in the specified order. You can check the Lua script run and past execution status from the show status lua command. Also, to forcibly terminate running Lua scripts, use the terminate lua command.

If a syntax error occurs in an executed Lua command or script, an INFO type error message will be output to the system log and script execution will be halted.

[System log example]

2009/09/21 12:20:07:  lua:  mail.lua:26: 'rt.mail': 'text' field value of argument #1 is invalid.

As duplicate checks of the script file are not performed, if you specify the same script file at the same time and execute lua command, the same script file will run with multiple Lua tasks. If you mistakenly executed them, you can use the terminate lua command to forcibly terminate the unnecessary Lua task(s).

Execution with the DOWNLOAD button (excluding models that do not have a DOWNLOAD button)

You can execute only one script file from the DOWNLOAD button. Complicated operations like the lua command cannot be performed.

If you use the DOWNLOAD button to run Lua script, only one Lua task will be allocated. However, as there is a Lua task that is dedicated to the DOWNLOAD button in addition to the eight tasks that are allocated when the lua command is executed, even if the Lua tasks for the lua command are all busy, you can run a Lua script from the DOWNLOAD button. The following describes execution methods using the DOWNLOAD button.
* For models that do not have a DOWNLOAD light, the DOWNLOAD light does not turn on or flash.

  • Lua script execution is allocated to the DOWNLOAD button function with the operation button function download command.
  • If you hold the DOWNLOAD button for more than three seconds, the Lua script will run.
    An alarm, "beep", will sound and the DOWNLOAD light will begin flashing. When the Lua script ends, an alarm, "beep pip beep pip", will sound and the DOWNLOAD light will turn off.
  • If you want to terminate Lua script while it is running, hold down the DOWNLOAD button for more than one second. If you terminate a Lua script, the DOWNLOAD light turns off. Note that if you hold down the DOWNLOAD button for more than three seconds, the Lua script will run again so when the DOWNLOAD light turns off, let go of the button.
    You can also terminate script that you ran with the DOWNLOAD button with the terminate lua command. In this case, when the Lua script terminates, an alarm, "beep beep beep beep", will sound and the DOWNLOAD light will turn off.
  • If the Lua script fails, an alarm, "beep beep beep beep", will sound and the DOWNLOAD light will turn off.
    If this happens, hold down the DOWNLOAD button for more than one second to clear the error and the DOWNLOAD light turns off.
  • If a Lua script that you executed with the DOWNLOAD button is still running and you execute the operation button function download command, the Lua script will forcibly terminate, regardless of whether there are any parameter changes.

Resident Lua script

As it is executed with a dedicated task, you can run resident Lua scripts that are endless in programs. Lua tasks have been configured to use a limited amount of CPU resources, but depending on the content of the executed script, CPU usage rate may rise to almost 100%. Therefore, you need to make sure that the CPU usage rate does not become high for script programs as well (see Precautions).

2. File I/O

You can save script files to the router's built-in flash ROM (RTFS) or external memory. RTFS is the file system built into the router's built-in flash ROM. If you specify a script file with the lua command or the operation button function download command, you can specify the absolute path of the saved location or the relative path from the PWD environment variable. To specify the absolute path, add a prefix, such as usb1: or sd1:, that follows the external memory port on the router to the file path to indicate the external memory. If no prefix that indicates the external memory is described, the system will determine that it is a file path indicates the RTFS. To specify a relative path, use the PWD environment variable to differentiate between the external memory and RTFS. Note that script file encryption is not supported.

For the file system operation method, see the technical documentation (RTFS / Using external memory).

Example 1: Specifying a script file on the built-in flash ROM with an absolute path.

# lua /lua/sample.lua

Example 2: Specifying a script file on external memory with an absolute path.

# lua usb1:/lua/sample.lua

Example 3: Configuring a script on external memory that you will execute with the DOWNLOAD button with an absolute path.

# operation button function download execute lua usb1:/lua/sample.lua

Example 4: Specifying a script file with a relative path.

# lua sample.lua

If Example 4 had /lua configured in PWD, it would be the same as Example 1, and if usb1:/lua was configured, it would be the same as Example 2.

In the same manner, the file operating system function in the Lua standard functions can also specify the router's built-in flash ROM or external memory, and files can be generated and read on each device. The absolute path and relative path can be used for the file name of file operating system function argument. Note that frequent writing to the flash ROM will shorten the life of the device so take care when executing scripts that write repeatedly to the flash ROM (see Precautions).

Example: Writing the content of the file in_file.txt on the built-in flash ROM to the file out_file.txt on a USB flash drive.

-- Script 

fdr, err = io.open("/in_file.txt", "r")
if (not fdr) then
	print(err)
	os.exit(-1)
end
fdw, err = io.open("usb1:/out_file.txt", "w")
if (not fdw) then
	print(err)
	fdr:close()
	os.exit(-1)
end
str = fdr:read("*a")
fdw:write(str)
fdr:close()
fdw:close()

Standard input (stdin), standard output (stdout), and error output (stderr) of a defined file descriptor is not supported, so they cannot be specified. However, the print( ) function, a standard Lua function, can be used. The output destination of the print( ) function is the router console that executed the lua command, but if a Lua script is executed with the schedule at command or execution is triggered by the DOWNLOAD button, nothing will be output for the print( ) function.

3. Lua standard functions

The Lua version on Yamaha routers is 5.1.4 or 5.1.5. Of the standard functions that Lua 5.1.4 and 5.1.5 versions support, there are some functions that cannot be used or use methods are restricted on Yamaha routers. The functions not listed here can be used as per the standard specifications.

Functions that cannot be used

  • Mathematical library functions (math.XXX)
    • For firmware that is _RT_LUA_VERSION 1.0, no functions can be used.
    • For firmware whose is _RT_LUA_VERSION is "1.01", some functions cannot be used.
      For details, see the Library functions page.
  • package.loadlib( )
  • io.popen( )
  • io.tmpfile( )
  • file:setvbuf( )
  • file:seek( )
  • os.execute( ) (rt.command( ) can be used as a substitute)
  • os.setlocale( )
  • os.tmpname( )
  • debug.debug( )

Functions that have use method restrictions

  • dofile( )/loadfile( )
    As standard input is not supported, make sure to specify the argument file name.
  • require( )
    As the C module cannot be loaded, specify the module name described in Lua for the argument.
  • string.format( )
    The characters e, E / f, F / g, G cannot be used for the type conversion specifier of the command format.
  • io library (io.XXX)
    As standard input and output is not supported, the default input/output file is not configured in the default state. If performing operations on the default input/output file, you need to configure it in advance with io.input( ) and io.output( ). Standard input (stdin), standard output (stdout), and error output (stderr) cannot be used as file handles.
  • io.open( )
    You cannot append a plus sign (+), such as "r+" / "w+" / "a+", to the mode. As RTFS is not supported in append mode, you cannot specify "a" if the file to be opened is on the built-in flash ROM.
  • io.read( ) / file:read( )
    You cannot use "*n" in the command format.
  • os.date( )
    As isdst is not supported, when "*t" is specified in the format argument isdst field in the returned table will always state false.
  • os.time( )
    As isdst is not supported, if isdst is in the argument table field it will be ignored.

4. Lua global variables

In the Lua standard, there are reserved global variables, such as "_VERSION", and they can be referenced by just specifying the variable name inside the script. This section explains the reserved global variables that have been newly added for the router.

_RT_LUA_VERSION
_RT_LUA_VERSION_NUM

In addition to the base Lua version (_VERSION), there is a version with this function customized for the router independently. The initial release of this function has the string 1.0 for the _RT_LUA_VERSION and in accordance with expansion of this function's specifications and the addition of an API for the router, the version number has increased. The _RT_LUA_VERSION_NUM is indicated by a number, which is a three digit number with the first digit being the major number and the last two digits being the minor numbers. For 1.0, _RT_LUA_VERSION_NUM == 100. If you need to use the API separately with the old and new router firmware, you can categorized it with this variable.

Example: Branch processing from the _RT_LUA_VERSION_NUM.

-- Script 

if (_RT_LUA_VERSION_NUM >= 200) then 
    -- use the API compatible with 2.0 
else 
    -- use the API compatible with the version earlier than 2.0 
end

_RT_FIRM_REVISION

The character string that indicates the router firmware revision is configured.

Example: Display of each version

-- Script 

a = _RT_LUA_VERSION
b = _RT_LUA_VERSION_NUM
c = _RT_FIRM_REVISION
d = _VERSION

print("_RT_LUA_VERSION     : " .. a)
print("_RT_LUA_VERSION_NUM : " .. b)
print("_RT_FIRM_REVISION   : " .. c)
print("_VERSION            : " .. d)
[Result]

_RT_LUA_VERSION     : 1.0
_RT_LUA_VERSION_NUM : 100
_RT_FIRM_REVISION   : RTX810 Rev.11.01.29 (Fri Jan 20 08:10:19 2017)
_VERSION            : Lua 5.1

5. Router environment variables

You can configure environmental variables with the set command for well-used addresses, character strings, and different settings for each router. The configured environmental variable references the Lua standard function os.getenv( ). It is useful if you want to standardize the Lua script on each router.

Example: Configure the gateway address on the WAN in the environment variable and ping that address five times.

( config )
# set GATEWAY1=172.16.1.100
-- Script

adr = os.getenv("GATEWAY1")
rt.command("ping -c 5 " .. adr)

Next, the environment variable referenced internally by the Lua script function will be explained.

LUA_INIT (capital letters)

LUA_INIT configures the script to be executed when Lua starts beforehand. If LUA_INIT is configured, that script will always be executed before scripts specified with lua command and so on run. If the setting value has an "@" symbol at the front, it will be recognized as the path indicating the script file; all others will be recognized as script character stings.

Example 1: Configure a script file for initialization.

# set LUA_INIT=@/lua/init.lua

Example 2: Configure a script for initialization. If the setting value has a special character, it needs to be linked with a double quotation (") or single quotation (').

# set LUA_INIT='rt.command("clear log")'

The LUA_INIT default value is not configured.

LUA_PATH (capital letters)

LUA_PATH configures the path that the Lua standard function require( ) uses to load the Lua module. Lua uses "?" as a permutation symbol of a module name, but if "?" is entered on the router console, Help appears, so enter the escape sequence "\" before entering the "?".

Example: If the module to be loaded is under "usb1:/"

# set LUA_PATH="usb1:/\?.lua;"

If LUA_PATH is not configured, "./?.lua;" will be used as the default path.

Note: A C module cannot be loaded for require( ) in this function. Therefore, the LUA_CPATH is not used.

PWD (capital letters)

PWD configures the absolute path as the origin path of the relative path that indicates the script file. If specifying a script file with a relative path with the lua command or other commands, this PWD is the origin. A slash (/) at the end is not necessary.
If PWD is not configured, a slash (/) (the RTFS root) will be used as the default path.

Example: Configure the path to a script file.

# set PWD="/lua"

6. Dedicated Yamaha Router APIs

By using the API specialized for the Yamaha router, you can program the router operations. Yamaha plans to continually add to the API.

Public site of Lua for the API specialized for the Yamaha router

7. Lua compiler (Luac)

By executing the luac command, you can compile Lua script and generate bytecode (intermediate language). Of the standard luac command options, the - option that must be entered for script with standard input (stdin) is not supported. You can only run one Lua compiler at a time. Unlike the lua command, the command will not be returned until the compiling ends, so you can forcibly terminate compilation while it is running by pressing CTRL + C. The schedule at command cannot be specified for the luac command.

Example:

# luac -o usb1:/script.out usb1:/script.lua

It is also possible to execute a generated byte code file by specifying it as an execution target of the lua command, etc. This method is effective if you wish to reduce the execution load of the Lua script or make it difficult to understand the content of the saved script files at quick glance. You can only execute byte codes that have been generated on the router; byte codes generated on the PC, etc. on which Lua was installed cannot be executed.

Example:

# lua usb1:/script.out

Notes

  • Please use the built-in flash ROM of the router (RTFS) as an application to save the script files for execution. Note that frequent writing to the external memory or built-in flash ROM of the router will shorten the life of the device so take care when executing scripts that write repeatedly to the external memory/flash ROM. In particular, if malfunction occurs in the built-in flash ROM of the router due to frequent writing, it will not be covered by the warranty even within the warranty period.
  • The Lua version on Yamaha routers is 5.1.4 or 5.1.5. The Lua language specifications conform with those for Lua 5.1.4/5.1.5. There was an issue with some SJIS characters not displaying correctly for the Lua standard, but those issues have been fixed and Japanese (SJIS characters) can be used in strings and comments. However, Japanese (SJIS characters) cannot be used for function and variable names.
  • The Lua script function has been configured to use a limited amount of CPU resources. Therefore, even if a script is run that is only an endless loop, the CPU usage rate will not become 100%. However, if you execute multiple scripts at the same time that have high command loads, the CPU usage rate will become high and may affect other router functions. If you repeatedly perform the same process like an endless loop over a long period of time, take care that CPU usage rate does not become high by occasionally inserting rt.sleep( ) or the like. rt.sleep( ) suspends tasks.
  • Lua programming language numeric type lua_Number has been changed from the standard double type (64-bit double-precision floating point type) to long type (32-bit signed integral type). Numbers expressed by float or double are not supported by Lua on the Yamaha router. Likewise, e, E / f, F / g, G cannot be used for the type conversion specifier of the command format for the string.format( ) function.
  • Standard input (stdin), standard output (stdout), and error output (stderr) of a defined file descriptor cannot be used in a Lua script.
  • Any C modules cannot be loaded for the Lua standard function require( ). Therefore, LUA_CPATH is not used in this function.

Commands

Set Whether to Enable the Lua Script Function

[Syntax]

lua use switch
no lua use [switch]

[Setting and Initial value]

  • switch
    • [Setting] :
      Setting Description
      on Enable
      off Disable
    • [Initial value] : on

[Description]

Sets whether to enable the Lua script function.
If you use this command to disable the Lua script function, any Lua scripts that are running are stopped.

[Models]

RTX810 RTX5000 FWX120

Execute a Lua Script

[Syntax]

lua [-e stat] [-l module] [-v] [--] [script_file [args ...]]

[Setting and Initial value]

  • stat
    • [Setting] : Script character string
    • [Initial value] : -
  • module
    • [Setting] : The module to load (require)
    • [Initial value] : -
  • script_file
    • [Setting] : Specify the absolute or relative path of a script file or bytecode file.
    • [Initial value] : -
  • args
    • [Setting] : The variable arguments to pass to script_file.
    • [Initial value] : -

[Description]

Executes a Lua script.
The basic syntax is the same as that for standard lua commands, however, the router does not support execution without parameters or the g-ih and g-h options for using the standard input (stdin) as the script's input. The g-vh option outputs the version information.
-- The g--h option terminates the option at the described point, and you can specify a file name and text string starting from g-h for script_file and args.
The g-eh, g-lh, and g-vh options can be specified multiple times, but they cannot be specified after script_file. You can only specify one file for the script_file parameter. Any parameters listed after the script_file parameter are ignored. No error message appears to indicate ignored parameters.

If you set script_file to a relative path, it is interpreted as a path starting with the PWD environment variable. You can change PWD with the set command. Its initial value is g/h.

[Note]

If the LUA_INIT environment variable has been set, the script that is specified is executed first.
For the script_file parameter, you can only specify bytecode files that were created on the router. You cannot execute bytecode files that have been created by other devices, such as a PC with Lua installed on it.

[Models]

RTX810 RTX5000 FWX120

Execute the Lua Compiler

[Syntax]

luac [-l] [-o output_file] [-p] [-s] [-v] [--] script_file [script_file ..]

[Setting and Initial value]

  • output_file
    • [Setting] : Specify the absolute or relative path of the bytecode file to output to.
    • [Initial value] : luac.out (relative path)
  • script_file
    • [Setting] : Specify the absolute or relative path of the script file to compile.
    • [Initial value] : -

[Description]

Executes the Lua compiler and creates a bytecode file.
The fundamental syntax is the same as that of the standard Lua luac command, except that the g-h option cannot be specified. The g-lh option generates a list of the bytecode. The g-ph option only performs syntax analysis. The g-sh option removes comments and other debugging information. The g-vh option outputs the version information.
-- The g--h option terminates the option at the described point, and you can specify a file name starting from g-g for script_file.
You can include multiple script_file specifications and make them into a single bytecode file.

If you set script_file or output_file to a relative path, it is interpreted as a path starting with the PWD environment variable. You can change PWD with the set command. Its initial value is g/h.

[Models]

RTX810 RTX5000 FWX120

Show the Status of Running Lua Scripts

[Syntax]

show status lua [info]

[Setting and Initial value]

  • info : Type of information to be shown
    • [Setting] :
      Setting Description
      running Information about currently running scripts
      history Information about scripts that ran in the past
      Omitted All information is displayed
    • [Initial value] : -

[Description]

Displays status of the Lua script running currently, and its past operation history. This information is cleared if you disable the Lua script function using the lua use command.

  • Lua version information
  • Running scripts [running]
    • Lua task number
    • Running status
      RUN Running
      SLEEP Sleeping
      WATCH Monitoring SYSLOG (the Lua task is sleeping)
      COMMUNICATE Sending and receiving the HTTP message
      TERMINATE Stopping forcedly
    • Trigger
      • lua command
      • luac command
      • Schedule
      • DOWNLOAD button
    • Command line
    • Script file name
    • Text string to be monitored (when SYSLOG is being monitored)
    • Starting date and time and run time
  • Scripts ran in the past [history] (the most recent ten with the newest script listed first)
    • Trigger
      • lua command
      • luac command
      • Schedule
      • DOWNLOAD button
    • Command line
    • Script file name
    • Number of times ran/number of errors/Error history (the most recent five with the newest message listed first)
    • The latest start date and time, end time, and result
[Display example]

# show status lua
Lua Library Version:            Lua 5.1.4
Lua Script Function Version:    1.0

[running]
Lua Task ID (State): 1  (RUN)
Running Trigger:     executed by 'lua' command
Command Line:        lua test.lua
Script File:         /lua/test.lua
Starting Date:       2009/09/21 16:41:01
Elapsed Time:        6 seconds
-------------------------------------------------------------------------------
Lua Task ID (State): 9  (SLEEP)
Running Trigger:     executed by DOWNLOAD button
Script File:         usb1:/lua/test2.lua
Starting Date:       2009/09/21 16:40:32
Elapsed Time:        35 seconds

[history]
(1)
Running Trigger:     executed by DOWNLOAD button
Script File:         usb1:/lua/mail.lua
Running Counts:      1
Error Counts:        1
Error Record:
  2009/09/21 16:37:51: lua: mail.lua:36: 'rt.mail': 'smtp_address' field of arg
ument #1 doesn't exist.
First Starting Date: 2009/09/21 16:37:51
Last Starting Date:  2009/09/21 16:37:51
Last Ending Date:    2009/09/21 16:37:51
Last Result:         failure
-------------------------------------------------------------------------------
(2)
Running Trigger:     executed by 'lua' command
Command Line  :      lua -e "print(rt.command(\"show environment\"))"
Running Counts       3
Error Counts:        0
First Starting Date: 2009/09/21 16:35:47
Last Starting Date:  2009/09/21 16:36:57
Last Ending Date:    2009/09/21 16:36:57
Last Result:         success

[Models]

RTX810 RTX5000 FWX120

Stop a Lua Script

[Syntax]

terminate lua task_id
terminate lua file script_file

[Setting and Initial value]

  • task_id : The number of the Lua task that you want to stop
    • [Setting] :
      Setting Description
      all All Lua task numbers
      1..10 (for models without DOWNLOAD button 1..9) A Lua task number
    • [Initial value] : -
  • script_file
    • [Setting] : Specify the absolute or relative path of the script file or bytecode file that you want to stop.
    • [Initial value] : -

[Description]

Stops the specified Lua task or script.
In the first syntax, the Lua task specified by the task_id parameter is stopped. You can view Lua task numbers and scripts that are currently being executed by executing the show status lua command.

In the second syntax, all Lua tasks that are executing the script that matches perfectly with the path and file name specified by script_file are stopped. If you specify a relative path for script_file, the router searches for Lua tasks after first converting the path to an absolute path that starts with environment variable PWD.

To stop Lua scripts that are using the -e option and running without a script file, use the first syntax.

[Models]

RTX810 RTX5000 FWX120

Set Environment Variables

[Syntax]

set name=value
no set name[=value]

[Setting and Initial value]

  • name
    • [Setting] : Environment variable name
    • [Initial value] : -
  • value
    • [Setting] : Setting
    • [Initial value] : -

[Description]

Sets the routers environment variables.

The environment variable naming rules are listed below.
Alphanumeric characters and underscores can be used, but names cannot start with underscores or numbers.
There is no variable name length limit, but the set command cannot be executed if it exceeds the maximum command line length (4095 characters).
Names are case-sensitive. For example, gabch and gAbch are treated as different variables.

[Models]

RTX810 RTX5000 FWX120

Set Whether to Sound Alarms for the Lua Script Function

[Syntax]

alarm lua switch
no alarm lua [switch]

[Setting and Initial value]

  • switch
    • [Setting] :
      Setting Description
      on Sound alarms.
      off Do not sound alarms.
    • [Initial value] : on

[Description]

Sets whether to sound alarms for the Lua script function.

[Note]

This command allows you to set whether to sound alarms using the DOWNLOAD button when executing the Lua script function. To set whether to sound alarms under control from hardware libraries, follow the setting of the alarm entire command.

[Models]

FWX120 RTX820

Set the Function to Execute When the DOWNLOAD Button Is Pressed

[Syntax]

operation button function download function [script_file [args ...]]
no operation button function download [function [script_file [args ...]]]

[Setting and Initial value]

  • function : The function to execute when the DOWNLOAD button is pressed
    • [Setting] :
      Setting Description
      http revision-up HTTP revision update
      execute batch Batch file execution
      mobile signal-strength Acquisition of the signal reception level of a mobile terminal
      execute lua Lua script execution
    • [Initial value] : http revision-up
  • script_file
    • [Setting] : Specify the absolute or relative path of a script file or bytecode file.
    • [Initial value] : -
  • args
    • [Setting] : The variable arguments to pass to script_file.
    • [Initial value] : -

[Description]

Sets the function that is executed when the DOWNLOAD button is pressed. While the function is being executed, the LED below the DOWNLOAD button lights. The LED turns off when the execution of the function is completed.

If you set the function parameter to execute lua, you must specify a file for the script_file parameter. If you set script_file to a relative path, it is interpreted as a path starting with the PWD environment variable. You can change PWD with the set command. Its initial value is g/h.

[Note]

When you execute a Lua script, if the LUA_INIT environment variable has been specified, it will be executed before the file specified by the script_file parameter.

[Models]

RTX810 FWX120

Set the Schedule

[Syntax]

schedule at id [date] time * command...
schedule at id [date] time pp peer_num command...
schedule at id [date] time tunnel tunnel_num command...
schedule at id [date] time switch switch command...
no scudule at id [[date]...]

[Setting and Initial value]

  • id
    • [Setting] : Schedule number
    • [Initial value] : -
  • date : Date (can be omitted)
    • [Setting] :
      • Month/Day
      • Assumed to be */* if omitted
        Month Setup Example Setting
        1,2 January and February
        2- February to December
        2-7 February to July
        -7 January to July
        * Every month
        Date Setup Example Setting
        1 Day 1 only
        1,2 Day 1 and 2
        2- Day 2 to the end of the month
        2-7 Day 2 to 7
        -7 Day 1 to 7
        mon Monday only
        sat,sun Saturday and Sunday
        mon-fri Monday through Friday
        -fri Sunday through Friday
        * Every day
    • [Initial value] : -
  • time : Time
    • [Setting] :
      Setting Description
      hh:mm[:ss] Hour (0..23 or *): Minute (0..59 or *): Second (0..59). The second can be omitted.
      startup At startup
      usb-attached When a USB device is detected
      sd-attached When a microSD is detected
    • [Initial value] : -
  • peer_num
    • [Setting] :
      • Peer number
      • anonymous
    • [Initial value] : -
  • tunnel_num
    • [Setting] : Tunnel interface number
    • [Initial value] : -
  • switch : Switch
    • [Setting] :
      • MAC address
      • Route
    • [Initial value] : -
  • command
    • [Setting] : Command to be executed (limitations exist)
    • [Initial value] : -

[Description]

Executes the command specified by command at the time specified by time.
If the second, third or fourth syntax is specified, the command operates as if the pp select/tunnel select/switch select command has been executed on the specified peer number, tunnel number or switch in advance.
Multiple schedule at commands can be specified. If multiple commands are specified at the same time, the commands are executed in ascending order of id.
When time is specified in the hh:mm format, the router determines that the second has been omitted. When it is specified in the hh:mm:ss format, the router determines that the second has been specified. You cannot use g-g for the number of seconds to specify a range, or g*h for total specification.

The following commands cannot be specified.
administrator, administrator password, administrator password encrypted, auth user, auth user group, bgp configure refresh, cold start, commands starting with console excluding console info and console prompt, copy, copy exec, date, delete, exit, external-memory performance-test go, help, http revision-up go, http revision-up schedule, interface reset, commands starting with less, login password, login password encrypted, login timer, login user, luac, make directory, nslookup, ospf configure refresh, packetdump, ping, ping6, pp select, quit, remote setup, rename, rtfs format, rtfs garbage collect, save, schedule at, commands that start with show, sshd host key generate, sshd session, ssl public key generate, system packet-buffer, telnet, telnetd session, time, timezone, traceroute, traceroute6, tunnel select, user attribute

[Note]

Command completion using the TAB key is carried out for the command parameter when entering a command. However, errors such as syntax errors are not detected until the command is actually executed. When executing a command specified by the schedule at command, the command that was attempted is output to the SYSLOG of INFO type.
A number and a day of the week cannot be mixed in date.
A schedule with startup specified is executed when the router starts up. This is convenient for cases such as when you wish to originate a call as soon as the power is turned on.

[Example]

Allow connection only between 8:00 and 17:00 on a weekday

# schedule at 1 */mon-fri 8:00 pp 1 wan1 auto connect on
# schedule at 2 */mon-fri 17:00 pp 1 wan1 auto connect off
# schedule at 3 */mon-fri 17:05 * disconnect 1

Allow connection only for 15 minutes from minute 0 of every hour

# schedule at 1 *:00 pp 1 wan1 auto connect on
# schedule at 2 *:15 pp 1 wan1 auto connect off
# schedule at 3 *:15 * disconnect 1

Switch the routing on the next New Years day

# schedule at 1 1/1 0:0 * ip route NETWORK gateway pp 2

Execute a Lua script for 20 seconds every day between 12:00 and 13:00

# schedule at 1 12:*:00 * lua script.lua
# schedule at 2 12:*:20 * lua script.lua
# schedule at 3 12:*:40 * lua script.lua

Switch is rebooted everyday at 3 o'clock.

# schedule at 1 */* 03:00 switch 00:a0:de:01:02:03 switch control function execute restart
# schedule at 2 */* 03:00 switch lan1:4 switch control function execute restart

[Models]

RTX810 RTX5000 FWX120

Setting Examples

1. Send reboot information as an email when the router restarts

[Settings necessary for the configuration]

schedule at 1 startup * lua /lua/restart.lua

Configures a Lua script execution schedule when the router starts. Other settings, such as basic route settings, will be assumed to be already configured.

[Lua script]

-- ### restart.lua ###

--------------------------------------------------------------------------------
-- Function to execute a router command and return as an output result format --
--------------------------------------------------------------------------------
function exec_command(cmd)
	local rtn, str
	local text

	rtn, str = rt.command(cmd)
	if (rtn) and (str) then 
		text = string.format(Execution result of "\"%s\” \r\n\r\n%s\r\n", cmd, str) 
	else 
		text = string.format("\"%s\"execution failure\r\n\r\n", cmd) 
	end

	return text
end

------------------------------------------------------------ 
-- Main part                                             -- 
------------------------------------------------------------
mail_table = { 
	smtp_address = "smtp.xxxx.co.jp",            --  change accordingly
	from = "rt-admin@xxxx.co.jp",                -- change accordingly
	to = "rt-admin@xxxx.co.jp",                  -- change accordingly
	subject = "the router restarted"
}

-- information collection 
mail_table.text = exec_command("show status boot all")
mail_table.text = mail_table.text .. exec_command("show log") 

-- send mail 
rt.mail(mail_table)

Create the above restart.lua text file and save it under /lua in RTFS. For how to save the file, see here.

[Script explanation]

  • /lua/restart.lua
    This script sends an email with the execution result of show status boot all and show log to the administrator. If you configure a schedule for this script to execute when the router starts, you will know immediately if the router restarted and you will also be obtain information necessary for analysis.

2. Depending on the WAN communication status, configure QoS and send an email with the monitoring status at set intervals.

[Network configuration]

  • IPsec-VPN connection between headquarters and Tokyo office
  • The Tokyo office connects to the ISP with a terminal
  • Only apply QoS during times when packet loss is great

Network configuration

[Tokyo office router configuration example]

set GATEWAY=172.16.10.254
set LUA_INIT=@/lua/init.lua
set PWD=/lua/tokyo

ip route default gateway 172.16.10.254
ip route 192.168.1.0/24 gateway tunnel 1
ip lan1 address 192.168.2.1/24
ip lan2 address 172.16.10.1/24
ip lan2 nat descriptor 1

tunnel select 1
 ipsec tunnel 101
  ipsec sa policy 101 1 esp aes-cbc sha-hmac anti-replay-check=off
  ipsec ike always-on 1 on
  ipsec ike pre-shared-key 1 text PASSWORD
  ipsec ike remote address 1 172.16.2.1
 tunnel enable 1
ipsec auto refresh on

nat descriptor type 1 masquerade
nat descriptor address outer 1 primary
nat descriptor masquerade static 1 1 192.168.2.1 udp 500
nat descriptor masquerade static 1 2 192.168.2.1 esp

[Configuration explanation]

set GATEWAY=172.16.10.254
set LUA_INIT=@/lua/init.lua
set PWD=/lua/tokyo

Configures the environment variables that the script uses.

[Lua script]

-- ### init.lua ###

rt.command("clear log") 
rt.syslog("info", "[script run]")

Create the above init.lua text file and save it under /lua in RTFS. For how to save the file, see here.

-- ### ping.lua ###

adr = os.getenv("GATEWAY")

--------------------------------------------------------------- 
-- Function to execute PING n times and return the loss rate -- 
---------------------------------------------------------------
function exec_ping(n)
	local ping_cmd
	local rtn, str
	local loss

	ping_cmd = string.format("ping -c %s -w 0.5 %s", n, adr)
	rtn, str = rt.command(ping_cmd)
	if (not rtn) or (not str) then 
		-- error 
		return -1
	end 

	loss = string.match(str, "(%d+)%.%d+%%")     -- Extract the intergral part of the packet loss rate (NNN.N%) 
	if (not loss) then
		loss = -1
	else
		loss = tonumber(loss)
	end

	return loss
end

--------------------------------------------------------------------------
-- Function to cancel/configure QoS in order to prioritize IPsec packet --
--------------------------------------------------------------------------
function set_qos(set)
	local no = ""

	if (not set) then
		no = "no "
	end

	rt.command(no .. "queue class filter 1 4 ip * * udp 500")
	rt.command(no .. "queue class filter 2 4 ip * * esp")
	rt.command(no .. "queue lan2 class filter list 1 2") 
	rt.command(no .. "speed lan2 80m")           -- Value that considers up speed 
	rt.command(no .. "queue lan2 type priority")
	rt.command("save")
end

------------------------------------------------------------
-- Main part                                              --
------------------------------------------------------------
local rtn, str

cnt = 1
qos = false
show_cmd = "show status qos all"
mail_table = { 
	smtp_address = "smtp.xxxx.co.jp",            -- change accordingly
	from = "admin-tokyo@xxxx.co.jp",             -- change accordingly
	to = "admin-tokyo@xxxx.co.jp",               -- change accordingly 
	subject = "Ping Status",
	text = ""
}

while (1) do
	set_qos_flag = false 

	-- 10 minute suspension 
	rt.sleep(600) 

	text = os.date("%Y%m%d %H%M%S: PING execution result\r\n") 

	loss = exec_ping(arg[1])

	if (loss < 0) then
		text = text .. "PING execution error"
	else
		text = text .. string.format("destination:%s loss:%d%%", adr, loss)

		if (loss >= 10) then
			if (not qos) then
				set_qos(true)
				set_qos_flag = true
				qos = true 
				text = text .. "\r\n configured QoS” 
			end
		elseif (loss == 0) then
			if (qos) then
				set_qos(false)
				qos = false 
				text = text .. "\r\n canceled QoS" 
			end
		end
	end 

	-- Record to system log 
	rt.syslog("info", text)
	text = text .. "\r\n" 

	-- send email notification in packets of 6 
	mail_table.text = mail_table.text .. text .. "\r\n"
	if (cnt < 6) then
		cnt = cnt + 1
	else
		-- When QoS is configured, the result of "show status qos" will be added to an e-mail's body.
		-- Except just behind the time when QoS is configured.
		if (qos) and (not set_qos_flag) then
			rtn, str = rt.command(show_cmd)
			if (rtn) and (str) then
				text = string.format("# %s\r\n%s", show_cmd, str)
				mail_table.text = mail_table.text .. text
			end
		end

		-- Sending an e-mail
		if (not rt.mail(mail_table)) then
			rt.syslog("info", "Failed rt.mail by Lua")
		end

		-- Reset after sending an e-mail
		cnt = 1
		mail_table.text = ""
	end
end

Create the above ping.lua text file and save it under /lua/tokyo in RTFS. For how to save the file, see here.

[Script explanation]

  • /lua/init.lua
    This script is for initialization to configure LUA_INIT. System log will be initialized.
  • /lua/tokyo/ping.lua
    This is the main script. The content of the script is as follows. This is a script that is an endless loop so make sure that rt.sleep( ) is stated.
    • Sends an optional number of pings to the WAN gateway every 10 minutes.
    • Configures QoS in order to prioritize IPsec packets when the ping packet loss rate is 10% or more.
    • Cancels QoS configuration when the ping packet loss rate is less than 1%.
    • Record every ping execution result to the system log.
    • Sends an email to the administrator with a set number of ping execution results.
    • If QoS is configured when an email is sent, the output result of show status qos all will be added to the body of the email.

[Script execution example]

# lua ping.lua 30

Logs in to the Tokyo office router via serial or TELNET and say you want to enter the number of ping transmissions as 30, enter as above on the command input screen. As /lua/tokyo is configured in PWD, the file path will be interpreted as /lua/tokyo/ping.lua. As ping.lua performs an endless loop, use the terminate lua command if you want to terminate it while it is running.

System log messages

The system log messages output by this function are displayed below. The prefix "[LUA]" is appended to the actual messages output. For output system log messages by APIs specialized for Yamaha routers, see the Lua for the API Specialized for the Yamaha Router page.

Level Output message Meaning
INFO Lua script function was enabled. The Lua script function was enabled.
Lua script function was disabled. The Lua script function was disabled.
DEBUG created Lua Task(N) Generated a Lua task with the task number (N)
terminated Lua Task(N) Forcibly terminated Lua task with the task number (N)
closed Lua Task(N): success Terminated Lua task with the task number (N) The executed script successfully completed.
closed Lua Task(N): failure Terminated Lua task with the task number (N) The executed script failed.

Reference Information

Return to Top

Product Categories