I was working on a little script that would do some logging for me from an asterisk machine. From the linux (centOS) command line, I can type:
asterisk -rx "transcoder show"
which provides the output I need to log. This output looks like this:
5/5 encoders/decoders of 120 channels are in use.
I wanted to write a line to a log file that would look like this:
YYYY-MM-DD HH-MM-SS #encoders #decoders
and then I'd log this every couple of minutes, and I'd have a history of how many channels I was using. So I wrote a little php script:
<?php
exec("asterisk -rx \"transcoder show\" | sed 's|\\([0-9]*\\)\/\\([0-9]*\\).*|\\1:\\2|'",$retval);
$time = date('Y-m-d h:i:s');
$vals = explode(":",$retval[0]);
$encoders = trim($vals[0]);
$decoders = trim($vals[1]);
$logString = "$time\t$encoders\t$decoders\n";
$fh = fopen('/root/script/trans.log','a');
fwrite($fh,$logString);
fclose($fh);
?>
Sorry, the code is a little funky there, theoretically I should have been able to output exactly what I needed from sed, but the code you see there is after I had changed it to try to address the problem you'll se below. In testing, I found the sed script worked fine from the command line; it output #encoders:#decoders as expected. But, when I ran the php script, it was writing lines like this to the log file:
2011-06-13 10:24:02 ^[[0;37;40m6 6
I can't figure out where the ^[[0;37;40m is coming from. It's a color code, I understand, to set the color for displaying the text in the shell, but is that something sed is adding, or is it coming from the original output? How do I 开发者_运维问答get rid of it? If I use an echo statement to print the variables $encoders and $decoders to the command line, there is no special color formatting, nor is there in the output from the original asterisk -rx command.
It's not that sed
is adding color codes, it's just that it is passing it through from Asterisk. What you really want to do is receive output from Asterisk that does not have those color codes to begin with.
The -n
command will strip ANSI color support: Asterisk man page
asterisk -nrx \"transcoder show\"
精彩评论