Community discussions

MikroTik App
 
dssmiktik
Forum Veteran
Forum Veteran
Topic Author
Posts: 732
Joined: Fri Aug 17, 2007 8:42 am

[CONTRIB] Restore Global Variables on Startup

Mon Jul 06, 2009 10:16 am

This is a script to restore global variables on startup of RouterOS. I'm posting here so others may use/improve it. The main use for me is to prevent ChangeIP script from automatically updating each reboot (as it uses global vars to tell if IP addr changes), and anytime I don't want to loose a global variable on startup (ex BadIPs). I name this script RestoreGlobalVars and have it Scheduled to run every 15 secs.

Anyway, hope this is useful for anyone.

# this script restores global variables after a startup or reboot

:global RestoreGlobalVars

# if global var isn't set (aka we've rebooted or just started), run restore script
:if ([:len $RestoreGlobalVars] = 0) do={
# if restore script exists, run it
  :if ([:len [/system script find name=GlobalVars]] > 0) do={
    :log warning "Running GlobalVars script"
    /system script run GlobalVars    
  } else={
    :log warning "No GlobalVars script found.  Not running."
  }
  :global RestoreGlobalVars 1
} else={

# create new source for script
	:local globalvars
	:set globalvars "# Begin of global variables definition\n"
	:foreach var in=[/system script environment find] do={
# do not include RestoreGlobalVars as this is our controlling variable
		:if ([/system script environment get $var name] != "RestoreGlobalVars") do={
# only accept name and values that are not blank
			:if ([:len [/system script environment get $var name]] > 0) do={
				:if ([:len [/system script environment get $var value]] > 0) do={
					:set globalvars ($globalvars . ":global " . [/system script environment get $var name] . "  \"" . [/system script environment get $var value] . "\"\n")
				}
			}
		}
	}
	:set globalvars ($globalvars . "# End of global variables definition")
	
	:if ([:len $globalvars] > 0) do={
		:if ([:len [/system script find name=GlobalVars]] > 0) do={
# if new source doesn't match existing source, write new source to script
				:if ([/system script get GlobalVars source] != $globalvars) do={
					:log warning "GlobalVars source changed"
					/system script set GlobalVars source="$globalvars"
				}
		} else={
			/system script add name="GlobalVars" source="$globalvars"
		}
	}
}