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
parameters:%s
type:script_output
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
/*
Copyright (C) 2014 Deciso B.V.
Copyright (C) 2014-2016 Deciso B.V.
Copyright (C) 2006 Fernando Lamos
All rights reserved.
......@@ -30,211 +30,132 @@
include('guiconfig.inc');
if (isset($_REQUEST['isAjax'])) {
$netstat = "/usr/bin/netstat -rW";
if (isset($_REQUEST['IPv6'])) {
$netstat .= " -f inet6";
echo "IPv6\n";
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (empty($_POST['resolve'])) {
$resolve = '-n';
} else {
$netstat .= " -f inet";
echo "IPv4\n";
$resolve = '';
}
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));
echo configd_run("system routes list {$resolve} json");
exit;
}
include('head.inc');
?>
<body>
<?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">
//<![CDATA[
function update_routes(section) {
var url = "diag_routes.php";
var limit = jQuery('#limit option:selected').text();
var filter = jQuery('#filter').val();
var params = "isAjax=true&limit=" + limit + "&filter=" + filter;
if (jQuery('#resolve').is(':checked'))
params += "&resolve=true";
if (section == "IPv6")
params += "&IPv6=true";
var myAjax = $.ajax(
{
url:url,
type: 'post',
data: params,
success: update_routes_callback
});
}
function update_routes_callback(data, textStatus, transport) {
// First line contains section
var responseTextArr = transport.responseText.split("\n");
var section = responseTextArr.shift();
var tbody = '';
var field = '';
var elements = 8;
var tr_class = '';
var thead = '';
for (var i = 0; i < responseTextArr.length; i++) {
if (responseTextArr[i] == "")
continue;
var tmp = '';
if (i == 0) {
tr_class = 'listhdrr';
tmp += '<tr class="sortableHeaderRowIdentifier">' + "\n";
$( document ).ready(function() {
var gridopt = {
ajax: false,
selection: false,
multiSelect: false
};
$("#grid-routes").bootgrid('destroy');
$("#grid-routes").bootgrid(gridopt);
// update routes
$("#update").click(function() {
$("#loading").show();
if ($("#resolve").prop("checked")) {
resolve = "yes";
} else {
tr_class = 'listlr';
tmp += '<tr>' + "\n";
}
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++;
resolve = "";
}
// 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);
$.post(window.location, {resolve: resolve}, function(data) {
$("#grid-routes").bootgrid('destroy');
var html = [];
$.each(data, function (key, value) {
var fields = ["proto", "destination", "gateway", "flags", "use", "mtu", "netif", "expire"];
tr_str = '<tr>';
for (var i = 0; i < fields.length; i++) {
if (value[fields[i]] != null) {
tr_str += '<td>' + value[fields[i]] + '</td>';
} else {
tr_str += '<td></td>';
}
function update_all_routes() {
update_routes("IPv4");
update_routes("IPv6");
}
tr_str += '</tr>';
html.push(tr_str);
});
$("#grid-routes > tbody").html(html.join(''));
$("#grid-routes").bootgrid(gridopt);
$("#loading").hide();
}, "json");
});
jQuery(document).ready(function(){setTimeout('update_all_routes()', 3000);});
//]]>
// initial load
$("#update").click();
});
</script>
<section class="page-content-main">
<div class="container-fluid">
<div class="row">
<section class="col-xs-12">
<?php if (isset($input_errors) && count($input_errors) > 0) print_input_errors($input_errors); ?>
<div class="tab-content content-box col-xs-12">
<form action="<?=$_SERVER['REQUEST_URI'];?>" method="post" name="iform" id="iform">
<div class="table-responsive">
<table class="table table-striped __nomb">
<table class="table table-striped">
<thead>
<tr>
<td colspan="2" valign="top" class="listtopic"><strong><?= gettext('Routing tables') ?></strong></td>
</tr>
<tr>
<td><?=gettext("Name resolution");?></td>
<td><input type="checkbox" class="formfld" id="resolve" name="resolve" value="yes" <?php if ($_POST['resolve'] == 'yes') echo "checked=\"checked\""; ?> />&nbsp;<?=gettext("Enable");?>
<p class="text-muted"><em><small><?=gettext("Enable this to attempt to resolve names when displaying the tables.");?><br/>
<?= 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>
<th><?=gettext("Name resolution");?></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td><?=gettext("Number of rows");?></td>
<td><select id="limit" name="limit" class="form-control">
<?php
foreach (array("10", "50", "100", "200", "500", "1000", gettext("all")) as $item) {
echo "<option value=\"{$item}\" " . ($item == "100" ? "selected=\"selected\"" : "") . ">{$item}</option>\n";
}
?>
</select>
<p class="text-muted"><em><small><?=gettext("Select how many rows to display.");?></small></em></p>
<td>
<input type="checkbox" class="formfld" id="resolve" name="resolve" value="yes">
</td>
</tr>
<tr>
<td><?=gettext("Filter expression");?></td>
<td>
<input type="text" class="form-control search" name="filter" id="filter" />
<p class="text-muted"><em><small><?=gettext("Use a regular expression to filter IP address or hostnames.");?></small></em></p>
<p class="text-muted">
<em>
<small>
<?=gettext("Enable this to attempt to resolve names when displaying the tables.");?><br/>
<?= 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>
</tr>
<tr>
<td>&nbsp;</td>
<td>
<input type="button" class="btn btn-primary" name="update" onclick="update_all_routes();" value="<?=gettext("Update"); ?>" />
<input type="button" id="update" class="btn btn-primary" value="<?=gettext("Update"); ?>" />
</td>
</tr>
</table>
</div>
</form>
</div>
</section>
<section class="col-xs-12">
<div class="content-box">
<header class="content-box-head container-fluid">
<h3>IPv4</h3>
</header>
<table class="table table-striped table-sort sortable __nomb" id="IPv4" summary="IPv4 routes">
<thead></thead>
<tbody>
<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>
<div class="table-responsive">
<table id="grid-routes" class="table table-condensed table-hover table-striped table-responsive">
<thead>
<tr>
<th data-column-id="proto" data-type="string" ><?=gettext("Proto");?></th>
<th data-column-id="destination" data-type="string" data-identifier="true"><?=gettext("Destination");?></th>
<th data-column-id="gateway" data-type="string"><?=gettext("Gateway");?></th>
<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>
<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>
<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>
<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>
<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>
</tr>
</thead>
<tbody>
<tr><td class="listhdrr"><?=gettext("Gathering data, please wait...");?></td></tr>
</tbody>
<tfoot>
<tr>
<td colspan="6" id="loading"><?=gettext("loading....");?></td>
</tr>
</tfoot>
</table>
</div>
</div>
</section>
</div>
</div>
</section>
<?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