I'm trying to make a "snmpget" on an IP table and display it using a foreach. I'm already doing a ping. On my web page, only the ping result is displayed. No sign of the snmp result.
The command in shell_exec() work when I write it in a Linux shell and return "6.0.0." for each IP (yes, with the "").
<html>
<body>
<?php
ini_set('display_errors',1); error_reporting(E_ALL); //debug
function pingAddress($ip) {
$pingresult = exec("ping -c 1 $ip", $outcome, $status);
if (0 == $status) {
$status = "reachable";
} else {
$status = "unreachable!";
}
echo "<p>IP state: <strong>$ip</strong> is".$status."</p>";
}
function snmp($ip) {
$snmpresult = shell_exec('snmpget -v 2c -c public $ip 1.1.1.1.1.1.1.1.1.1.0 | awk \'{print $4}\''); //changed the OID just for confidentiality
echo $snmpresult;
}
$arr = array('192.168.1.11', '192.168.1.12', '192.168.1.2');
foreach ($arr as &$value) {
pingAddress($value);
snmp($value);
}
unset($value);
?>
</body>
</html>
The actual result on my web page is this:
IP state: 192.168.1.11 is reachable
IP state: 192.168.1.12 is reachable
IP state: 192.168.1.2 is reachable
And I don't see the snmp() result. Any idea? I'm far from being a real PHP developer so if you have any other recommendations, don't hesitate. Thank you.
You used single quotes to build the command string, so $ip
is not interpolated.
Furthermore, you did not provide yourself with any means to see error messages coming out of the snmpget
command, otherwise this might have been more obvious.
A quick fix would be something like:
function snmp($ip)
{
$oid = "1.1.1.1.1.1.1.1.1.1.0";
$cmd = "snmpget -v 2c -c public $ip $oid | awk '{print \$4}'";
$snmpresult = shell_exec($cmd);
echo $snmpresult;
}
I've split the string into variables so we can read it all better, plus now you can print $cmd
for debugging (which also would have revealed your bug).
And I recommend returning the result rather than echo
ing it directly, so that the calling scope can do something else with it if it likes.
For better diagnostics, and just better code overall, consider switching to the built-in snmpget
function; direct shell commands are almost always a hack.
You should also bear in mind that, for security reasons, a webserver is often run in a constrained context, preventing certain operations from being performed. If snmpget
doesn't work at all, you could look to see whether something like SELinux is disallowing it.