Jump to content

Regex to match log entry


jmurch

Recommended Posts

 

I am trying to come up with a regex that will match this log entry:

 

[Aug 04 14:22:02]      err: bad or missing CDL header. refused connection from 98.165.54.217:54335 [l:980]

 

Where timestamp and ip address will obviousley be different each time.  I dont care about anything after the colon in the ip address.

 

TIA, Jeff

 

Link to comment
https://forums.phpfreaks.com/topic/243854-regex-to-match-log-entry/
Share on other sites

More than one line would be helpful, but

 

$expression = '/\[([^]]+)\] +([^\r\n]+)/';

 


\[([^]]+)] +([^\r\n]+)

Match the character “[” literally «\[»
Match the regular expression below and capture its match into backreference number 1 «([^]]+)»
   Match any character that is NOT a “]” «[^]]+»
      Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the character “]” literally «]»
Match the character “ ” literally « +»
   Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the regular expression below and capture its match into backreference number 2 «([^\r\n]+)»
   Match a single character NOT present in the list below «[^\r\n]+»
      Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
      A carriage return character «\r»
      A line feed character «\n»

 

More missing details:

 

 

This rule matches this ssh log entry:

Log entry: Aug  4 20:59:16 socketserver sshd[21442]: Failed password for root from 98.165.54.217 port 56595 ssh2

Rule: ^%(__prefix_line)sFailed (?:password|publickey) for .* from <HOST>(?: port \d*)?(?: ssh\d*)?$

(Note that this is for use in the iptables module fail2ban. The entry __prefix_line comes from another config file but I figured that leaving it out would be more confusing)

 

This rule does not match this log entry:

Log entry: [Aug 04 14:22:02]      err: bad or missing CDL header. refused connection from 98.165.54.217:54335 [l:980]

Rule: /bad or missing CDL header\. refused connection from ([0-9.:]+)/

 

Thanks!

I'm not familiar with fail2ban, but I know my RegEx works.

 

<?php


$sb = '[Aug 04 14:22:02]      err: bad or missing CDL header. refused connection from 98.165.54.217:54335 [l:980]';
$ex = '/bad or missing CDL header\. refused connection from ([0-9.:]+)/';
preg_match_all( $ex, $sb, $match );

print_r( $match );

?>

 

Output

 

Array
(
    [0] => Array
        (
            [0] => bad or missing CDL header. refused connection from 98.165.54.217:54335
        )

    [1] => Array
        (
            [0] => 98.165.54.217:54335
        )

)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.