juniper-config-to-set/juniper-config-to-set.php

86 lines
2.4 KiB
PHP
Raw Normal View History

2016-11-23 22:20:47 +01:00
#!/usr/bin/php
<?php
2018-03-26 03:09:59 +02:00
/******************************************************************************************************
2016-11-23 22:20:47 +01:00
*
* Written by Tim Price 24/11/2016
*
* The purpose of this script is to take a juniper config and convert it to set commands.
2018-03-26 03:09:59 +02:00
* There was a business need to audit thbe correctness of Juniper configs and the process of logging
* into each Juniper device and dumping the configs in set format was too burdensome on both the Juniper
* devices in question but also extended the execution time of the audit scripts by some minutes.
2016-11-23 22:20:47 +01:00
*
* Usage example: `cat juniper-config.txt | juniper-config-to-set.php`
*
2018-03-26 03:09:59 +02:00
******************************************************************************************************/
2016-11-23 22:20:47 +01:00
function endswith($string, $test) {
$strlen = strlen($string);
$testlen = strlen($test);
if ($testlen > $strlen) return false;
return substr_compare($string, $test, $strlen - $testlen, $testlen) === 0;
}
function addtotree($tree,$word) {
array_push($tree,$word);
return $tree;
}
function removewordfromtree($tree) {
array_pop($tree);
return $tree;
}
function printtree($tree) {
return implode(" ",$tree);
}
$tree=array();
while($line = fgets(STDIN)){
// Skip any commented lines
if(strpos($line,'#')===0) {
continue;
}
// Trim white space from the line
$line=trim($line);
2018-03-26 03:09:59 +02:00
// Trim inline comments from the line
if(preg_match('/; ##/',$line)==1) {
list($line,$comment)=preg_split('/; ##/',$line);
$line .= ";";
}
2016-11-23 22:20:47 +01:00
// What remains is a series of tests to see what the line ends with.
2018-03-26 03:09:59 +02:00
// This test matches a ';' character which means its a leaf and we can output the whole line to STDOUT
2016-11-23 22:20:47 +01:00
if(endswith($line,';')) {
// Trim the semi-colon from the end of the line, we don't need that.
$line = rtrim($line,';');
2018-03-26 03:09:59 +02:00
//Test to see if the tree is empty, if it is then we'll just print the leaf and not the tree
//to avoid excess white spaces
2016-11-23 22:20:47 +01:00
if(count($tree)==0) {
echo "set $line\n";
} else {
echo "set " . printtree($tree) . " $line\n";
}
}
2018-03-26 03:09:59 +02:00
// This test matches a '{' character on the end of the line and means we need to add a branch to the tree
2016-11-23 22:20:47 +01:00
if(endswith($line,'{')) {
$line = rtrim($line,' {');
$tree=addtotree($tree,$line);
}
2018-03-26 03:09:59 +02:00
// This test matches a '}' character on the end of the line and means we need to remove the last branch that we added to the tree
2016-11-23 22:20:47 +01:00
if(endswith($line,'}')) {
$tree=removewordfromtree($tree);
}
}
?>