Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I have to receive snmptraps in php script, so what i've done is:

snmptrapd.conf

traphandle 1.3.6.1.4.1.3.1.1 /usr/home/user/trap/l.php

l.php

#!/usr/local/bin/php
<?php
$flow = fopen("php://stderr","r");
while(!feof($flow)){
    file_put_contents("out",fread($flow,1024)."\n", FILE_APPEND);
}
?>

then i start snmptrapd like this:

snmptrapd -Le -f

and generated traps like this:

snmptrap -v 1 -c public localhost '' localhost 6 1 ''

snmptrapd gives me such output

2012-01-16 14:38:49 127.0.0.1(via UDP: [127.0.0.1]:11478->[0.0.0.0]:0) TRAP, SNMP v1, community public
        SNMPv2-SMI::enterprises.3.1.1 Enterprise Specific Trap (1) Uptime: 70 days, 1:03:57.00

so it seems working... but the problem is that l.php is not executed, or there's nothing in stderr - i can't realize.

please, where's my mistake?

share|improve this question
add comment

1 Answer 1

up vote 1 down vote accepted

php://stderr is not a stream that can be read from. It is a pipe to the STDERR for the PHP process itself, which is write-only.

You need to access the data via STDIN. Rather than using the php:// wrapper to access the STDIO streams, which is known to be buggy (see the manual) you should use the special constants STDOUT, STDERR and STDIN. So for example, I might write your PHP script like this:

#!/usr/local/bin/php
<?php

  // The file we will be writing to. It's best to specify a full path, to avoid
  // any confusion over the current working directory
  $outFile = '/var/myuser/snmp.out';

  // First, we'll open our outfile...
  if (!$ofp = fopen($outFile, 'a')) exit("Oh No! I couldn't open my out file!");

  // ...and write the current timestamp to it, so we are certain the script was
  // invoked. You can remove this if you want, once you are sure it is working
  fwrite($ofp, "Process started at ".date('Y-m-d H:i:s')."\n");

  // Next we'll write all the trap data to the file
  // We could use stream_copy_to_stream() for this, but I don't know if it is
  // available on your server so I won't do it here
  fwrite($ofp,"Data:\n");
  while (!feof(STDIN)) {
    fwrite($ofp, fread(STDIN, 1024)."\n");
  }
  fwrite($ofp,"End Data\n");

  // We don't actually need a closing PHP tag and in many cases it is better
  // to omit it, to avoid unexpected whitespace being output.
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.