LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
楼主: devel

perl脚本共享区(欢迎大家把实用的脚本贴在这里) :2004年1月20日更新

[复制链接]
发表于 2004-1-11 10:44:38 | 显示全部楼层
Problems with binary transfers in Net::FTP
come from this link:
http://www.perldiscuss.com/artic ... p;group=perl.libnet

Subject: Problems with binary transfers in Net::FTP
From: (F Marchettistasi)
Newsgroups: perl.libnet
Date: Feb 24 2003 11:27:56

I am writing a perl script to automatically transfer a section of
our Intranet to Internet, at the same time reformatting index
pages and rearranging directories. I am rather satisfied of the
outcome, but I have problems with the transfer of TIFF images:
apparently, they are transferred in ASCII mode, in spite of the
message "Opening BINARY data mode" in the log.

Here is a test script I used to narrow down the problem (sorry
for the masking of the addresses, even if we don't have an
explicit policy to that effect I think it's safer to avoid
sending them out):

-----<Cut here>-----
#!/usr/bin/perl -w

$debug = 1 ;

$localfile = "test.tif" ;
$remotefile = "test-auto.tif" ;

use Net::FTP ;
use Fcntl ;

$ftp = Net::FTP -> new ( "xxx.yyy.z.ww" ,
                         Debug => $debug , Passive => 0
                         ) ;
if ( ! defined $ftp ) {
    print "Error: connection to the FTP server failed.\n" ;
    print "Reason: $@\n" ;
    exit 1 ;
}

$ftp -> login ( "xxxxxxxxxxxx" , "************" ) ;

if ( ! $ftp -> ok () ) {
    print "Error connecting to the FTP server.\n" ;
    $errortext = $ftp -> message ;
    print "Reason: $errortext</p>\n" ;
    exit 1 ;
}


$ftp -> cwd ( "xxx.xxxxxx.it/ProjectTest/ ) ;

# $ftp -> type ( "binary" ) ;
$ftp -> quot ( "TYPE" , "I" ) ;
$ftp -> put ( $localfile , $remotefile ) ;

# $dcref = $ftp -> stor ( $remotefile ) ;
# sysopen ( LOC , $localfile , O_RDONLY ) ;
# binmode LOC ;

# my $readbuf = '' ;
# my $nread = 0 ;
# my $bsize = 1024 ;
# while ( ( $nread = sysread ( LOC , $readbuf , $bsize ) ) != 0 )
{
#     $dcref -> write ( $readbuf , $nread ) ;
# }
# $dcref -> close ;
# close LOC ;


$ftp -> quit ;
-----<Cut here>-----

The (NT) server I am connecting to does not understand "TYPE
BINARY", so I have to send a "TYPE I" command instead. In the
commented section I tried to use a dataconn object to have more
control. I also tried to turn passive mode on, since the server
seems to prefer passive data transfer. The result is always the
same: the file transferred via manual ftp is correctly sent,
while the one transferred via Net:FTP gets corrupted.

And here is the output:

-----<Cut here>-----
Net::FTP: Net::FTP(2.65)
Net::FTP:   Exporter(5.566)
Net::FTP:   Net::Cmd(2.21)
Net::FTP:   IO::Socket::INET(1.26)
Net::FTP:     IO::Socket(1.27)
Net::FTP:       IO::Handle(1.21)

Net::FTP=GLOB(0x806517c)<<< 220 InterScan FTP VirusWall NT 3.53
(Stand-alone Mode), Virus scan on
Net::FTP=GLOB(0x806517c)>>> user xxxxxxxxxxxx@xxx.yyy.z.ww
Net::FTP=GLOB(0x806517c)<<< 331 Password required for
xxxxxxxxxxxx.
Net::FTP=GLOB(0x806517c)>>> PASS ....
Net::FTP=GLOB(0x806517c)<<< 230 User xxxxxxxxxxxx logged in.
Net::FTP=GLOB(0x806517c)>>> CWD xxx.xxxxxx.it/ProjectTest/
Net::FTP=GLOB(0x806517c)<<< 250 CWD command successful.
Net::FTP=GLOB(0x806517c)>>> TYPE I
Net::FTP=GLOB(0x806517c)<<< 200 Type set to I.
Net::FTP=GLOB(0x806517c)>>> PORT xx,yyy,w,zz,14,24
Net::FTP=GLOB(0x806517c)<<< 200 PORT command successful.
Net::FTP=GLOB(0x806517c)>>> STOR test.tif
Net::FTP=GLOB(0x806517c)<<< 150 Opening BINARY mode data
connection for test.tif.
Net::FTP=GLOB(0x806517c)<<< 226-Message from InterScan FTP
VirusWall NT 3.53
Net::FTP=GLOB(0x806517c)<<< 226-No virus found in test.tif
Net::FTP=GLOB(0x806517c)<<< 226 Transfer complete.
Net::FTP=GLOB(0x806517c)>>> QUIT
Net::FTP=GLOB(0x806517c)<<< 221
-----<Cut here>-----

Everything seems just fine, doesn't it? Well it isn't; here is an
ftp session which demonstrates it:

-----<Cut here>-----
$ ftp xxx.yyy.z.ww
Connected to xxx.yyy.z.ww (xxx.yyy.z.ww).
220 InterScan FTP VirusWall NT 3.53 (Stand-alone Mode), Virus
scan on
331 Password required for xxxxxxxxxxxx.
230 User xxxxxxxxxxxx logged in.
Remote system type is Windows_NT.
ftp> cd xxx.xxxxxx.it/ProjectTest/
250 CWD command successful.
ftp> bin
200 Type set to I.
ftp> put test.tif
local: test.tif remote: test.tif
227 Entering Passive Mode (xxx,yyy,z,ww,10,47)
125 Data connection already open; Transfer starting.
226-Message from InterScan FTP VirusWall NT 3.53
226-No virus found in test.tif
226 Transfer complete.
110180 bytes sent in 0.325 secs (3.3e+02 Kbytes/sec)
ftp> ls
227 Entering Passive Mode (xxx,yyy,z,ww,10,63)
125 Data connection already open; Transfer starting.
02-24-03  10:58AM               110494 test-auto.tif
02-24-03  11:12AM               110180 test.tif
226 Transfer complete.
ftp> quit
221
$ wc -l test.tif
    314 test.tif
-----<Cut here>-----

As you can see from the output of "wc", the tif "file" has 314
"lines", so that an additional octet is added for each "line", as
in ASCII mode.

Sorry for the length, I tried to be as precise as possible. Any
suggestion is HIGHLY welcome...

Francesco Marchetti-Stasi
(f.marchettistasi at avlp.it
 楼主| 发表于 2004-1-20 18:18:02 | 显示全部楼层
come from
http://developer.netscape.com/do ... rise/nt/cgitips.htm

A sample CGI program in Perl

The following Perl example prints a message about the browser being used, unless the browser is Netscape Navigator, in which case the example prints a different message. This shows how you can do different actions depending on the client browser. This example also shows how you get information from environment variables.

A CGI Perl example that checks the user's client browser

#!/bin/perl
# Remember that the above line must reflect where your perl really resides.
# sample2.pl: A simple Perl CGI program that displays a different message  
#             depending on the user's browser.

# Terminate headers
print "Content-type: text/htmlnn";

# Get the User-Agent (also known as client type)
$user_agent = $ENV{"HTTP_USER_AGENT"};

# Print a header with appropriate information
print "  <TITLE>Which browser are you using?</TITLE>
<H1 align=center>Which browser are you using?</H1>";

# Print the browser that they're using.
print "<hr>I'm using <b>".$user_agent."</b><hr>n";

# If it's Mozilla (Netscape Navigator), tell them how cool they are.  
if($user_agent =~ "Mozilla")
        { print "<i>Congratulations!</i>"; }
else
        { print "<i>To each his own, as they say.</i>"; }

print "<hr>";

The CGI Perl code that handles the form data

#!/bin/perl
# Remember that the above line has to reflect where your perl really resides. This is a  
# simple form handler that uses form values to send mail to a hard-coded user.

# Terminate headers
print "Content-type: text/htmlnn";

# Who should get the email and where is the email program?
$send_to = "user@yourserver.yourdomain.dom";
$mail_prog = "/usr/lib/sendmail";

# See which method they used to access this form. If they used POST, then
# read the input from STDIN. If they used GET, use the query string.

# Which method is used is determined by the HTML in the form.
if($ENV{'REQUEST_METHOD'} eq "GET") {
        $buffer = $ENV{'QUERY_STRING'};
        if($buffer eq "")  {
                print "<TITLE>Error - use HTML</TITLE>n";
                print "<H1 align=center>lease use the HTML form provided</H1>n";
                print "You accessed this program without a valid query string. Please ";
                print "use the associated form to access it.n";
                exit(1);
        }
}  else  {
        read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
}
# Split pairs by the ampersand that divides variables
@pairs = split(/&/, $buffer);
# Create an array, indexed by the variable name, that contains all the values

foreach $pair (@pairs)
{
# Each variable is structured "name1=value1", so split it on those lines
        ($name, $value) = split(/=/, $pair);

# Decode the value (+ is a space, and %xx in hex is an encoded character)
        $value =~ tr/+/ /;
        $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
# Create an array indexed by names and put the value in
$form{$name} = $value;
}

# The program should have the following values:
#  email  = the person's email address
#  p_feed = the person's positive feedback
#  n_feed = the person's negative feedback
#
# Next, put it into a usable form and mail it. Check to see if they left an
# email address. Don't check to see if it's valid, just to see if it's there.
if($form{"email"} eq "")  {
print "<TITLE>Sorry</TITLE>n";
print "<h1 align=center>No email address given</h1>n";
print "<p align=center>Your request could not be sent because you ";
print "gave no return address. Please give a return address and ";
print "try again.</p>n";
exit(1);
}

# Open the mail command, or print an error.
open (MAIL, "|$mail_prog $send_to") || die "Could not open $mail_prog";

# Send the feedback. print MAIL "From: $form{'email'}n";  


# Print the user's email address as a reply-to, and send the user a copy
print MAIL "Reply-to: $form{'email'}n";
print MAIL "Cc: $form{'email'}n";

# Terminate mail headers.
print MAIL "n";

# Create the document body
print MAIL "Feedback from ".$form{'email'}.":n";
print MAIL "--------------------------------------------------------------n";
print MAIL "n----Positive feedback----n";
print MAIL $form{'p_feed'};
print MAIL "n----Negative feedback----n";
print MAIL $form{'n_feed'};
print MAIL "n------------------------------------------------------------n";

# Close the command, and send the mail.
close (MAIL);

# Now print out a success story, so the user knows it was sent
print "<TITLE>Thanks for your feedback</TITLE>n";
print "<h1 align=center>Thanks for your feedback</h1>n";
print "Thanks for taking the time to give us your feedback. We hope that ";
print "with your help, we can make this an even better web site!n";
print "<hr>";

exit(0);
发表于 2004-1-21 22:04:09 | 显示全部楼层
Internet TCP Clients and Servers

Use Internet-domain sockets when you want to do client-server communication that might extend to machines outside of your own system.

Here's a sample TCP client using Internet-domain sockets:

#!/usr/bin/perl -w require 5.002; use strict; use Socket; my ($remote,$port, $iaddr, $paddr, $proto, $line); $remote = shift || 'localhost'; $port = shift || 2345; # random port if ($port =~ /\D/) { $port = getservbyname($port, 'tcp') } die &amp;quot;No port&amp;quot; unless $port; $iaddr = inet_aton($remote) || die &amp;quot;no host: $remote&amp;quot;; $paddr = sockaddr_in($port, $iaddr); $proto = getprotobyname('tcp'); socket(SOCK, PF_INET, SOCK_STREAM, $proto) || die &amp;quot;socket: $!&amp;quot;; connect(SOCK, $paddr) || die &amp;quot;connect: $!&amp;quot;; while ($line = &lt;sock&gt;) { print $line; } close (SOCK) || die &amp;quot;close: $!&amp;quot;; exit;

And here's a corresponding server to go along with it. We'll leave the address as INADDR_ANY so that the kernel can choose the appropriate interface on multihomed hosts:

#!/usr/bin/perl -Tw require 5.002; use strict; BEGIN { $ENV{PATH} = '/usr/ucb:/bin' } use Socket; use Carp; sub spawn; # forward declaration sub logmsg { print &amp;quot;$0 $$: @_ at &amp;quot;, scalar localtime, &amp;quot;\n&amp;quot; } my $port = shift || 2345; my $proto = getprotobyname('tcp'); socket(SERVER, PF_INET, SOCK_STREAM, $proto) || die &amp;quot;socket: $!&amp;quot;; setsockopt(SERVER, SOL_SOCKET, SO_REUSEADDR, 1) || die &amp;quot;setsockopt: $!&amp;quot;; bind(SERVER, sockaddr_in($port, INADDR_ANY)) || die &amp;quot;bind: $!&amp;quot;; listen(SERVER,5) || die &amp;quot;listen: $!&amp;quot;; logmsg &amp;quot;server started on port $port&amp;quot;; my $waitedpid = 0; my $paddr; sub REAPER { $SIG{CHLD} = \&amp;amp;REAPER; # loathe sysV $waitedpid = wait; logmsg &amp;quot;reaped $waitedpid&amp;quot; . ($? ? &amp;quot; with exit $?&amp;quot; : ''); } $SIG{CHLD} = \&amp;amp;REAPER; for ( $waitedpid = 0; ($paddr = accept(CLIENT,SERVER)) || $waitedpid; $waitedpid = 0, close CLIENT) { next if $waitedpid; my($port,$iaddr) = sockaddr_in($paddr); my $name = gethostbyaddr($iaddr,AF_INET); logmsg &amp;quot;connection from $name [&amp;quot;, inet_ntoa($iaddr), &amp;quot;] at port $port&amp;quot;; spawn sub { print &amp;quot;Hello there, $name, it's now &amp;quot;, scalar localtime, &amp;quot;\n&amp;quot;; exec '/usr/games/fortune' or confess &amp;quot;can't exec fortune: $!&amp;quot;; }; } sub spawn { my $coderef = shift; unless (@_ == 0 &amp;amp;&amp;amp; $coderef &amp;amp;&amp;amp; ref($coderef) eq 'CODE') { confess &amp;quot;usage: spawn CODEREF&amp;quot;; } my $pid; if (!defined($pid = fork)) { logmsg &amp;quot;cannot fork: $!&amp;quot;; return; } elsif ($pid) { logmsg &amp;quot;begat $pid&amp;quot;; return; # i'm the parent } # else i'm the child -- go spawn open(STDIN, &amp;quot;&lt;&amp;client") || die "can't dup client to stdin"; open(STDOUT, "&gt;&amp;amp;CLIENT&amp;quot;) || die &amp;quot;can't dup client to stdout&amp;quot;; ## open(STDERR, &amp;quot;&amp;gt;&amp;amp;STDOUT&amp;quot;) || die &amp;quot;can't dup stdout to stderr&amp;quot;; exit &amp;amp;$coderef(); }

This server takes the trouble to clone off a child version via fork() for each incoming request. That way it can handle many requests at once, which you might not always want. Even if you don't fork() , the listen() will allow that many pending connections. Forking servers have to be particularly careful about cleaning up their dead children (called ``zombies'' in Unix parlance), because otherwise you'll quickly fill up your process table.

We suggest that you use the -T flag to use taint checking (see the perlsec manpage ) even if we aren't running setuid or setgid. This is always a good idea for servers and other programs run on behalf of someone else (like CGI scripts), because it lessens the chances that people from the outside will be able to compromise your system.

Let's look at another TCP client. This one connects to the TCP ``time'' service on a number of different machines and shows how far their clocks differ from the system on which it's being run:

#!/usr/bin/perl -w require 5.002; use strict; use Socket; my $SECS_of_70_YEARS = 2208988800; sub ctime { scalar localtime(shift) } my $iaddr = gethostbyname('localhost'); my $proto = getprotobyname('tcp'); my $port = getservbyname('time', 'tcp'); my $paddr = sockaddr_in(0, $iaddr); my($host); $| = 1; printf &amp;quot;%-24s %8s %s\n&amp;quot;, &amp;quot;localhost&amp;quot;, 0, ctime(time()); foreach $host (@ARGV) { printf &amp;quot;%-24s &amp;quot;, $host; my $hisiaddr = inet_aton($host) || die &amp;quot;unknown host&amp;quot;; my $hispaddr = sockaddr_in($port, $hisiaddr); socket(SOCKET, PF_INET, SOCK_STREAM, $proto) || die &amp;quot;socket: $!&amp;quot;; connect(SOCKET, $hispaddr) || die &amp;quot;bind: $!&amp;quot;; my $rtime = ' '; read(SOCKET, $rtime, 4); close(SOCKET); my $histime = unpack(&amp;quot;N&amp;quot;, $rtime) - $SECS_of_70_YEARS ; printf &amp;quot;%8d %s\n&amp;quot;, $histime - time, ctime($histime); }


Unix-Domain TCP Clients and Servers

That's fine for Internet-domain clients and servers, but what local communications? While you can use the same setup, sometimes you don't want to. Unix-domain sockets are local to the current host, and are often used internally to implement pipes. Unlike Internet domain sockets, UNIX domain sockets can show up in the file system with an ls(1) listing.

$ ls -l /dev/log srw-rw-rw- 1 root 0 Oct 31 07:23 /dev/log

You can test for these with Perl's -S file test:

unless ( -S '/dev/log' ) { die &amp;quot;something's wicked with the print system&amp;quot;; }

Here's a sample Unix-domain client:

#!/usr/bin/perl -w require 5.002; use Socket; use strict; my ($rendezvous, $line); $rendezvous = shift || '/tmp/catsock'; socket(SOCK, PF_UNIX, SOCK_STREAM, 0) || die &amp;quot;socket: $!&amp;quot;; connect(SOCK, sockaddr_un($remote)) || die &amp;quot;connect: $!&amp;quot;; while ($line = &lt;sock&gt;) { print $line; } exit;

And here's a corresponding server.

#!/usr/bin/perl -Tw require 5.002; use strict; use Socket; use Carp; BEGIN { $ENV{PATH} = '/usr/ucb:/bin' } my $NAME = '/tmp/catsock'; my $uaddr = sockaddr_un($NAME); my $proto = getprotobyname('tcp'); socket(SERVER,PF_UNIX,SOCK_STREAM,0) || die &amp;quot;socket: $!&amp;quot;; unlink($NAME); bind (SERVER, $uaddr) || die &amp;quot;bind: $!&amp;quot;; listen(SERVER,5) || die &amp;quot;listen: $!&amp;quot;; logmsg &amp;quot;server started on $NAME&amp;quot;; $SIG{CHLD} = \&amp;amp;REAPER; for ( $waitedpid = 0; accept(CLIENT,SERVER) || $waitedpid; $waitedpid = 0, close CLIENT) { next if $waitedpid; logmsg &amp;quot;connection on $NAME&amp;quot;; spawn sub { print &amp;quot;Hello there, it's now &amp;quot;, scalar localtime, &amp;quot;\n&amp;quot;; exec '/usr/games/fortune' or die &amp;quot;can't exec fortune: $!&amp;quot;; }; }

As you see, it's remarkably similar to the Internet domain TCP server, so much so, in fact, that we've omitted several duplicate functions--spawn(), logmsg(), ctime(), and REAPER()--which are exactly the same as in the other server.

So why would you ever want to use a Unix domain socket instead of a simpler named pipe? Because a named pipe doesn't give you sessions. You can't tell one process's data from another's. With socket programming, you get a separate session for each client: that's why accept() takes two arguments.

For example, let's say that you have a long running database server daemon that you want folks from the World Wide Web to be able to access, but only if they go through a CGI interface. You'd have a small, simple CGI program that does whatever checks and logging you feel like, and then acts as a Unix-domain client and connects to your private server.
发表于 2004-1-27 00:42:04 | 显示全部楼层
come from
http://www.zevils.com/cgi-bin/cv ... c/tocserver?rev=1.5

不知道干什么用的?


  1. #!/usr/bin/perl

  2. use Data::Dumper;
  3. use Toc qw(:all);
  4. use IO::Socket;
  5. use IO::Select;
  6. use GDBM_File;
  7. use Fcntl;
  8. use Fcntl qw(:flock);
  9. use POSIX;

  10. my($sock, $pid, $screenname);

  11. $pid = fork;
  12. exit unless $pid == 0;
  13. POSIX::setsid();

  14. $sock = IO::Socket::INET->new(LocalPort => 5000, Listen => 5) or die "Couldn't sock: $@\n";
  15. $dir = (getpwent())[7];

  16. unlink "$dir/toc.db";
  17. unlink "$dir/chatseq";
  18. system("rm -f $dir/*.lock");

  19. sub dbtie() {
  20.         my $VAR1;

  21.         while(-f "$dir/toc.db.lock") { select(undef, undef, undef, 0.01); }
  22.         touch("$dir/toc.db.lock");
  23.         open(TOC, "$dir/toc.db");
  24.         local $/ = undef;
  25.         my $toc = <TOC>;
  26.         eval $toc;
  27.         %toc = %$VAR1;
  28.         close TOC;
  29.         #print "Loaded DB: ", Data::Dumper::Dumper(\%toc), "\n";
  30. }

  31. sub dbuntie() {
  32.         open(TOC, ">$dir/toc.db");
  33.         print TOC Data::Dumper::Dumper \%toc;
  34.         #print "Dumping DB: ", Data::Dumper::Dumper(\%toc), "\n";
  35.         close TOC;
  36.         unlink "$dir/toc.db.lock";
  37. }

  38. sub END { $server->close if $server; $client->close if $client; }

  39. sub chatseq() {
  40.         while(-f "$dir/chatseq.lock") { select(undef, undef, undef, 0.01); }
  41.         touch("$dir/chatseq.lock");

  42.         open(CHATSEQ, "$dir/chatseq");
  43.         my $chatseq = <CHATSEQ> or "0";
  44.         close CHATSEQ;

  45.         $chatseq++;
  46.         open(CHATSEQ, ">$dir/chatseq");
  47.         print CHATSEQ $chatseq;
  48.         close CHATSEQ;

  49.         unlink("$dir/chatseq.lock");
  50.         return $chatseq;
  51. }

  52. sub touch($) {
  53.         my $file = shift;
  54.         open(FILE, ">$file");
  55.         close FILE;
  56. }

  57. sub putmsg($$) {
  58.         my $who = shift;
  59.         my $message = shift;
  60.         my ($inmsg, @messages, $VAR1);

  61.         push @{$queue{$who}}, $message if $message;
  62.         return if -f "$dir/$who" or not @{$queue{$who}};

  63.         print "Put $message!\n";
  64.         while(-f "$dir/$who.lock") { select(undef, undef, undef, 0.01); }
  65.         touch("$dir/$who.lock");

  66.         open(MSG, ">$dir/$who");
  67.         print MSG scalar pop @{$queue{$who}};
  68.         close MSG;
  69.         unlink("$dir/$who.lock");

  70.         print "$screenname putmsg($who, $message)\n";
  71. }

  72. sub getmsg() {
  73.         my(@messages, $VAR1);

  74.         while(-f "$dir/$screenname.lock") { select(undef, undef, undef, 0.01); }
  75.         touch("$dir/$screenname.lock");
  76.         open(MSG, "$dir/$screenname");
  77.         local $/ = undef;
  78.         my $message = <MSG>;
  79.         print "Got $message!\n";
  80.         close MSG;
  81.         unlink "$dir/$screenname";
  82.         unlink "$dir/$screenname.lock";

  83.         print STDERR "getmsg($screenname, $message)\n";
  84.         return $message;
  85. }

  86. sub tellbuds($) {
  87.         my $message = shift;
  88.         my $person;

  89.         foreach $person(keys %{$toc{people}}) {
  90.                 next unless exists $toc{people}{$person}{on} and exists $toc{people}{$person}{buddies}{$screenname};
  91.                 putmsg($person, $message);
  92.         }
  93. }

  94. sub unquote($) {
  95.         my $msg = shift;
  96.         $msg =~ s/\\\\/\\/g;
  97.         $msg =~ s/\\\$/\$/g; $msg =~ s/\\\[/\[/g; $msg =~ s/\\]/]/g;
  98.         $msg =~ s/\\\(/\(/g; $msg =~ s/\\\)/\)/g; $msg =~ s/\\\#/\#/g;
  99.         $msg =~ s/\\\{/\{/g; $msg =~ s/\\\}/\}/g; $msg =~ s/\\"/"/g;
  100.         $msg =~ s/\\\'/\'/g; $msg =~ s/\\\`/\`/g;
  101.         return $msg;
  102. }

  103. sub leavechat($) {
  104.         my $chat = shift;
  105.         my $chatname;
  106.         my $person;

  107.         $chatname = $toc{people}{$screenname}{chats}{$chat};
  108.         foreach $person(keys %{$toc{chats}{$chatname}}) {
  109.                 next if $person eq $screenname;
  110.                 putmsg($person, "CHAT_UPDATE_BUDDY:".$toc{chats}{$chatname}{$person}.":F:$screenname");
  111.         }
  112.         delete $toc{chats}{$chatname}{$screenname};
  113. }

  114. sub toc_signoff() {
  115.         my $chat;
  116.         my $chatname;
  117.         my $person;

  118.         dbtie;

  119.         foreach $chat(keys %{$toc{people}{$screenname}{chats}}) {
  120.                 leavechat($chat);
  121.         }

  122.         delete $toc{people}{$screenname};
  123.         tellbuds("UPDATE_BUDDY:$screenname:F:0:0:0:  ");
  124.         unlink "$dir/$screenname";
  125.         dbuntie;
  126. }

  127. $Toc::config{temp}{paused} = 0;
  128. while($client = $sock->accept) {
  129.         my($line, $message, $command, @params, $person, $flags);

  130.         $pid = fork();
  131.         die "Couldn't fork: $!" unless defined $pid;
  132.         if($pid == 0) {
  133.                 $client->close;
  134.                 next;
  135.         }

  136.         ${*$client}{'net_toc_username'} = 'temp';

  137.         $client->read($line, 10);
  138.         die unless $line eq "FLAPON\r\n\r\n";

  139.         $flags = 0;
  140.         fcntl($client, F_GETFL, $flags);
  141.         $flags |= O_NONBLOCK;
  142.         fcntl($client, F_SETFL, $flags);

  143.         #sflap_do($client, "SIGN_ON:1.0");
  144.         sflap_put($client, sflap_encode(pack("N", 1), 1));
  145.         $message = sflap_get($client, 1);
  146.         (undef, undef, undef, $screenname) = unpack("Nnna*", $message); #signon packet
  147.         $Toc::config{$screenname}{paused} = 0;
  148.         ${*$client}{'net_toc_username'} = $screenname;
  149.         sflap_get($client, 1);
  150.         sflap_do($client, "SIGN_ON:TOC1.0");
  151.         sflap_do($client, "NICK:$screenname");
  152.         sflap_do($client, "CONFIG:m 1\ng Buddies\nb $screenname");

  153.         while(1) {
  154.                 foreach $person(keys %queue) {
  155.                         putmsg($person, undef);
  156.                 }
  157.                 select(undef, undef, undef, 0.1);

  158.                 if(-f "$dir/$screenname") {
  159.                         sflap_do($client, getmsg());
  160.                 }

  161.                 $message = sflap_get($client);
  162.                 if($message eq "-1" and $! != EAGAIN) {
  163.                         toc_signoff;
  164.                         die "Client died: $!\n";
  165.                 } elsif($message eq "-1" or $message =~ /^\s*$/) {
  166.                         next;
  167.                 } else {
  168.                         #print "We got $message!\n";
  169.                 }

  170.                 for($i = length($message) - 1; $i >= 0; $i--) {
  171.                         substr($message, $i, 1, "") if substr($message, $i, 1) eq chr(0);
  172.                 }
  173.                 dbtie;
  174.                 my @new = ();
  175.                 push(@new, $+) while $message =~ m{
  176.                         "([^"\\]*(?:\\.[^"\\]*)*)"\s?  # groups the phrase inside the quotes
  177.                         | ([^ ]+)\s?
  178.                         | \s
  179.                 }gx;
  180.                 push(@new, undef) if substr($message,-1,1) eq ' ';

  181.                 ($command, @params) = map { unquote($_) } @new;
  182.                 #print "command=$command.\n";
  183.                 if($command eq "toc_init_done") {
  184.                         print "toc{people}{$screenname}?\n";
  185.                         $toc{people}{$screenname}{on} = 1;
  186.                         print Data::Dumper::Dumper($toc{people}{$screenname}), "\n";
  187.                         tellbuds("UPDATE_BUDDY:$screenname:T:0:".time.":0: O");
  188.                 } elsif($command eq "toc_send_im") {
  189.                         my($who, $message) = @params;
  190.                         print "toc{people}{$who}?\n";
  191.                         print Data::Dumper::Dumper($toc{people}{$who}), "\n";
  192.                         if(exists $toc{people}{$who}{on}) {
  193.                                 putmsg($who, "IM_IN:$screenname:F:$message");
  194.                         } else {
  195.                                 putmsg($screenname, "ERROR:901:$who");
  196.                         }
  197.                 } elsif($command eq "toc_add_buddy") {
  198.                         foreach $person(@params) {
  199.                                 $toc{people}{$screenname}{buddies}{$person} = 1;
  200.                                 if(exists($toc{people}{$person}{on})) {
  201.                                         putmsg($screenname, "UPDATE_BUDDY:$person:T:0:".time.":0: O");
  202.                                 }
  203.                         }
  204.                 } elsif($command eq "toc_remove_buddy") {
  205.                         foreach $person(@params) {
  206.                                 delete $toc{people}{$screenname}{buddies}{$person};
  207.                         }
  208.                 } elsif($command eq "toc_set_config") {
  209.                 } elsif($command eq "toc_evil") {
  210.                 } elsif($command eq "toc_add_permit") {
  211.                 } elsif($command eq "toc_add_deny") {
  212.                 } elsif($command eq "toc_chat_join") {
  213.                         my $chat = chatseq();
  214.                         $toc{chats}{$params[1]}{$screenname} = $chat;
  215.                         $toc{people}{$screenname}{chats}{$chat} = $params[1];
  216.                         putmsg($screenname, "CHAT_JOIN:$chat:".$params[1]);
  217.                         putmsg($screenname, "CHAT_UPDATE_BUDDY:$chat:T:".join(":", keys %{$toc{chats}{$params[1]}}));
  218.                         foreach $person(keys %{$toc{chats}{$params[1]}}) {
  219.                                 next if $person eq $screenname;
  220.                                 $chat = $toc{chats}{$params[1]}{$person};
  221.                                 putmsg($person, "CHAT_UPDATE_BUDDY:$chat:T:$screenname");
  222.                         }
  223.                 } elsif($command eq "toc_chat_send") {
  224.                         my $chat = $params[0];
  225.                         $message = $params[1];
  226.                         my $chatname = $toc{people}{$screenname}{chats}{$chat};
  227.                         foreach $person(keys %{$toc{chats}{$chatname}}) {
  228.                                 putmsg($person, "CHAT_IN:".$toc{chats}{$chatname}{$person}.":$screenname:F:$message");
  229.                         }
  230.                 } elsif($command eq "toc_chat_whisper") {
  231.                         my $chat = $params[0];
  232.                         $person = $params[1];
  233.                         $message = $params[2];
  234.                         my $chatname = $toc{people}{$screenname}{chats}{$chat};
  235.                         putmsg($person, "CHAT_IN".$toc{chatname}{$person}.":$screenname:T:$message");
  236.                 } elsif($command eq "toc_chat_evil") {
  237.                 } elsif($command eq "toc_chat_invite") {
  238.                         my $chat = shift @params;
  239.                         $message = shift @params;
  240.                         my $chatname = $toc{people}{$screenname}{chats}{$chat};
  241.                         foreach $person(@params) {
  242.                                 $chat = chatseq();
  243.                                 $toc{people}{$person}{invites}{$chat} = $chatname;
  244.                                 putmsg($person, "CHAT_INVITE:$chatname:$chat:$screenname:$message");
  245.                         }
  246.                 } elsif($command eq "toc_chat_leave") {
  247.                         leavechat($params[0]);
  248.                 } elsif($command eq "toc_chat_accept") {
  249.                         my $chat = shift @params;
  250.                         my $chatname = $toc{people}{$screenname}{invites}{$chat};

  251.                         $toc{chats}{$chatname}{$screenname} = $chat;
  252.                         $toc{people}{$screenname}{chats}{$chat} = $chatname;
  253.                         putmsg($screenname, "CHAT_JOIN:$chat:$chatname");
  254.                         putmsg($screenname, "CHAT_UPDATE_BUDDY:$chat:T:".join(":", keys %{$toc{chats}{$chatname}}));

  255.                         foreach $person(keys %{$toc{chats}{$chatname}}) {
  256.                                 next if $person eq $screenname;
  257.                                 $chat = $toc{chats}{$chatname}{$person};
  258.                                 putmsg($person, "CHAT_UPDATE_BUDDY:$chat:T:$screenname");
  259.                         }
  260.                 } elsif($command eq "toc_get_info") {
  261.                 } elsif($command eq "toc_set_info") {
  262.                 } elsif($command eq "toc_set_away") {
  263.                         if($params[0]) {
  264.                                 tellbuds("UPDATE_BUDDY:$screenname:T:0:".time.":0: OU");
  265.                         } else {
  266.                                 tellbuds("UPDATE_BUDDY:$screenname:T:0:".time.":0: O");
  267.                         }
  268.                 } elsif($command eq "toc_get_dir") {
  269.                 } elsif($command eq "toc_set_dir") {
  270.                 } elsif($command eq "toc_dir_search") {
  271.                 } elsif($command eq "toc_set_idle") {
  272.                 } elsif($command eq "toc_set_caps") {
  273.                 } elsif($command eq "toc_rvous_propose") {
  274.                 } elsif($command eq "toc_rvous_accept") {
  275.                 } elsif($command eq "toc_rvous_cancel") {
  276.                 } elsif($command eq "toc_format_nickname") {
  277.                 } elsif($command eq "toc_change_passwd") {
  278.                 }

  279.                 dbuntie;
  280.         }
  281. }

  282. sub Toc::debug_print($$$) {
  283.         my($text, $type, $level) = @_;
  284.         #print STDERR "($level, $type) $text";
  285. }
复制代码
发表于 2004-2-3 17:43:17 | 显示全部楼层

send.pl


  1. #!/usr/local/bin/perl
  2. use strict;

  3. my $url = 'http://path/to/receive.pl';
  4. my $query = 'body=hogehoge';

  5. main();
  6. exit;

  7. sub main {
  8.     do_post($url, $query);
  9. }

  10. sub do_post {
  11.     my ($url, $query) = @_;
  12.     $url =~ m|^(?:[url]http://[/url])?(.*?)(/.*)|;
  13.     my $host = $1;
  14.     my $uri = $2;
  15.     my $len = length($query);

  16.     my $addr = (gethostbyname($host))[4];
  17.     my $name = pack("S n a4 x8", 2, 80, $addr);
  18.     socket(SOCKET, 2, 1, 0);
  19.     connect(SOCKET, $name);
  20.     binmode(SOCKET);
  21.     select(SOCKET); $| = 1; select(STDOUT);

  22.     print SOCKET <<END;
  23. POST $uri HTTP/1.0
  24. Host: $host
  25. Content-Length: $len

  26. $query
  27. END

  28.     while (<SOCKET>) {
  29.         print;
  30.     }

  31.     close(SOCKET);
  32. }
复制代码

com from this link:
http://uttsu.com/r/20021120_4.html
发表于 2004-6-4 20:30:46 | 显示全部楼层

分别把文本格式转换为 DOS/Windows系统和UNIX/Linux系统及Mac系统的

3个perl脚本,用来分别把文本格式转换为
DOS/Windows系统和UNIX/Linux系统及Mac系统的
[PHP]\064"


-----text3dos.pl---------------------------
#!/usr/bin/perl
while(<stdin>){
        $_=~/\r\n/\r;
        $_=~/\n/\r;
        $_=~/\r/\r\n;
        print $_;
}
#        DOS/Windows系统和UNIX/Linux系统及Mac系统的行结束符不一样.
#        DOS/Windows 的行结束符是 "\r\n" (回车符+换行符)
#        UNIX/Linux 的行结束符是 "\n" (换行符)
#        Mac 的行结束符是 "\r" (回车符)
#
#本例把UNIX/Linux 的行结束符 转换为DOS/Windows 的行结束符
#
#建议把她放到patch下,如 /usr/local/bin
#
#本例把标准输入的文本转换后送到标准输入。
#
#如 #cat textfile | text3dos.pl > texefile.txt
#
# jhuangjiahua@163.com
#



-----text3unix.pl---------------------------
#!/usr/bin/perl
while(<stdin>){
        $_=~/\r\n/\n;
        $_=~/\r/\n;
        print $_;
}



-----text3mac.pl---------------------------
#!/usr/bin/perl
while(<stdin>){
        $_=~/\r\n/\r;
        $_=~/\n/\r;
        print $_;
}


"[/PHP]
发表于 2004-12-12 09:50:43 | 显示全部楼层
各位朋友在发贴的时候能不能把程序的作用,和一些关键的地方作一些注释,这样新来的读起来就方便多了,也方便各位以后在复习.
谢谢各位的努力.
发表于 2005-11-1 13:10:52 | 显示全部楼层
author: me
utility: guestbook
testing: http://www.uni-ulm.de/~s_xsun/
code: http://www.uni-ulm.de/~s_xsun/tmp/cgi.pm
回复 支持 反对

使用道具 举报

发表于 2006-1-9 11:49:04 | 显示全部楼层
楼主的脚本是Perl NetWork Program<erl网络编程》里的例子。
呵呵。
回复 支持 反对

使用道具 举报

发表于 2006-7-24 22:49:28 | 显示全部楼层
以前的写的一个脚本, 用来批量下载163相册里的图片。
演示了如何使用LWP模块

#!/usr/bin/perl
#
# File: down.pl
# Author: phus

use strict;
use warnings;

use LWP::UserAgent;
use HTTP::Request::Common;
use Encode;
use File:ath;

sub lwp_get($;%)
{
    my ($url, %opt) = @_;

    my $uri = URI->new($url);
    my $referer = $uri->scheme."://".$uri->host.$uri->path unless (%opt || $opt{referer});  
    my $useragent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1' unless (%opt || $opt{useragent});

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

    my $req = HTTP::Request->new(GET => $url);
    $req->header('Host' => $uri->host);
    $req->header('User-Agent' => $useragent);
    $req->header('Referer' => $referer);
    $req->header('Cookie' => $opt{cookie});

    my $res = $ua->request($req);
    warn "fetch_page error! perhaps you should try again.\n" unless $res->is_success;

    if($opt{remote_charset} && $opt{local_charset} && ($opt{remote_charset} ne $opt{local_charset}))
    {
        return encode($opt{local_charset}, decode($opt{remote_charset}, $res->as_string));
    }

    return $res->as_string;
}

sub lwp_post($$;%)
{
    my ($url, $form_ref, %opt) = @_;

    my $uri = URI->new($url);
    my $referer = $uri->scheme."://".$uri->host.$uri->path unless (%opt || $opt{referer});  
    my $useragent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1' unless (%opt || $opt{useragent});
    my $cookie = ' '  unless (%opt || $opt{cookie});

    my $ua = LWP::UserAgent->new();
    $ua->default_headers->push_header('Host' => $uri->host,);
    $ua->default_headers->push_header('User-Agent' => $useragent,);
    $ua->default_headers->push_header('Referer' => $referer,);
    $ua->default_headers->push_header('Cookie' => $cookie);
   
    my $res = $ua->request(POST $url, Content => ${form_ref});

    warn "lwp_post faild!perhaps you supply a right password.\n" unless $res->is_success;

    return $res->as_string;
}

sub nease_split($$$)
{
    my ($html, $user, $aid) = @_;
    my ($datas) = $html =~ /var datas = \[(.*)\]/g;
    my ($gPhotosIds) = $html =~ /var gPhotosIds = \[(.*)\];/g;
   
    my (@hostids, @type, @name, @photoids);
    @photoids = split(/,/, $gPhotosIds);
    @hostids = $datas =~ /\[(\d\d\d),\d,"\d+x\d+","[^\]]* "\]/g;
    @type = $datas =~ /\[\d\d\d,(\d),"\d+x\d+","[^\]]* "\]/g;
    @name = $datas =~ /\[\d\d\d,\d,"\d+x\d+","([^\]]*) "\]/g;
   
    my @ext_types = ('.jpg', '.jpg', '.gif');
    my @url = ();
    foreach (0..$#photoids) {
        push(@url, "http://img".$hostids[$_].".photo.163.com/".$user."/".$aid."/".$photoids[$_].$ext_types[$type[$_]]);
        $name[$_] .= $ext_types[$type[$_]] unless ($name[$_] =~ /$ext_types[$type[$_]]$/)
    }
   
    return (\@url, \@name);
}

my ($user, $aid, $pwd) = @ARGV;
die "usage: $0 \$user \$aid [\$password]\n" if((not defined($user)) || (not defined($aid)));

my $aurl = "http://photo.163.com/photos/$user/$aid/";
my $iurl = "http://photo.163.com/js/photosinfo.php?user=$user&aid=$aid";

my ($html, $cookie);
if($pwd) {
    my %form =  ('checking' => '1', 'pass' => $pwd);
    $html = lwp_post($aurl, \%form);
    ($cookie) = $html =~ /Set\-Cookie.*)/ig;
}

$html = lwp_get($iurl, (cookie => $cookie));
my ($url_ref, $name_ref) = nease_split($html, $user, $aid);

my $folder = "$user/$aid";
mkpath($folder, 1, 0755);

my $ret;
foreach (0..$#${url_ref}) {
    print "\n$_/$#${url_ref} downloaded. ".$name_ref->[$_]."\n";
    next if(-f "$folder/".$name_ref->[$_+2]);
    $ret = `wget -c --referer=http://photo.163.com/photos/ $url_ref->[$_] -O \"$folder/$name_ref->[$_]\"`;
}
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表