返回
perl批量查询ip归属地的方法代码
电脑技巧
2023-09-11 04:39:42
利用Perl轻松批量查询IP地址归属地
引言
在日常工作中,我们经常需要查询IP地址的归属地信息。当需要查询大量IP地址时,使用在线IP查询工具效率低下。Perl,一种功能强大的脚本语言,可帮助我们编写脚本,批量获取IP地址的归属地信息。
使用Perl批量查询IP归属地
代码示例
#!/usr/bin/perl
use strict;
use warnings;
use Geo::IP;
my $ip_file = 'ip_list.txt';
my $output_file = 'ip_info.txt';
open(my $fh_ip, '<', $ip_file) or die "Can't open $ip_file: $!";
open(my $fh_out, '>', $output_file) or die "Can't open $output_file: $!";
my $geoip = Geo::IP->new('GeoIP.dat');
while (my $ip = <$fh_ip>) {
chomp $ip;
my $country_code = $geoip->country_code_by_addr($ip);
my $country_name = $geoip->country_name_by_addr($ip);
my $region = $geoip->region_by_addr($ip);
my $city = $geoip->city_by_addr($ip);
my $latitude = $geoip->latitude_by_addr($ip);
my $longitude = $geoip->longitude_by_addr($ip);
print $fh_out "$ip|$country_code|$country_name|$region|$city|$latitude|$longitude\n";
}
close($fh_ip);
close($fh_out);
使用方法
- 将需要查询的IP地址列表保存到文本文件中,命名为
ip_list.txt
。 - 将Perl脚本保存为文本文件,命名为
ip_query.pl
。 - 在命令行中,转到Perl脚本所在目录。
- 运行命令:
perl ip_query.pl
。 - 查询结果将保存到
ip_info.txt
文件中。
注意事项
- Geo::IP模块需要安装才能使用。
- GeoIP.dat文件是Geo::IP模块使用的数据文件,需要从MaxMind网站下载。
- 查询速度取决于IP地址数量和计算机性能。
总结
Perl脚本提供了批量查询IP归属地信息的便捷方法。它比在线工具更有效率,特别是当需要查询大量IP地址时。
常见问题解答
-
如何在Windows上使用Perl脚本?
在Windows上安装Strawberry Perl并设置环境变量。
-
GeoIP.dat文件在哪里下载?
从MaxMind网站下载:https://dev.maxmind.com/geoip/geoip2/geoip2-city
-
查询结果中有哪些信息?
IP地址、国家代码、国家名称、地区、城市、经度和纬度。
-
脚本是否可以自定义输出?
可以,修改
print $fh_out
行以添加或删除信息。 -
脚本如何处理不存在信息的IP地址?
将返回空值或默认值,例如“未知”。