dehio3’s diary

仕事、生活、趣味のメモ

ibwww-perl レスポンス(response)オブジェクトの復帰コードがバージョンによって違った

事象

URLの存在チェックする処理にて、バージョンが変わるとHTTPステータスコード200から403に変わってしまった。

チェックスクリプト

#!/usr/bin/perl

use strict;
use warnings;
use LWP::UserAgent;

my $ua = LWP::UserAgent->new;
$ua->agent('Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)');
$ua->timeout(5);

my $url = '<チェックしたいURL>';

my $req = HTTP::Request->new(GET => $url);
my $res = $ua->request($req);

#print $res->as_string();

print $res->status_line . "\n";
print $res->code . "\n";

$ perl http_status.pl
200 OK
200

$ perl http_status.pl
403 Forbidden
403

環境

perl

$ perl -version

This is perl, v5.8.5 built for x86_64-linux-thread-multi

Copyright 1987-2004, Larry Wall

Perl may be copied only under the terms of either the Artistic License or the
GNU General Public License, which may be found in the Perl 5 source kit.

Complete documentation for Perl, including FAQ lists, should be found on
this system using `man perl' or `perldoc perl'.  If you have access to the
Internet, point your browser at http://www.perl.com/, the Perl Home Page.
$ rpm -qa | grep libwww-perl
perl-libwww-perl-5.79-5

$ perl -version

This is perl 5, version 16, subversion 3 (v5.16.3) built for x86_64-linux-thread-multi
(with 29 registered patches, see perl -V for more detail)

Copyright 1987-2012, Larry Wall

Perl may be copied only under the terms of either the Artistic License or the
GNU General Public License, which may be found in the Perl 5 source kit.

Complete documentation for Perl, including FAQ lists, should be found on
this system using "man perl" or "perldoc perl".  If you have access to the
Internet, point your browser at http://www.perl.org/, the Perl Home Page.
$ rpm -qa | grep libwww-perl
perl-libwww-perl-6.05-2.17.amzn1.noarch

対処

agentの指定を無効化した

#$ua->agent('Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)');

agentの指定しない場合のagentは?

libwww-perlのバージョンが設定される

 [06/Jun/2017:14:47:32 +0000] "GET /index.html HTTP/1.1" 200 - "-" "libwww-perl/6.05"
[06/Jun/2017:14:51:13 +0000] "GET /index.html HTTP/1.1" 200 - "-" "libwww-perl/5.805"

実際のブラウザからのアクセスを想定した動作にしたいのでagentは設定する。

無効化するとスパム扱いされる可能性あるから設定したい。

ブラウザからアクセスした場合のヘッダー情報と、スクリプトからのアクセスした場合のヘッダー情報を比較して

色々試した結果以下を追加したら成功した。

$ua->default_header('accept-encoding' => 'gzip,deflate');

あとSSLのサイトで、ブラウザはOKだけどスクリプトNGだった奴は以下を追加して対応

$ua->ssl_opts(verify_hostname => 0);

にひりずむ::しんぷる - LWP での SSL 接続で certificate verify failed しちゃう件の解決方法

詳細はまた後日。。。