Commit 6e7f1432 authored by Ad Schellevis's avatar Ad Schellevis

refactor diag_routes.php

parent 0ec32edf
#!/usr/local/bin/python2.7
"""
Copyright (c) 2016 Ad Schellevis
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
--------------------------------------------------------------------------------------
returns the system routing table
"""
import tempfile
import subprocess
import os
import sys
import ujson
if __name__ == '__main__':
result = []
fieldnames=[]
with tempfile.NamedTemporaryFile() as output_stream:
if '-n' in sys.argv:
resolv = '-n'
else:
resolv = ''
subprocess.call(['/usr/bin/netstat', '-rW', resolv], stdout=output_stream, stderr=open(os.devnull, 'wb'))
output_stream.seek(0)
current_proto = ""
for line in output_stream.read().strip().split('\n'):
fields = line.split()
if len(fields) == 0:
continue
elif len(fields) == 1 and fields[0] == 'Internet:':
current_proto = 'ipv4'
elif len(fields) == 1 and fields[0] == 'Internet6:':
current_proto = 'ipv6'
elif len(fields) > 2 and fields[0] == 'Destination' and fields[1] == 'Gateway':
fieldnames = map(lambda x : x.lower(), fields)
elif len(fields) > 2:
record = {'proto': current_proto}
for fieldid in range(len(fields)):
if len(fieldnames) > fieldid:
record[fieldnames[fieldid]] = fields[fieldid]
# space out missing fields
for fieldname in fieldnames:
if fieldname not in record:
record[fieldname] = ""
result.append(record)
# handle command line argument (type selection)
if len(sys.argv) > 1 and 'json' in sys.argv:
print(ujson.dumps(result))
else:
# output plain
print ('\t\t'.join(fieldnames))
frmt = "%(proto)s\t"
for fieldname in fieldnames:
frmt = frmt + "%("+fieldname+")s\t"
for record in result:
print (frmt%record)
...@@ -3,3 +3,10 @@ command:/usr/local/opnsense/scripts/systemhealth/activity.py ...@@ -3,3 +3,10 @@ command:/usr/local/opnsense/scripts/systemhealth/activity.py
parameters:%s parameters:%s
type:script_output type:script_output
message:show system activity message:show system activity
[routes.list]
command:/usr/local/opnsense/scripts/routes/show_routes.py
parameters:%s %s
type:script_output
message:show system routing table
<?php <?php
/* /*
Copyright (C) 2014 Deciso B.V. Copyright (C) 2014-2016 Deciso B.V.
Copyright (C) 2006 Fernando Lamos Copyright (C) 2006 Fernando Lamos
All rights reserved. All rights reserved.
Redistribution and use in source and binary forms, with or without Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met: modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, 1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer. this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright 2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution. documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE. POSSIBILITY OF SUCH DAMAGE.
*/ */
include('guiconfig.inc'); include('guiconfig.inc');
if (isset($_REQUEST['isAjax'])) { if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$netstat = "/usr/bin/netstat -rW"; if (empty($_POST['resolve'])) {
if (isset($_REQUEST['IPv6'])) { $resolve = '-n';
$netstat .= " -f inet6"; } else {
echo "IPv6\n"; $resolve = '';
} else { }
$netstat .= " -f inet"; echo configd_run("system routes list {$resolve} json");
echo "IPv4\n"; exit;
}
if (!isset($_REQUEST['resolve']))
$netstat .= " -n";
if (!empty($_REQUEST['filter']))
$netstat .= " | /usr/bin/sed -e '1,3d; 5,\$ { /" . escapeshellarg(htmlspecialchars($_REQUEST['filter'])) . "/!d; };'";
else
$netstat .= " | /usr/bin/sed -e '1,3d'";
if (is_numeric($_REQUEST['limit']) && $_REQUEST['limit'] > 0)
$netstat .= " | /usr/bin/head -n {$_REQUEST['limit']}";
echo htmlspecialchars_decode(shell_exec($netstat));
exit;
} }
include('head.inc'); include('head.inc');
?> ?>
<body> <body>
<?php include("fbegin.inc"); ?> <?php include("fbegin.inc"); ?>
<link rel="stylesheet" type="text/css" href="/ui/css/jquery.bootgrid.css"/>
<script type="text/javascript" src="/ui/js/jquery.bootgrid.js"></script>
<script type="text/javascript"> <script type="text/javascript">
//<![CDATA[ $( document ).ready(function() {
var gridopt = {
function update_routes(section) { ajax: false,
var url = "diag_routes.php"; selection: false,
var limit = jQuery('#limit option:selected').text(); multiSelect: false
var filter = jQuery('#filter').val(); };
var params = "isAjax=true&limit=" + limit + "&filter=" + filter; $("#grid-routes").bootgrid('destroy');
if (jQuery('#resolve').is(':checked')) $("#grid-routes").bootgrid(gridopt);
params += "&resolve=true";
if (section == "IPv6") // update routes
params += "&IPv6=true"; $("#update").click(function() {
var myAjax = $.ajax( $("#loading").show();
if ($("#resolve").prop("checked")) {
{ resolve = "yes";
url:url, } else {
type: 'post', resolve = "";
data: params, }
success: update_routes_callback $.post(window.location, {resolve: resolve}, function(data) {
}); $("#grid-routes").bootgrid('destroy');
} var html = [];
$.each(data, function (key, value) {
function update_routes_callback(data, textStatus, transport) { var fields = ["proto", "destination", "gateway", "flags", "use", "mtu", "netif", "expire"];
// First line contains section tr_str = '<tr>';
var responseTextArr = transport.responseText.split("\n"); for (var i = 0; i < fields.length; i++) {
var section = responseTextArr.shift(); if (value[fields[i]] != null) {
var tbody = ''; tr_str += '<td>' + value[fields[i]] + '</td>';
var field = ''; } else {
var elements = 8; tr_str += '<td></td>';
var tr_class = ''; }
}
var thead = ''; tr_str += '</tr>';
for (var i = 0; i < responseTextArr.length; i++) { html.push(tr_str);
if (responseTextArr[i] == "") });
continue; $("#grid-routes > tbody").html(html.join(''));
var tmp = ''; $("#grid-routes").bootgrid(gridopt);
if (i == 0) { $("#loading").hide();
tr_class = 'listhdrr'; }, "json");
tmp += '<tr class="sortableHeaderRowIdentifier">' + "\n"; });
} else {
tr_class = 'listlr'; // initial load
tmp += '<tr>' + "\n"; $("#update").click();
} });
var j = 0;
var entry = responseTextArr[i].split(" ");
for (var k = 0; k < entry.length; k++) {
if (entry[k] == "")
continue;
if (i == 0 && j == (elements - 1))
tr_class = 'listhdr';
tmp += '<td class="' + tr_class + '">' + entry[k] + '<\/td>' + "\n";
if (i > 0)
tr_class = 'listr';
j++;
}
// The 'Expire' field might be blank
if (j == (elements - 2)) {
tmp += '<td class="listr">&nbsp;<\/td>' + "\n";
}
tmp += '<\/tr>' + "\n";
if (i == 0)
thead += tmp;
else
tbody += tmp;
}
jQuery('#' + section + ' > thead').html(thead);
jQuery('#' + section + ' > tbody').html(tbody);
}
function update_all_routes() {
update_routes("IPv4");
update_routes("IPv6");
}
jQuery(document).ready(function(){setTimeout('update_all_routes()', 3000);});
//]]>
</script> </script>
<section class="page-content-main"> <section class="page-content-main">
<div class="container-fluid"> <div class="container-fluid">
<div class="row"> <div class="row">
<section class="col-xs-12">
<section class="col-xs-12"> <div class="tab-content content-box col-xs-12">
<div class="table-responsive">
<?php if (isset($input_errors) && count($input_errors) > 0) print_input_errors($input_errors); ?> <table class="table table-striped">
<thead>
<div class="tab-content content-box col-xs-12"> <tr>
<form action="<?=$_SERVER['REQUEST_URI'];?>" method="post" name="iform" id="iform"> <th><?=gettext("Name resolution");?></th>
<div class="table-responsive"> <th></th>
<table class="table table-striped __nomb"> <th></th>
<tr> </tr>
<td colspan="2" valign="top" class="listtopic"><strong><?= gettext('Routing tables') ?></strong></td> </thead>
</tr> <tbody>
<tr> <tr>
<td><?=gettext("Name resolution");?></td> <td>
<td><input type="checkbox" class="formfld" id="resolve" name="resolve" value="yes" <?php if ($_POST['resolve'] == 'yes') echo "checked=\"checked\""; ?> />&nbsp;<?=gettext("Enable");?> <input type="checkbox" class="formfld" id="resolve" name="resolve" value="yes">
<p class="text-muted"><em><small><?=gettext("Enable this to attempt to resolve names when displaying the tables.");?><br/> </td>
<?= gettext('Note:') ?> <?=gettext("By enabling name resolution, the query should take a bit longer. You can stop it at any time by clicking the Stop button in your browser.");?></small></em></p> <td>
</td> <p class="text-muted">
</tr> <em>
<tr> <small>
<td><?=gettext("Number of rows");?></td> <?=gettext("Enable this to attempt to resolve names when displaying the tables.");?><br/>
<td><select id="limit" name="limit" class="form-control"> <?= gettext('Note:') ?> <?=gettext("By enabling name resolution, the query should take a bit longer. You can stop it at any time by clicking the Stop button in your browser.");?>
<?php </small>
foreach (array("10", "50", "100", "200", "500", "1000", gettext("all")) as $item) { </em>
echo "<option value=\"{$item}\" " . ($item == "100" ? "selected=\"selected\"" : "") . ">{$item}</option>\n"; </p>
} </td>
?> <td>
</select> <input type="button" id="update" class="btn btn-primary" value="<?=gettext("Update"); ?>" />
<p class="text-muted"><em><small><?=gettext("Select how many rows to display.");?></small></em></p> </td>
</td> </tr>
</tr> </tbody>
<tr> </table>
<td><?=gettext("Filter expression");?></td> </div>
<td> <div class="table-responsive">
<input type="text" class="form-control search" name="filter" id="filter" /> <table id="grid-routes" class="table table-condensed table-hover table-striped table-responsive">
<p class="text-muted"><em><small><?=gettext("Use a regular expression to filter IP address or hostnames.");?></small></em></p> <thead>
</td> <tr>
</tr> <th data-column-id="proto" data-type="string" ><?=gettext("Proto");?></th>
<tr> <th data-column-id="destination" data-type="string" data-identifier="true"><?=gettext("Destination");?></th>
<td>&nbsp;</td> <th data-column-id="gateway" data-type="string"><?=gettext("Gateway");?></th>
<td> <th data-column-id="flags" data-type="string" data-css-class="hidden-xs hidden-sm" data-header-css-class="hidden-xs hidden-sm"><?=gettext("Flags");?></th>
<input type="button" class="btn btn-primary" name="update" onclick="update_all_routes();" value="<?=gettext("Update"); ?>" /> <th data-column-id="use" data-type="string" data-css-class="hidden-xs hidden-sm" data-header-css-class="hidden-xs hidden-sm"><?=gettext("Use");?></th>
</td> <th data-column-id="mtu" data-type="string" data-css-class="hidden-xs hidden-sm" data-header-css-class="hidden-xs hidden-sm"><?=gettext("MTU");?></th>
</tr> <th data-column-id="netif" data-type="string" data-css-class="hidden-xs hidden-sm" data-header-css-class="hidden-xs hidden-sm"><?=gettext("Netif");?></th>
</table> <th data-column-id="expire" data-type="string" data-css-class="hidden-xs hidden-sm" data-header-css-class="hidden-xs hidden-sm"><?=gettext("Expire");?></th>
</div> </tr>
</form> </thead>
</div> <tbody>
</section> </tbody>
<tfoot>
<section class="col-xs-12"> <tr>
<td colspan="6" id="loading"><?=gettext("loading....");?></td>
<div class="content-box"> </tr>
</tfoot>
<header class="content-box-head container-fluid"> </table>
<h3>IPv4</h3> </div>
</header> </div>
<table class="table table-striped table-sort sortable __nomb" id="IPv4" summary="IPv4 routes"> </section>
<thead></thead> </div>
<tbody> </div>
<tr><td class="listhdrr"><?=gettext("Gathering data, please wait...");?></td></tr>
</tbody>
</table>
</div>
</section>
<section class="col-xs-12">
<div class="content-box">
<header class="content-box-head container-fluid">
<h3>IPv6</h3>
</header>
<table class="table table-striped table-sort sortable __nomb" id="IPv6" summary="IPv6 routes">
<thead></thead>
<tbody>
<tr><td class="listhdrr"><?=gettext("Gathering data, please wait...");?></td></tr>
</tbody>
</table>
</div>
</section>
</div>
</div>
</section> </section>
<?php <?php
include('foot.inc'); include('foot.inc');?>
?>
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment