script for export leases to file

Hello!

I am trying to make this script to get a list of addresses coming from dhcp-server lease. And that I register it in a text file.

{
:local output ""
:local filename "mac_address.txt";
/ip dhcp-server lease
:foreach i in=[find] do={
    :local hname [get $i host-name]
    if ($hname = "") do={ 
        :set output ($output . ([get $i address]."\t".[get $i mac-address]."\t".[get $i comment ]) . "\n");
    } else {
        :set output ($output . ([get $i address]."\t".[get $i mac-address]."\t".[get $i host-name ]) . "\n");
    }
}
/file print file=$filename;
:delay 1;
/file set $filename contents=$output;
}

The idea that the list contains:

  • address
  • mac-address
  • If there is host-name, show me that value and if not, show me the value of the comment.

I have some problem with the code as it doesn’t work well for me. Can you help me?

BR.

Try to not forget the : before “if”…

You can not compare “” with “nil”, you must check if the variable is nil, not if is empty.

Use this version as hint

{
:local filename "mac_address.txt"
:local output   ""

/ip dhcp-server lease
:foreach i in=[find] do={
    :local hname [get $i host-name]
    :if ([:typeof $hname] = "nil") do={:set hname "Comment: $[get $i comment]"}
    :set output "$output$[get $i address]\t$[get $i mac-address]\t$hname\n"
}

/file print file=$filename
:delay 2s
/file set $filename contents=$output
}

Thank you very much Rex.
I'm learning a lot with his scripts.

BR.