2009-11-17 71 views
4

我想對此perl腳本使用代理,但我不確定如何使其使用代理。在perl腳本中使用代理

#!/usr/bin/perl 
use IO::Socket; 
$remote = IO::Socket::INET->new(
         Proto => "tcp", 
         PeerAddr => "localhost", 
         PeerPort => "8080", 
        ) 
        or die "cannot connect"; 
print $remote "GET/HTTP/1.0\n\n"; 
    while (<$remote>) { print } 
+0

還在尋找一個非LWP解決方案 – Hintswen 2010-08-03 12:45:48

回答

9

使用LWP :: UserAgent模塊,它內置了proxy support。從我的劇本之一

+0

+1。比嘗試自己做更容易。 – rjp 2009-11-17 09:34:25

+0

我寧可不要使用LWP :: UserAgent。 -high- – Hintswen 2009-11-17 11:07:52

+0

@Hintswen - 你寧願不用LWP :: UserAgent可行解決方案的原因是什麼 - 爲什麼嘆息? – 2009-11-17 13:32:19

1

直:

use LWP::UserAgent; 
my($ua) = LWP::UserAgent->new; 

if ($opts->{'proxy'}) { 
    my($ip) = Sys::HostIP->hostip; 
    if (($ip =~ m{^16\.143\.}) || 
     ($ip =~ m{^161\.}) || 
     ($ip =~ m{^164\.})) { 
     $ua->proxy(http => 'http://localhost:8080'); 
    } 
    else { 
     $ua->proxy(http => ""); 
    } 
} 
else { 
    $ua->env_proxy; 
} 

#***** get current entry ***** 
my($req) = HTTP::Request->new(GET => "http://stackoverflow.com/questions/1746614/use-proxy-with-perl-script"); 
my($raw) = $ua->request($req)->content; 
7
use LWP::UserAgent; 
    $ua = LWP::UserAgent->new; 
    $ENV{HTTP_proxy} = "http://ip:port"; 
    $ua->env_proxy; # initialize from environment variables 
    my $req = HTTP::Request->new(GET => 'http://google.com/'); 
    print $ua->request($req)->as_string; 
    delete $ENV{HTTP_PROXY};