从perl中的字符串解析出IP地址和DNS服务器

时间:2013-08-02 04:13:23

标签: perl parsing header ip

有没有办法perl可以接收电子邮件收到标题信息并从字符串中取出服务器和IP地址?这是一个例子:

Received: from example.web.site.net (example.web.site.net [1.1.1.1])  (using example     filler text (256/256 bits))  (No client certificate requested)  by example.example.com     (Postfix) with ESMTPS id 123456

最终发送到SQL数据库时,这两个项目需要转到各自的字段。

这也是使用qpsmtp插件。

2 个答案:

答案 0 :(得分:0)

试试正则表达式:

my $str = "Received: from example.web.site.net (example.web.site.net [1.1.1.1])  (using example     filler text (256/256 bits))  (No client certificate requested)  by example.example.com     (Postfix) with ESMTPS id 123456";    
$str =~ s/[^\(]*\(([^ ]+) \[([^\]]+)\]\).*/$1|$2/; 

my @parts = split /\|/, $str;

$parts[0]有服务器,$parts[1]有IP

答案 1 :(得分:0)

如果我理解正确的话:

  • example.web.site.net 是服务器名称;和
  • 1.1.1.1 是IP

最好的方法是使用Regex捕获。 Perl捕获与括号中包含的某个表达式匹配的任何字符串。当您尝试将字符串与某个正则表达式匹配时,它会返回一个数组(m //)。

这是我的代码:

use strict;
use warnings;

my $str = "Received: from example.web.site.net (example.web.site.net [1.1.1.1])  (using example     filler text (256/256 bits))  (No client certificate requested)  by example.example.com     (Postfix) with ESMTPS id 123456";

my ($server, $ip) = $str =~ m/\((.+)\[(.+?)\]\)/sg;
chop($server);

print "'$server' - '$ip'";

我使用正则表达式来匹配字符串“(example.web.site.net [1.1.1.1])”的这一部分,我只是附上了我想要的那部分字符串用括号捕捉。因为我想获得2个字符串,因此赋值:

my ($server, $ip) = $str =~ m/\((.+)\[(.+?)\]\)/sg;

希望有所帮助!