The basics of reading and writing files in RouterOS

My good friend Greg was asking about how to store data to files onboard a MikroTik device so I thought I’d elaborate here with some information and examples.

Before we get started, some things to note:

  1. While you can fetch and read the contents of any file, you are limited to working with 4096 character files as this is a limitation on the amount of information that can be contained in a string variable in RouterOS at this time.
  2. When creating new files in RouterOS via terminal the extension .txt will be appended to anything that doesn’t already have .txt at the end.
  3. You can work with newlines \n\r as delimeters (which is super helpful when downloading something list of IP addresses from somewhere)

The basic commands for working with a file, using variables in place of static content or file names:
1. To create a new file

/file print file=$filename

2. To read an existing file

:set $filedata [/file get $filename contents]

3. To write to an existing file

/file set $filename contents=$newdata

4. To append to an existing file

/file set $filename contents=([get $filename contents] . $newdata)
Advertisement

2 thoughts on “The basics of reading and writing files in RouterOS

  1. Your “The basics of reading and writing files in RouterOS” assumes knowledge of the Mikrotik scripting language (which is crappy). Minor improvements would make it much better. For example “To read an existing file” also needs: ” ; :put $filedata” to actually work. PLEASE, do not follow in Mikrotik’s steps.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.