Manual:Scripting-examples: Difference between revisions

From MikroTik Wiki
Jump to navigation Jump to search
No edit summary
 
(10 intermediate revisions by 2 users not shown)
Line 1: Line 1:
<div class=manual>


<h2>CMD Scripting examples</h2>
==CMD Scripting examples==
<p>
 
This section contains some useful scripts and shows all available scripting features. Script examples used in this section were tested with the latest 3.x version.
This section contains some useful scripts and shows all available scripting features. Script examples used in this section were tested with the latest 3.x version.
</p>


<h3>Create a file</h3>
 
<p>
===Create a file===
 
In v3.x it is not possible to create file directly, however there is a workaround
In v3.x it is not possible to create file directly, however there is a workaround
<pre>
<pre>
Line 13: Line 12:
/file set myFile.txt contents=""
/file set myFile.txt contents=""
</pre>
</pre>
</p>


<h3>Check if IP on interface have changed</h3>
 
<p>
===Check if IP on interface have changed===
 
Sometimes provider gives dynamic IP addresses. This script will compare if dynamic IP address is changed.
Sometimes provider gives dynamic IP addresses. This script will compare if dynamic IP address is changed.


Line 30: Line 29:
</pre>
</pre>


</p>




<h3>Strip netmask</h3>
 
<p>
===Strip netmask===
 
This script is useful if you need ip address without netmask (for example to use it in firewall), but "<code>/ip address get [id] address</code>" returns ip address and netmask.
This script is useful if you need ip address without netmask (for example to use it in firewall), but "<code>/ip address get [id] address</code>" returns ip address and netmask.
<br />
 
Code:
Code:
<pre>
<pre>
Line 49: Line 48:
</pre>
</pre>


</p>


Another much more simple way:
<pre>
:global ipaddress 10.1.101.1/24
:put [:pick $ipaddress 0 [:find $ipaddress "/"]]
</pre>
===Resolve host-name===
Many users are asking feature to use dns names instead of IP address for radius servers, firewall rules, etc.
So here is an example how to resolve RADIUS server's IP.


<h3>Resolve host-name</h3>
<p>
Many users are asking feature to use dns names instead of IP address for radius servers, firewall rules, etc. <br />
So here is an example how to resolve RADIUS server's IP. <br />
Lets say we have radius server configured:
Lets say we have radius server configured:
<pre>
<pre>
Line 83: Line 88:
</pre>
</pre>


</p>


===Write simple queue stats in multiple files===
Lets consider queue namings are "some text.1" so we can search queues by last number right after the dot.
<pre>
:local entriesPerFile 10;
:local currentQueue 0;
:local queuesInFile 0;
:local fileContent "";
#determine needed file count
:local numQueues [/queue simple print count-only] ;
:local fileCount ($numQueues / $entriesPerFile);
:if ( ($fileCount * $entriesPerFile) != $numQueues) do={
  :set fileCount ($fileCount + 1);
}
#remove old files
/file remove [find name~"stats"];
:put "fileCount=$fileCount";
:for i from=1 to=$fileCount do={
#create file
  /file print file="stats$i.txt";
#clear content
  /file set [find name="stats$i.txt"] contents="";
  :while ($queuesInFile < $entriesPerFile) do={
    :if ($currentQueue < $numQueues) do={
        :set currentQueue ($currentQueue +1);
        :put $currentQueue ;
        /queue simple
        :local internalID [find name~"\\.$currentQueue\$"];
        :put "internalID=$internalID";
        :set fileContent ($fileContent . [get $internalID target-address] . \
          " " . [get $internalID total-bytes] . "\r\n");
    }
    :set queuesInFile ($queuesInFile +1);
   
  }
  /file set "stats$i.txt" contents=$fileContent;
  :set fileContent "";
  :set queuesInFile 0;
}
</pre>
===Generate backup and send it by e-mail===
This script generates backup file and sends it to specified e-mail address. Mail subject contains router's name, current date and time.


<h3>Generate backup and send it by e-mail</h3>
<p>
This script generates backup file and sends it to specified e-mail address. Mail subject contains router's name, current date and time. <br />
Note that smtp server must be configured before this script can be used. See <var>/tool e-mail</var> for configuration options.
Note that smtp server must be configured before this script can be used. See <var>/tool e-mail</var> for configuration options.
<br />
 
<br />
 
Script:
Script:
<pre>
<pre>
Line 98: Line 150:
   subject="$[/system identity get name] $[/system clock get time] $[/system clock get date] Backup")
   subject="$[/system identity get name] $[/system clock get time] $[/system clock get date] Backup")
</pre>
</pre>
</p>
{{Note | backup file contains sensitive information like passwords. So to get access to generated backup file, script or scheduler must have <b>'sensitive'</b> policy.


<h3>Use string as function</h3>
{{Note | backup file contains sensitive information like passwords. So to get access to generated backup file, script or scheduler must have <b>'sensitive'</b> policy.}}
<p>
 
 
===Use string as function===


Code:
Code:
Line 110: Line 162:
</pre>
</pre>


</p>


<h3>Check bandwidth and add limitations</h3>
===Check bandwidth and add limitations===
<p>
 
This script checks if download on interface is more than 512kbps, if true then queue is added to limit speed to 256kbps.<br />
This script checks if download on interface is more than 512kbps, if true then queue is added to limit speed to 256kbps.
 
Code:
Code:
<pre>
<pre>
Line 132: Line 184:
</pre>
</pre>


</p>


===Block access to specific websites===
This script is useful if you want to block certain web sites but you don't want to use web proxy.
This example looks entries "rapidshare" and "youtube" in dns cache and adds IPs to address list named "restricted".


<h3>Block access to specific websites</h3>
<p>
This script is useful if you want to block certain web sites but you don't want to use web proxy. <br />
This example looks entries "rapidshare" and "youtube" in dns cache and adds IPs to address list named "restricted". <br />


Before you begin, you must set up router to catch all dns requests:
Before you begin, you must set up router to catch all dns requests:
Line 153: Line 205:
</pre>
</pre>


Now we can write a script and schedule it to run, lets say, every 30 seconds.<br />
Now we can write a script and schedule it to run, lets say, every 30 seconds.
 
Script Code:
Script Code:
<pre>
<pre>
Line 161: Line 214:
#    :put $cacheName;
#    :put $cacheName;


     :if (([:find $cacheName "rapidshare"] != 0) || ([:find $cacheName "youtube"] != 0)) do={
     :if (([:find $cacheName "rapidshare"] >= 0) || ([:find $cacheName "youtube"] >= 0)) do={


         :local tmpAddress [/ip dns cache get $i address] ;
         :local tmpAddress [/ip dns cache get $i address] ;
Line 167: Line 220:


# if address list is empty do not check
# if address list is empty do not check
         :if ( [/ip firewall address-list find ] = "") do={
         :if ( [/ip firewall address-list find list="restricted" ] = "") do={
             :log info ("added entry: $[/ip dns cache get $i name] IP $tmpAddress");
             :log info ("added entry: $[/ip dns cache get $i name] IP $tmpAddress");
             /ip firewall address-list add address=$tmpAddress list=restricted comment=$cacheName;
             /ip firewall address-list add address=$tmpAddress list=restricted comment=$cacheName;
         } else={
         } else={
             :foreach j in=[/ip firewall address-list find ] do={
             :foreach j in=[/ip firewall address-list find list="restricted"] do={
                 :if ( [/ip firewall address-list get $j address] = $tmpAddress ) do={
                 :if ( [/ip firewall address-list get $j address] = $tmpAddress ) do={
                     :set bNew "false";
                     :set bNew "false";
Line 185: Line 238:
</pre>
</pre>


</p>
===Parse file to add ppp secrets===
 
This script requires that entries inside the file is in following format:
 
username,password,local_address,remote_address,profile,service


<h3>Parse file to add ppp secrets</h3>
For example:  
<p>
This script requires that entries inside the file is in following format:<br />
username,password,local_address,remote_address,profile,service <br />
For example: <br />
<pre>
<pre>
janis,123,1.1.1.1,2.2.2.1,ppp_profile,myService
janis,123,1.1.1.1,2.2.2.1,ppp_profile,myService
Line 224: Line 277:
</pre>
</pre>


</p>


<h3>Detect new log entry</h3>
 
<p>
===Detect new log entry===
This script is checking if new log entry is added to particular buffer. <br />
 
This script is checking if new log entry is added to particular buffer.


In this example we will use pppoe logs:
In this example we will use pppoe logs:
Line 240: Line 293:
Log buffer will look similar to this one:
Log buffer will look similar to this one:
<pre>
<pre>
[admin@mainGW] > /log print buffer=pppoe  
[admin@mainGW] > /log print where buffer=pppoe  
13:11:08 pppoe,info PPPoE connection established from 00:0C:42:04:4C:EE  
13:11:08 pppoe,info PPPoE connection established from 00:0C:42:04:4C:EE  
</pre>
</pre>


Now we can write a script to detect if new entry is added.
Now we can write a script to detect if new entry is added.
<br />
 
Code:
Code:
<pre>
<pre>
Line 270: Line 323:
After new entry is detected, it is saved in "message" variable, which you can use later to parse log message, for example, to get pppoe clients mac address.
After new entry is detected, it is saved in "message" variable, which you can use later to parse log message, for example, to get pppoe clients mac address.


</p>


<h3>Allow use of ntp.org pool service for NTP</h3>
===Allow use of ntp.org pool service for NTP===
 
This script resolves the hostnames of two NTP servers, compares the result with the current NTP settings and changes the addresses if they're different. This script is required as RouterOS does not allow hostnames to be used in the NTP configuration. Two scripts are used. The first defines some system variables which are used in other scripts and the second does the grunt work:
This script resolves the hostnames of two NTP servers, compares the result with the current NTP settings and changes the addresses if they're different. This script is required as RouterOS does not allow hostnames to be used in the NTP configuration. Two scripts are used. The first defines some system variables which are used in other scripts and the second does the grunt work:
<pre># System configuration script - "GlobalVars"
<pre># System configuration script - "GlobalVars"
Line 361: Line 414:
   start-time=16:00:00</pre>
   start-time=16:00:00</pre>


<h3>Auto upgrade script</h3>
===Auto upgrade script===
<p>
 
[[Auto_upgrade_script_V3.x]]
* [[Auto_upgrade_script_V3.x]]
</p>
 
<h3>Other scripts known to work with latest v3.x</h3>
 
===Other scripts known to work with latest v3.x===


* [[Dynamic_DNS_Update_Script_for_EveryDNS]]
* [[Dynamic_DNS_Update_Script_for_EveryDNS]]
Line 371: Line 425:
* [[UPS_scripts#version_for_ROS_3.x | UPS Script]]
* [[UPS_scripts#version_for_ROS_3.x | UPS Script]]


<h2>LUA Scripting examples</h2>
==LUA Scripting examples==
<p>NOTE!</p>
<p>NOTE!</p>
<p>After RouterOS v4.0beta4, Lua support is removed until further notice</p>
<p>After RouterOS v4.0beta4, Lua support is removed until further notice</p>
Line 381: Line 435:




<h3>Print function</h3>
===Print function===
<p>
<p>
As stated in [[Lua]] documentation, 'print' command is not available in RouterOS compared to standard Lua release. This example will show you how to get back 'print' command
As stated in [[Lua]] documentation, 'print' command is not available in RouterOS compared to standard Lua release. This example will show you how to get back 'print' command
Line 407: Line 461:
</p>
</p>


<h3>Read and write large files</h3>
===Read and write large files===
<p>
<p>
Many users requested ability to work with files. Now you can do it without limitations. <br />
Many users requested ability to work with files. Now you can do it without limitations. <br />
Line 425: Line 479:
</p>
</p>


<h3>Include custom function in another script</h3>
===Include custom function in another script===
<p>
<p>
This example will show where to store and how to include your cool custom created functions into another scripts <br />
This example will show where to store and how to include your cool custom created functions into another scripts <br />
Line 442: Line 496:
=== See also ===  
=== See also ===  


* Theory of [[Scripting]]
* Theory of [[M:Scripting | Scripting]]
* User submitted [[Scripts]]
* User submitted [[Scripts]]


</div>


{{Cont}}
{{Cont}}


[[Category:Manual]]
[[Category:Manual|S]]
[[Category:System]]
[[Category:System|S]]
[[Category:Console]]
[[Category:Console|S]]
[[Category:Examples]]
[[Category:Examples|S]]

Latest revision as of 09:37, 18 October 2017

CMD Scripting examples

This section contains some useful scripts and shows all available scripting features. Script examples used in this section were tested with the latest 3.x version.


Create a file

In v3.x it is not possible to create file directly, however there is a workaround

/file print file=myFile
/file set myFile.txt contents=""


Check if IP on interface have changed

Sometimes provider gives dynamic IP addresses. This script will compare if dynamic IP address is changed.

:global currentIP;

:local newIP [/ip address get [find interface="ether1"] address];

:if ($newIP != $currentIP) do={
    :put "ip address $currentIP changed to $newIP";
    :set currentIP $newIP;
}



Strip netmask

This script is useful if you need ip address without netmask (for example to use it in firewall), but "/ip address get [id] address" returns ip address and netmask.

Code:


:global ipaddress 10.1.101.1/24

:for i from=( [:len $ipaddress] - 1) to=0 do={ 
	:if ( [:pick $ipaddress $i] = "/") do={ 
		:put [:pick $ipaddress 0 $i]
	} 
}


Another much more simple way:

:global ipaddress 10.1.101.1/24
:put [:pick $ipaddress 0 [:find $ipaddress "/"]]

Resolve host-name

Many users are asking feature to use dns names instead of IP address for radius servers, firewall rules, etc.

So here is an example how to resolve RADIUS server's IP.

Lets say we have radius server configured:

/radius 
add address=3.4.5.6 comment=myRad

And here is a script that will resolve ip address, compare resolved ip with configured one and replace if not equal:

/system script add name="resolver" source= {

:local resolvedIP [:resolve "server.example.com"];
:local radiusID [/radius find comment="myRad"];
:local currentIP [/radius get $radiusID address];

:if ($resolvedIP != $currentIP) do={
   /radius set $radiusID address=$resolvedIP;
   /log info "radius ip updated";
}

}

Add this script to scheduler to run for example every 5 minutes

/system scheduler add name=resolveRadiusIP on-event="resolver" interval=5m


Write simple queue stats in multiple files

Lets consider queue namings are "some text.1" so we can search queues by last number right after the dot.

:local entriesPerFile 10;
:local currentQueue 0;
:local queuesInFile 0;
:local fileContent "";
#determine needed file count
:local numQueues [/queue simple print count-only] ;
:local fileCount ($numQueues / $entriesPerFile);
:if ( ($fileCount * $entriesPerFile) != $numQueues) do={
   :set fileCount ($fileCount + 1);
}

#remove old files 
/file remove [find name~"stats"];

:put "fileCount=$fileCount";

:for i from=1 to=$fileCount do={
#create file
   /file print file="stats$i.txt";
#clear content
   /file set [find name="stats$i.txt"] contents="";

   :while ($queuesInFile < $entriesPerFile) do={
     :if ($currentQueue < $numQueues) do={
         :set currentQueue ($currentQueue +1);
         :put $currentQueue ;
         /queue simple
         :local internalID [find name~"\\.$currentQueue\$"];
         :put "internalID=$internalID";
         :set fileContent ($fileContent . [get $internalID target-address] . \
           " " . [get $internalID total-bytes] . "\r\n");
     }
     :set queuesInFile ($queuesInFile +1);
     
   }
   /file set "stats$i.txt" contents=$fileContent;
   :set fileContent "";
   :set queuesInFile 0;

}

Generate backup and send it by e-mail

This script generates backup file and sends it to specified e-mail address. Mail subject contains router's name, current date and time.

Note that smtp server must be configured before this script can be used. See /tool e-mail for configuration options.


Script:

/system backup save name=email_backup
/tool e-mail send file=email_backup.backup to="me@test.com" body="See attached file" \
   subject="$[/system identity get name] $[/system clock get time] $[/system clock get date] Backup")

Note: backup file contains sensitive information like passwords. So to get access to generated backup file, script or scheduler must have 'sensitive' policy.



Use string as function

Code:

:global printA [:parse ":local A; :put \$A;" ];   
$printA 


Check bandwidth and add limitations

This script checks if download on interface is more than 512kbps, if true then queue is added to limit speed to 256kbps.

Code:

:foreach i in=[/interface find] do={
    /interface monitor-traffic $i once do={
        :if ($"received-bits-per-second" > 0 ) do={
            :local tmpIP [/ip address get [/ip address find interface=$i] address] ;
#            :log warning $tmpIP ;
            :for j from=( [:len $tmpIP] - 1) to=0 do={
                :if ( [:pick $tmpIP $j] = "/") do={
                    /queue simple add name=$i max-limit=256000/256000 dst-address=[:pick $tmpIP 0 $j] ;
                } 
            }
        }
    }
}


Block access to specific websites

This script is useful if you want to block certain web sites but you don't want to use web proxy.

This example looks entries "rapidshare" and "youtube" in dns cache and adds IPs to address list named "restricted".


Before you begin, you must set up router to catch all dns requests:

/ip firewall nat
add action=redirect chain=dstnat comment=DNS dst-port=53 protocol=tcp to-ports=53
add action=redirect chain=dstnat dst-port=53 protocol=udp to-ports=53

and add firewall

/ip firewall filter
add chain=forward dst-address-list=restricted action=drop

Now we can write a script and schedule it to run, lets say, every 30 seconds.

Script Code:

:foreach i in=[/ip dns cache find] do={
    :local bNew "true";
    :local cacheName [/ip dns cache all get $i name] ;
#    :put $cacheName;

    :if (([:find $cacheName "rapidshare"] >= 0) || ([:find $cacheName "youtube"] >= 0)) do={

        :local tmpAddress [/ip dns cache get $i address] ;
#	:put $tmpAddress;

# if address list is empty do not check
        :if ( [/ip firewall address-list find list="restricted" ] = "") do={
            :log info ("added entry: $[/ip dns cache get $i name] IP $tmpAddress");
            /ip firewall address-list add address=$tmpAddress list=restricted comment=$cacheName;
        } else={
            :foreach j in=[/ip firewall address-list find list="restricted"] do={
                :if ( [/ip firewall address-list get $j address] = $tmpAddress ) do={
                    :set bNew "false";
                }
            }
            :if ( $bNew = "true" ) do={
                :log info ("added entry: $[/ip dns cache get $i name] IP $tmpAddress");
                /ip firewall address-list add address=$tmpAddress list=restricted comment=$cacheName;
            }
        }
    }
}

Parse file to add ppp secrets

This script requires that entries inside the file is in following format:

username,password,local_address,remote_address,profile,service

For example:

janis,123,1.1.1.1,2.2.2.1,ppp_profile,myService
juris,456,1.1.1.1,2.2.2.2,ppp_profile,myService
aija,678,1.1.1.1,2.2.2.3,ppp_profile,myService

Code:


:global content [/file get [/file find name=test.txt] contents] ;
:global contentLen [ :len $content ] ;

:global lineEnd 0;
:global line "";
:global lastEnd 0;


:do {
       :set lineEnd [:find $content "\r\n" $lastEnd ] ;
       :set line [:pick $content $lastEnd $lineEnd] ;
       :set lastEnd ( $lineEnd + 2 ) ;

       :local tmpArray [:toarray $line] ;
	:if ( [:pick $tmpArray 0] != "" ) do={
	:put $tmpArray;
         /ppp secret add name=[:pick $tmpArray 0] password=[:pick $tmpArray 1] \
             local-address=[:pick $tmpArray 2] remote-address=[:pick $tmpArray 3] \
             profile=[:pick $tmpArray 4] service=[:pick $tmpArray 5];
}
} while ($lineEnd < $contentLen)


Detect new log entry

This script is checking if new log entry is added to particular buffer.

In this example we will use pppoe logs:

/system logging action
add name="pppoe"
/system logging
add action=pppoe topics=pppoe,info,!ppp,!debug

Log buffer will look similar to this one:

[admin@mainGW] > /log print where buffer=pppoe 
13:11:08 pppoe,info PPPoE connection established from 00:0C:42:04:4C:EE 

Now we can write a script to detect if new entry is added.

Code:

:global lastTime;

:global currentBuf [ :toarray [ /log find buffer=pppoe  ] ] ;
:global currentLineCount [ :len $currentBuf ] ;
:global currentTime [ :totime [/log get [ :pick $currentBuf ($currentLineCount -1) ] time   ] ];

:global message "";

:if ( $lastTime = "" ) do={ 
	:set lastTime $currentTime ; 
	:set message [/log get [ :pick $currentBuf ($currentLineCount-1) ] message];

} else={
	:if ( $lastTime < $currentTime ) do={ 
		:set lastTime $currentTime ; 
		:set message [/log get [ :pick $currentBuf ($currentLineCount-1) ] message];
	}
}

After new entry is detected, it is saved in "message" variable, which you can use later to parse log message, for example, to get pppoe clients mac address.


Allow use of ntp.org pool service for NTP

This script resolves the hostnames of two NTP servers, compares the result with the current NTP settings and changes the addresses if they're different. This script is required as RouterOS does not allow hostnames to be used in the NTP configuration. Two scripts are used. The first defines some system variables which are used in other scripts and the second does the grunt work:

# System configuration script - "GlobalVars"

:put "Setting system globals";

# System name
:global SYSname [/system identity get name];

# E-mail address to send notifications to
:global SYSsendemail "mail@my.address";

# E-mail address to send notifications from
:global SYSmyemail "routeros@my.address";

# Mail server to use
:global SYSemailserver "1.2.3.4";

# NTP pools to use (check www.pool.ntp.org)
:global SYSntpa "0.uk.pool.ntp.org";
:global SYSntpb "1.uk.pool.ntp.org";
# Check and set NTP servers - "setntppool"

# We need to use the following globals which must be defined here even
# though they are also defined in the script we call to set them.
:global SYSname;
:global SYSsendemail;
:global SYSmyemail;
:global SYSmyname;
:global SYSemailserver;
:global SYSntpa;
:global SYSntpb;

# Load the global variables with the system defaults
/system script run GlobalVars

# Resolve the two ntp pool hostnames
:local ntpipa [:resolve $SYSntpa];
:local ntpipb [:resolve $SYSntpb];

# Get the current settings
:local ntpcura [/system ntp client get primary-ntp];
:local ntpcurb [/system ntp client get secondary-ntp];

# Define a variable so we know if anything's changed.
:local changea 0;
:local changeb 0;

# Debug output
:put ("Old: " . $ntpcura . " New: " . $ntpipa);
:put ("Old: " . $ntpcurb . " New: " . $ntpipb);

# Change primary if required
:if ($ntpipa != $ntpcura) do={
    :put "Changing primary NTP";
    /system ntp client set primary-ntp="$ntpipa";
    :set changea 1;
    }

# Change secondary if required
:if ($ntpipb != $ntpcurb) do={
    :put "Changing secondary NTP";
    /system ntp client set secondary-ntp="$ntpipb";
    :set changeb 1;
    }

# If we've made a change, send an e-mail to say so.
:if (($changea = 1) || ($changeb = 1)) do={
    :put "Sending e-mail.";
    /tool e-mail send \
        to=$SYSsendemail \
        subject=($SYSname . " NTP change") \
        from=$SYSmyemail \
        server=$SYSemailserver \
        body=("Your NTP servers have just been changed:\n\nPrimary:\nOld: " . $ntpcura . "\nNew: " \
          . $ntpipa . "\n\nSecondary\nOld: " . $ntpcurb . "\nNew: " . $ntpipb);
    }

Scheduler entry:

/system scheduler add \
  comment="Check and set NTP servers" \
  disabled=no \
  interval=12h \
  name=CheckNTPServers \
  on-event=setntppool \
  policy=read,write,test \
  start-date=jan/01/1970 \
  start-time=16:00:00

Auto upgrade script


Other scripts known to work with latest v3.x

LUA Scripting examples

NOTE!

After RouterOS v4.0beta4, Lua support is removed until further notice

In v4.0beta3 Lua scripting language is integrated in console. This integration allows users to create their own functions and bypass several command line scripting limitations.
All examples below require at least basic knowledge of Lua scripting language. Good tutorials can be found here as a starting point.


Print function

As stated in Lua documentation, 'print' command is not available in RouterOS compared to standard Lua release. This example will show you how to get back 'print' command

-- ------------------------------------------------------------------------
-- Print function
-- ------------------------------------------------------------------------    
function print (...)
   local strPrintResult = ""
   if ... then
      local targs = {...}
      for i,v in ipairs(targs) do
        strPrintResult = strPrintResult .. tostring(v) .. "  "
      end
      strPrintResult = strPrintResult .. "\r\n"
      io.write(strPrintResult)
   end
end

Now you can include this custom function to other scripts and use this cool custom print function :)
You can also modify this function to write messages in RouterOS log.

Read and write large files

Many users requested ability to work with files. Now you can do it without limitations.
Create and write to file:

:global newContent "new file content\r\nanother line\r\n";
[/lua "local f=assert(io.open('/test.txt', 'w+')); f:write(newContent); f:close()" ];

Read file content to variable:

:global cnt ""
[/lua "local f=assert(io.open('/test.txt', 'r')); cnt=f:read('*all'); f:close()" ];
:put $cnt

Include custom function in another script

This example will show where to store and how to include your cool custom created functions into another scripts

  • In router's file root directory create subdirectory named 'lua'
  • On your PC create new file named customprint.lua and write this function in it.
  • Upload newly created file in router's 'lua' directory that we made in first step
  • Now you can test your custom lua function
[:lua "require 'customprint'\n print('hello from custom print function')"]

See also


[ Top | Back to Content ]