2015-02-24 87 views
0

我想分析rsyslog日志。为此,我将所有日志发送给socat,然后将它们发送到Unix域套接字。该套接字是通过perl脚本创建的,该脚本正在该套接字上侦听以解析日志。无法使用socat连接到套接字

我的bash脚本到rsyslog现在正在发送的所有日志

if [ ! `pidof -x log_parser.pl` ] 
    then 
./log_parser.pl & 1>&1 
fi 

if [ -S /tmp/sock ] 
then 
/usr/bin/socat -t0 -T0 - UNIX-CONNECT:/tmp/sock 2>> /var/log/socat.log 
fi 

/tmp/sock使用perl脚本log_parser.pl这是

use IO::Socket::UNIX; 

sub socket_create { 
    $socket_path = '/tmp/sock'; 
    unlink($socket_path); 

    $listner = IO::Socket::UNIX->new(
     Type => SOCK_STREAM, 
     Local => $socket_path, 
     Listen => SOMAXCONN, 
     Blocking => 0, 
    ) 
     or die("Can't create server socket: $!\n"); 

    $socket = $listner->accept() 
     or die("Can't accept connection: $!\n"); 
    } 

    socket_create(); 
    while(1) { 

    chomp($line=<$socket>); 
    print "$line\n"; 
    } 

有这个错误我是从socat是

越来越创建
2015/02/24 11:58:01 socat[4608] E connect(3, AF=1 "/tmp/sock", 11): Connection refused 

我不是插座的冠军所以ia米不能理解这是什么。请帮忙。提前致谢。

主要问题是,当我杀了我的perl脚本,然后bash脚本是想要再次调用它并启动它。 究竟发生了什么是sript开始,但socat不是开始,而是它给这个错误,永远不会开始。

+0

你正在定义一个子程序,但是你在哪里调用它? – reinierpost 2015-02-24 09:01:21

回答

1

如果我在尝试使用socat之前没有运行perl程序,我可以复制你的错误。下面是我的什么作品:

1)my_prog.pl:

use strict; 
use warnings; 
use 5.016; 
use Data::Dumper; 
use IO::Socket::UNIX; 

my $socket_path = '/tmp/sock'; 
unlink $socket_path; 

my $socket = IO::Socket::UNIX->new(
    Local => $socket_path, 
    Type => SOCK_STREAM, 
    Listen => SOMAXCONN, 
) or die "Couldn't create socket: $!"; 

say "Connected to $socket_path..."; 
my $CONN = $socket->accept() 
    or die "Whoops! Failed to open a connection: $!"; 

{ 
    local $/ = undef; #local -> restore previous value when the enclosing scope, delimited by the braces, is exited. 
         #Setting $/ to undef puts file reads in 'slurp mode' => whole file is considered one line. 
    my $file = <$CONN>; #Read one line. 
    print $file; 
}` 

2)$ perl my_prog.pl

3)socat -u -v GOPEN:./data.txt UNIX-CONNECT:/tmp/sock

-u和-v选项是没有必要的:

-u   Uses unidirectional mode. The first address is only used for 
       reading, and the second address is only used for writing (exam- 
       ple). 


-v   Writes the transferred data not only to their target streams, 
       but also to stderr. The output format is text with some conver- 
       sions for readability, and prefixed with "> " or "< " indicating 
       flow directions. 

4)你也可以这样做:

cat data.txt | socat STDIN UNIX-CONNECT:/tmp/sock 

管理标准输出cat命令socat,然后列出STDIN作为socat的文件之一。

回应评论:

这个bash脚本为我的作品:

#!/usr/bin/env bash 

echo 'bash script' 

../pperl_programs/my_prog.pl & 
sleep 1s 

socat GOPEN:./data.txt UNIX-CONNECT:/tmp/sock 

它看起来像Perl脚本没有足够的时间来建立套接字之前socat试图传输数据。

+0

是的,我知道这个错误出现在我试图在程序之前运行socat的时候。在我的bash脚本中,你可以看到如果perl程序没有运行,它会尝试运行它,然后去找socat。所以理想情况下,这个错误不应该到来,但这仍然会到来,我不知道为什么它会到来。 – shivams 2015-02-24 10:31:48

+0

@srtfmx,请参阅我的回答结束回复。 – 7stud 2015-02-24 11:07:19

+0

谢谢。它适合我。一段时间以来,我一直在盯着它,这就是这个睡眠问题。非常感谢 :) – shivams 2015-02-24 11:28:28

相关问题