Saturday, March 29, 2014

Split an IP address and convert decimal to hex using Junos scripting

Here's a simple script to convert decimal to hex. There could be a reason to get the hex value of an ip address.
user@router# run op HEX
BEFORE 192.168.1.1
AFTER C0A811
script
-------------
version 1.0;
/* OP SCRIPT BY FERDINAND */
ns junos = "http://xml.juniper.net/junos/*/junos";
ns xnm = "http://xml.juniper.net/xnm/1.1/xnm";
ns jcs = "http://xml.juniper.net/junos/commit-scripts/1.0";
import "../import/junos.xsl";
match / {
    <op-script-results> {
        <output method= "text"> {
        var $ip_address = "192.168.1.1";
          expr "BEFORE " _ $ip_address _ "\n";
          var $field = jcs:split('\\.', $ip_address);
          expr "AFTER ";
            for-each ($field) {
               call dec_to_hex($value = .);
            }
        }
    }
}
template dec_to_hex ($value) {
    if ($value >= 16) {
        call dec_to_hex($value = floor($value div 16));
    }
    var $hex_digits = "0123456789ABCDEF";
    expr substring($hex_digits,($value mod 16) + 1, 1);
}

No comments:

Post a Comment