home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2004 December / PCpro_2004_12.ISO / files / webserver / tsw / TSW_3.4.0.exe / Apache2 / perl / Perl.pm < prev    next >
Encoding:
Perl POD Document  |  2004-01-19  |  29.6 KB  |  876 lines

  1. # $Id: Perl.pm,v 1.113 2004/01/19 19:15:36 autarch Exp $
  2.  
  3. package Net::SSH::Perl;
  4. use strict;
  5.  
  6. use Net::SSH::Perl::Packet;
  7. use Net::SSH::Perl::Buffer;
  8. use Net::SSH::Perl::Config;
  9. use Net::SSH::Perl::Constants qw( :protocol :compat :hosts );
  10. use Net::SSH::Perl::Cipher;
  11. use Net::SSH::Perl::Util qw( :hosts _read_yes_or_no );
  12.  
  13. use vars qw( $VERSION $CONFIG $HOSTNAME );
  14. $CONFIG = {};
  15.  
  16. use Socket;
  17. use Fcntl;
  18. use Symbol;
  19. use Carp qw( croak );
  20. use Sys::Hostname;
  21. eval {
  22.     $HOSTNAME = hostname();
  23. };
  24.  
  25. $VERSION = '1.25';
  26.  
  27. sub VERSION { $VERSION }
  28.  
  29. sub new {
  30.     my $class = shift;
  31.     my $host = shift;
  32.     croak "usage: ", __PACKAGE__, "->new(\$host)"
  33.         unless defined $host;
  34.     my $ssh = bless { host => $host }, $class;
  35.     my %p = @_;
  36.     $ssh->{_test} = delete $p{_test};
  37.     $ssh->_init(%p);
  38.     $ssh->_connect unless $ssh->{_test};
  39.     $ssh;
  40. }
  41.  
  42. sub protocol { $_[0]->{use_protocol} }
  43.  
  44. sub set_protocol {
  45.     my $ssh = shift;
  46.     my $proto = shift;
  47.     $ssh->{use_protocol} = $proto;
  48.     my $proto_class = join '::', __PACKAGE__,
  49.         ($proto == PROTOCOL_SSH2 ? "SSH2" : "SSH1");
  50.     (my $lib = $proto_class . ".pm") =~ s!::!/!g;
  51.     require $lib;
  52.     bless $ssh, $proto_class;
  53.     $ssh->debug($proto_class->version_string);
  54.     $ssh->_proto_init;
  55. }
  56.  
  57. use vars qw( @COMPAT );
  58. @COMPAT = (
  59.   [  '^OpenSSH[-_]2\.[012]' => SSH_COMPAT_OLD_SESSIONID,   ],
  60.   [  'MindTerm'             => 0,                          ],
  61.   [  '^2\.1\.0 '            => SSH_COMPAT_BUG_SIGBLOB |
  62.                                SSH_COMPAT_BUG_HMAC |
  63.                                SSH_COMPAT_OLD_SESSIONID,   ],
  64.   [  '^2\.0\.'              => SSH_COMPAT_BUG_SIGBLOB |
  65.                                SSH_COMPAT_BUG_HMAC |
  66.                                SSH_COMPAT_OLD_SESSIONID |
  67.                                SSH_COMPAT_BUG_PUBKEYAUTH |
  68.                                SSH_COMPAT_BUG_X11FWD,      ],
  69.   [  '^2\.[23]\.0 '         => SSH_COMPAT_BUG_HMAC,        ],
  70.   [  '^2\.[2-9]\.'          => 0,                          ],
  71.   [  '^2\.4$'               => SSH_COMPAT_OLD_SESSIONID,   ],
  72.   [  '^3\.0 SecureCRT'      => SSH_COMPAT_OLD_SESSIONID,   ],
  73.   [  '^1\.7 SecureFX'       => SSH_COMPAT_OLD_SESSIONID,   ],
  74.   [  '^2\.'                 => SSH_COMPAT_BUG_HMAC,        ],
  75. );
  76.  
  77. sub _compat_init {
  78.     my $ssh = shift;
  79.     my($version) = @_;
  80.     $ssh->{datafellows} = 0;
  81.     for my $rec (@COMPAT) {
  82.         my($re, $mask) = @$rec[0, 1];
  83.         if ($version =~ /$re/) {
  84.             $ssh->debug("Compat match: '$version' matches pattern '$re'.");
  85.             $ssh->{datafellows} = $mask;
  86.             return;
  87.         }
  88.     }
  89.     $ssh->debug("No compat match: $version.");
  90. }
  91.  
  92. sub version_string { }
  93.  
  94. sub client_version_string { $_[0]->{client_version_string} }
  95. sub server_version_string { $_[0]->{server_version_string} }
  96.  
  97. sub _current_user {
  98.     my $user;
  99.     eval { $user = scalar getpwuid($<) };
  100.     $user;
  101. }
  102.  
  103. sub _init {
  104.     my $ssh = shift;
  105.  
  106.     my %arg = @_;
  107.     my $user_config = delete $arg{user_config} || "$ENV{HOME}/.ssh/config";
  108.     my $sys_config  = delete $arg{sys_config}  || "/etc/ssh_config";
  109.  
  110.     my $directives = delete $arg{options} || [];
  111.  
  112.     if (my $proto = delete $arg{protocol}) {
  113.         push @$directives, "Protocol $proto";
  114.     }
  115.  
  116.     my $cfg = Net::SSH::Perl::Config->new($ssh->{host}, %arg);
  117.     $ssh->{config} = $cfg;
  118.  
  119.     # Merge config-format directives given through "options"
  120.     # (just like -o option to ssh command line). Do this before
  121.     # reading config files so we override files.
  122.     for my $d (@$directives) {
  123.         $cfg->merge_directive($d);
  124.     }
  125.  
  126.     for my $f (($user_config, $sys_config)) {
  127.         $ssh->debug("Reading configuration data $f");
  128.         $cfg->read_config($f);
  129.     }
  130.  
  131.     if (my $real_host = $ssh->{config}->get('hostname')) {
  132.         $ssh->{host} = $real_host;
  133.     }
  134.  
  135.     my $user = _current_user();
  136.     if ($user && $user eq "root" &&
  137.       !defined $ssh->{config}->get('privileged')) {
  138.         $ssh->{config}->set('privileged', 1);
  139.     }
  140.  
  141.     unless ($ssh->{config}->get('protocol')) {
  142.         $ssh->{config}->set('protocol',
  143.             PROTOCOL_SSH1 | PROTOCOL_SSH2 | PROTOCOL_SSH1_PREFERRED);
  144.     }
  145.  
  146.     unless (defined $ssh->{config}->get('password_prompt_login')) {
  147.         $ssh->{config}->set('password_prompt_login', 1);
  148.     }
  149.     unless (defined $ssh->{config}->get('password_prompt_host')) {
  150.         $ssh->{config}->set('password_prompt_host', 1);
  151.     }
  152.     unless (defined $ssh->{config}->get('number_of_password_prompts')) {
  153.         $ssh->{config}->set('number_of_password_prompts', 3);
  154.     }
  155. }
  156.  
  157. sub _proto_init { }
  158.  
  159. sub register_handler { }
  160.  
  161. sub config { $_[0]->{config} }
  162.  
  163. sub configure {
  164.     my $class = shift;
  165.     $CONFIG = { @_ };
  166. }
  167.  
  168. sub ssh {
  169.     my($host, @cmd) = @_;
  170.     my($user);
  171.     ($host, $user) = $host =~ m!(.+)@(.+)! ?
  172.        ($2, $1) : ($host, _current_user());
  173.     my $ssh = __PACKAGE__->new($host, %$CONFIG);
  174.     $ssh->login($user);
  175.     my($out, $err, $exit) = $ssh->cmd(join ' ', @cmd);
  176.     print $out;
  177.     print STDERR $err if $err;
  178. }
  179.  
  180. sub issh {
  181.     my($host, @cmd) = @_;
  182.     print join(' ', @cmd), "\n";
  183.     print "Proceed: [y/N]:";
  184.     my $x = scalar(<STDIN>);
  185.     if ($x =~ /^y/i) {
  186.         $CONFIG->{interactive} = 1;
  187.         ssh($host, @cmd);
  188.     }
  189. }
  190.  
  191. sub _connect {
  192.     my $ssh = shift;
  193.     my $sock = $ssh->_create_socket;
  194.  
  195.     my $raddr = inet_aton($ssh->{host});
  196.     croak "Net::SSH: Bad host name: $ssh->{host}"
  197.         unless defined $raddr;
  198.     my $rport = $ssh->{config}->get('port') || 'ssh';
  199.     if ($rport =~ /\D/) {
  200.         my @serv = getservbyname(my $serv = $rport, 'tcp');
  201.         $rport = $serv[2];
  202.         croak "Can't map service name '$serv' to port number"
  203.             unless defined $rport;
  204.     }
  205.     $ssh->debug("Connecting to $ssh->{host}, port $rport.");
  206.     connect($sock, sockaddr_in($rport, $raddr))
  207.         or die "Can't connect to $ssh->{host}, port $rport: $!";
  208.  
  209.     select((select($sock), $|=1)[0]);
  210.  
  211.     $ssh->{session}{sock} = $sock;
  212.     $ssh->_exchange_identification;
  213.  
  214.     fcntl($sock, F_SETFL, O_NONBLOCK)
  215.         or die "Can't set socket non-blocking: $!";
  216.  
  217.     $ssh->debug("Connection established.");
  218. }
  219.  
  220. sub _create_socket {
  221.     my $ssh = shift;
  222.     my $sock = gensym;
  223.     if ($ssh->{config}->get('privileged')) {
  224.         my $p;
  225.         my $proto = getprotobyname('tcp');
  226.         for ($p = 1023; $p > 512; $p--) {
  227.             socket($sock, AF_INET, SOCK_STREAM, $proto) ||
  228.                 croak "Net::SSH: Can't create socket: $!";
  229.             last if bind($sock, sockaddr_in($p, INADDR_ANY));
  230.             if ($! =~ /Address already in use/i) {
  231.                 close($sock);
  232.                 next;
  233.             }
  234.             croak "Net::SSH: Can't bind socket to port $p: $!";
  235.         }
  236.         $ssh->debug("Allocated local port $p.");
  237.         $ssh->{config}->set('localport', $p);
  238.     }
  239.     else {
  240.         socket($sock, AF_INET, SOCK_STREAM, 0) ||
  241.             croak "Net::SSH: Can't create socket: $!";
  242.     }
  243.     $sock;
  244. }
  245.  
  246. sub _disconnect { }
  247.  
  248. sub fatal_disconnect {
  249.     my $ssh = shift;
  250.     $ssh->_disconnect(@_);
  251.     croak @_;
  252. }
  253.  
  254. sub sock { $_[0]->{session}{sock} }
  255.  
  256. sub _exchange_identification {
  257.     my $ssh = shift;
  258.     my $sock = $ssh->{session}{sock};
  259.     my $remote_id = <$sock>;
  260.     ($ssh->{server_version_string} = $remote_id) =~ s/\cM?\n$//;
  261.     my($remote_major, $remote_minor, $remote_version) = $remote_id =~
  262.         /^SSH-(\d+)\.(\d+)-([^\n]+)\n$/;
  263.     $ssh->debug("Remote protocol version $remote_major.$remote_minor, remote software version $remote_version");
  264.  
  265.     my $proto = $ssh->config->get('protocol');
  266.     my($mismatch, $set_proto);
  267.     if ($remote_major == 1) {
  268.         if ($remote_minor == 99 && $proto & PROTOCOL_SSH2 &&
  269.             !($proto & PROTOCOL_SSH1_PREFERRED)) {
  270.             $set_proto = PROTOCOL_SSH2;
  271.         }
  272.         elsif (!($proto & PROTOCOL_SSH1)) {
  273.             $mismatch = 1;
  274.         }
  275.         else {
  276.             $set_proto = PROTOCOL_SSH1;
  277.         }
  278.     }
  279.     elsif ($remote_major == 2) {
  280.         if ($proto & PROTOCOL_SSH2) {
  281.             $set_proto = PROTOCOL_SSH2;
  282.         }
  283.     }
  284.     if ($mismatch) {
  285.         croak sprintf "Protocol major versions differ: %d vs. %d",
  286.             ($proto & PROTOCOL_SSH2) ? PROTOCOL_MAJOR_2 :
  287.             PROTOCOL_MAJOR_1, $remote_major;
  288.     }
  289.     my $compat20 = $set_proto == PROTOCOL_SSH2;
  290.     my $buf = sprintf "SSH-%d.%d-%s\n",
  291.         $compat20 ? PROTOCOL_MAJOR_2 : PROTOCOL_MAJOR_1,
  292.         $compat20 ? PROTOCOL_MINOR_2 : PROTOCOL_MINOR_1,
  293.         $VERSION;
  294.     $ssh->{client_version_string} = substr $buf, 0, -1;
  295.     print $sock $buf;
  296.  
  297.     $ssh->set_protocol($set_proto);
  298.     $ssh->_compat_init($remote_version);
  299. }
  300.  
  301. sub debug {
  302.     my $ssh = shift;
  303.     if ($ssh->{config}->get('debug')) {
  304.         printf STDERR "%s@_\n", $HOSTNAME ? "$HOSTNAME: " : '';
  305.     }
  306. }
  307.  
  308. sub login {
  309.     my $ssh = shift;
  310.     my($user, $pass) = @_;
  311.     if (!defined $ssh->{config}->get('user')) {
  312.         $ssh->{config}->set('user',
  313.             defined $user ? $user : _current_user());
  314.     }
  315.     if (!defined $pass && exists $CONFIG->{ssh_password}) {
  316.         $pass = $CONFIG->{ssh_password};
  317.     }
  318.     $ssh->{config}->set('pass', $pass);
  319. }
  320.  
  321. sub _login { }
  322.  
  323. sub cmd { }
  324. sub shell { }
  325.  
  326. sub incoming_data {
  327.     my $ssh = shift;
  328.     if (!exists $ssh->{session}{incoming_data}) {
  329.         $ssh->{session}{incoming_data} = Net::SSH::Perl::Buffer->new( MP => $ssh->protocol == PROTOCOL_SSH2 ? 'SSH2' : 'SSH1' );
  330.     }
  331.     $ssh->{session}{incoming_data};
  332. }
  333.  
  334. sub session_id {
  335.     my $ssh = shift;
  336.     $ssh->{session}{id} = shift if @_;
  337.     $ssh->{session}{id};
  338. }
  339.  
  340. sub packet_start { Net::SSH::Perl::Packet->new($_[0], type => $_[1]) }
  341.  
  342. sub check_host_key {
  343.     my $ssh = shift;
  344.     my($key, $host, $u_hostfile, $s_hostfile) = @_;
  345.     $host ||= $ssh->{host};
  346.     $u_hostfile ||= $ssh->{config}->get('user_known_hosts');
  347.     $s_hostfile ||= $ssh->{config}->get('global_known_hosts');
  348.  
  349.     my $status = _check_host_in_hostfile($host, $u_hostfile, $key);
  350.     unless (defined $status && $status == HOST_OK) {
  351.         $status = _check_host_in_hostfile($host, $s_hostfile, $key);
  352.     }
  353.  
  354.     if ($status == HOST_OK) {
  355.         $ssh->debug("Host '$host' is known and matches the host key.");
  356.     }
  357.     elsif ($status == HOST_NEW) {
  358.         if ($ssh->{config}->get('interactive')) {
  359.             my $prompt =
  360. qq(The authenticity of host '$host' can't be established.
  361. Key fingerprint is @{[ $key->fingerprint ]}.
  362. Are you sure you want to continue connecting (yes/no)?);
  363.             unless (_read_yes_or_no($prompt, "yes")) {
  364.                 croak "Aborted by user!";
  365.             }
  366.         }
  367.         $ssh->debug("Permanently added '$host' to the list of known hosts.");
  368.         _add_host_to_hostfile($host, $u_hostfile, $key);
  369.     }
  370.     else {
  371.         croak "Host key for '$host' has changed!";
  372.     }
  373. }
  374.  
  375. 1;
  376. __END__
  377.  
  378. =head1 NAME
  379.  
  380. Net::SSH::Perl - Perl client Interface to SSH
  381.  
  382. =head1 SYNOPSIS
  383.  
  384.     use Net::SSH::Perl;
  385.     my $ssh = Net::SSH::Perl->new($host);
  386.     $ssh->login($user, $pass);
  387.     my($stdout, $stderr, $exit) = $ssh->cmd($cmd);
  388.  
  389. =head1 DESCRIPTION
  390.  
  391. I<Net::SSH::Perl> is an all-Perl module implementing an SSH
  392. (Secure Shell) client. It is compatible with both the SSH-1 and
  393. SSH-2 protocols.
  394.  
  395. I<Net::SSH::Perl> enables you to simply and securely execute commands
  396. on remote machines, and receive the STDOUT, STDERR, and exit status
  397. of that remote command. It contains built-in support for various
  398. methods of authenticating with the server (password authentication,
  399. RSA challenge-response authentication, etc.). It completely implements
  400. the I/O buffering, packet transport, and user authentication layers
  401. of the SSH protocol, and makes use of external Perl libraries (in
  402. the Crypt:: family of modules) to handle encryption of all data sent
  403. across the insecure network. It can also read your existing SSH
  404. configuration files (F</etc/ssh_config>, etc.), RSA identity files,
  405. DSA identity files, known hosts files, etc.
  406.  
  407. One advantage to using I<Net::SSH::Perl> over wrapper-style
  408. implementations of ssh clients is that it saves on process
  409. overhead: you no longer need to fork and execute a separate process
  410. in order to connect to an sshd. Depending on the amount of time
  411. and memory needed to fork a process, this win can be quite
  412. substantial; particularly if you're running in a persistent
  413. Perl environment (I<mod_perl>, for example), where forking a new
  414. process is a drain on process and memory resources.
  415.  
  416. It also simplifies the process of using password-based authentications;
  417. when writing a wrapper around I<ssh> you probably need to use
  418. I<Expect> to control the ssh client and give it your password.
  419. I<Net::SSH::Perl> has built-in support for the authentication
  420. protocols, so there's no longer any hassle of communicating with
  421. any external processes.
  422.  
  423. The SSH2 protocol support (present in I<Net::SSH::Perl> as of version
  424. 1.00) is compatible with the SSH2 implementation in OpenSSH, and should
  425. also be fully compatible with the "official" SSH implementation. If
  426. you find an SSH2 implementation that is not compatible with
  427. I<Net::SSH::Perl>, please let me know (email address down in
  428. I<AUTHOR & COPYRIGHTS>); it turns out that some SSH2 implementations
  429. have subtle differences from others. 3DES (C<3des-cbc>), Blowfish
  430. (C<blowfish-cbc>), and RC4 (C<arcfour>) ciphers are currently
  431. supported for SSH2 encryption, and integrity checking is performed
  432. by either the C<hmac-sha1> or C<hmac-md5> algorithms. Compression, if
  433. requested, is limited to Zlib. Supported server host key algorithms
  434. are C<ssh-dss> (the default) and C<ssh-rsa> (requires I<Crypt::RSA>);
  435. supported SSH2 public key authentication algorithms are the same.
  436.  
  437. If you're looking for SFTP support, take a look at I<Net::SFTP>,
  438. which provides a full-featured Perl implementation of SFTP, and
  439. sits on top of I<Net::SSH::Perl>. SFTP requires the usage of the
  440. SSH2 protocol.
  441.  
  442. =head1 BASIC USAGE
  443.  
  444. Usage of I<Net::SSH::Perl> is very simple.
  445.  
  446. =head2 Net::SSH::Perl->new($host, %params)
  447.  
  448. To set up a new connection, call the I<new> method, which
  449. connects to I<$host> and returns a I<Net::SSH::Perl> object.
  450.  
  451. I<new> accepts the following named parameters in I<%params>:
  452.  
  453. =over 4
  454.  
  455. =item * protocol
  456.  
  457. The protocol you wish to use for the connection: should be either
  458. C<2>, C<1>, C<'1,2'> or C<'2,1'>. The first two say, quite simply,
  459. "only use this version of the protocol" (SSH-2 or SSH-1, respectively).
  460. The latter two specify that either protocol can be used, but that
  461. one protocol (the first in the comma-separated list) is preferred
  462. over the other.
  463.  
  464. For this reason, it's "safer" to use the latter two protocol
  465. specifications, because they ensure that either way, you'll be able
  466. to connect; if your server doesn't support the first protocol listed,
  467. the second will be used. (Presumably your server will support at
  468. least one of the two protocols. :)
  469.  
  470. The default value is C<'1,2'>, for compatibility with OpenSSH; this
  471. means that the client will use SSH-1 if the server supports SSH-1.
  472. Of course, you can always override this using a user/global
  473. configuration file, or through using this constructor argument.
  474.  
  475. =item * cipher
  476.  
  477. Specifies the name of the encryption cipher that you wish to
  478. use for this connection. This must be one of the supported
  479. ciphers; specifying an unsupported cipher will give you an error
  480. when you enter algorithm negotiation (in either SSH-1 or SSH-2).
  481.  
  482. In SSH-1, the supported cipher names are I<IDEA>, I<DES>, I<DES3>,
  483. and I<Blowfish>; in SSH-2, the supported ciphers are I<arcfour>,
  484. I<blowfish-cbc>, and I<3des-cbc>.
  485.  
  486. The default SSH-1 cipher is I<IDEA>; the default SSH-2 cipher is
  487. I<3des-cbc>.
  488.  
  489. =item * ciphers
  490.  
  491. Like I<cipher>, this is a method of setting the cipher you wish to
  492. use for a particular SSH connection; but this corresponds to the
  493. I<Ciphers> configuration option, where I<cipher> corresponds to
  494. I<Cipher>. This also applies only in SSH-2.
  495.  
  496. This should be a comma-separated list of SSH-2 cipher names; the list
  497. of cipher names is listed above in I<cipher>.
  498.  
  499. This defaults to I<3des-cbc,blowfish-cbc,arcfour>.
  500.  
  501. =item * port
  502.  
  503. The port of the I<sshd> daemon to which you wish to connect;
  504. if not specified, this is assumed to be the default I<ssh>
  505. port.
  506.  
  507. =item * debug
  508.  
  509. Set to a true value if you want debugging messages printed
  510. out while the connection is being opened. These can be helpful
  511. in trying to determine connection problems, etc. The messages
  512. are similar (and in some cases exact) to those written out by
  513. the I<ssh> client when you use the I<-v> option.
  514.  
  515. Defaults to false.
  516.  
  517. =item * interactive
  518.  
  519. Set to a true value if you're using I<Net::SSH::Perl> interactively.
  520. This is used in determining whether or not to display password
  521. prompts, for example. It's basically the inverse of the
  522. I<BatchMode> parameter in ssh configuration.
  523.  
  524. Defaults to false.
  525.  
  526. =item * privileged
  527.  
  528. Set to a true value if you want to bind to a privileged port
  529. locally. You'll need this if you plan to use Rhosts or
  530. Rhosts-RSA authentication, because the remote server
  531. requires the client to connect on a privileged port. Of course,
  532. to bind to a privileged port you'll need to be root.
  533.  
  534. If you don't provide this parameter, and I<Net::SSH::Perl>
  535. detects that you're running as root, this will automatically
  536. be set to true. Otherwise it defaults to false.
  537.  
  538. =item * identity_files
  539.  
  540. A list of RSA/DSA identity files to be used in RSA/DSA authentication.
  541. The value of this argument should be a reference to an array of
  542. strings, each string identifying the location of an identity
  543. file. Each identity file will be tested against the server until
  544. the client finds one that authenticates successfully.
  545.  
  546. If you don't provide this, RSA authentication defaults to using
  547. F<$ENV{HOME}/.ssh/identity>, and DSA authentication defaults to
  548. F<$ENV{HOME}/.ssh/id_dsa>.
  549.  
  550. =item * compression
  551.  
  552. If set to a true value, compression is turned on for the session
  553. (assuming that the server supports it).
  554.  
  555. Compression is off by default.
  556.  
  557. Note that compression requires that you have the I<Compress::Zlib>
  558. module installed on your system. If the module can't be loaded
  559. successfully, compression is disabled; you'll receive a warning
  560. stating as much if you having debugging on (I<debug> set to 1),
  561. and you try to turn on compression.
  562.  
  563. =item * compression_level
  564.  
  565. Specifies the compression level to use if compression is enabled
  566. (note that you must provide both the I<compression> and
  567. I<compression_level> arguments to set the level; providing only
  568. this argument will not turn on encryption).
  569.  
  570. This setting is only applicable to SSH-1; the compression level for
  571. SSH-2 Zlib compression is always set to 6.
  572.  
  573. The default value is 6.
  574.  
  575. =item * use_pty
  576.  
  577. Set this to 1 if you want to request a pseudo tty on the remote
  578. machine. This is really only useful if you're setting up a shell
  579. connection (see the I<shell> method, below); and in that case,
  580. unless you've explicitly declined a pty (by setting I<use_pty>
  581. to 0), this will be set automatically to 1. In other words,
  582. you probably won't need to use this, often.
  583.  
  584. The default is 1 if you're starting up a shell, and 0 otherwise.
  585.  
  586. =item * options
  587.  
  588. Used to specify additional options to the configuration settings;
  589. useful for specifying options for which there is no separate
  590. constructor argument. This is analogous to the B<-o> command line
  591. flag to the I<ssh> program.
  592.  
  593. If used, the value should be a reference to a list of option
  594. directives in the format used in the config file. For example:
  595.  
  596.     my $ssh = Net::SSH::Perl->new("host", options => [
  597.         "BatchMode yes", "RhostsAuthentication no" ]);
  598.  
  599. =back
  600.  
  601. =head2 $ssh->login([ $user [, $password ] ])
  602.  
  603. Sets the username and password to be used when authenticating
  604. with the I<sshd> daemon. The username I<$user> is required for
  605. all authentication protocols (to identify yourself to the
  606. remote server), but if you don't supply it the username of the
  607. user executing the program is used.
  608.  
  609. The password I<$password> is needed only for password
  610. authentication (it's not used for passphrases on encrypted
  611. RSA/DSA identity files, though perhaps it should be). And if you're
  612. running in an interactive session and you've not provided a
  613. password, you'll be prompted for one.
  614.  
  615. =head2 ($out, $err, $exit) = $ssh->cmd($cmd, [ $stdin ])
  616.  
  617. Runs the command I<$cmd> on the remote server and returns
  618. the I<stdout>, I<stderr>, and exit status of that
  619. command.
  620.  
  621. If I<$stdin> is provided, it's supplied to the remote command
  622. I<$cmd> on standard input.
  623.  
  624. NOTE: the SSH-1 protocol does not support running multiple commands
  625. per connection, unless those commands are chained together so that
  626. the remote shell can evaluate them. Because of this, a new socket
  627. connection is created each time you call I<cmd>, and disposed of
  628. afterwards. In other words, this code:
  629.  
  630.     my $ssh = Net::SSH::Perl->new("host1");
  631.     $ssh->login("user1", "pass1");
  632.  
  633.     $ssh->cmd("foo");
  634.     $ssh->cmd("bar");
  635.  
  636. will actually connect to the I<sshd> on the first invocation of
  637. I<cmd>, then disconnect; then connect again on the second
  638. invocation of I<cmd>, then disconnect again.
  639.  
  640. Note that this does I<not> apply to the SSH-2 protocol. SSH-2 fully
  641. supports running more than one command over the same connection.
  642.  
  643. =head2 $ssh->shell
  644.  
  645. Opens up an interactive shell on the remote machine and connects
  646. it to your STDIN. This is most effective when used with a
  647. pseudo tty; otherwise you won't get a command line prompt,
  648. and it won't look much like a shell. For this reason--unless
  649. you've specifically declined one--a pty will be requested
  650. from the remote machine, even if you haven't set the I<use_pty>
  651. argument to I<new> (described above).
  652.  
  653. This is really only useful in an interactive program.
  654.  
  655. In addition, you'll probably want to set your terminal to raw
  656. input before calling this method. This lets I<Net::SSH::Perl>
  657. process each character and send it off to the remote machine,
  658. as you type it.
  659.  
  660. To do so, use I<Term::ReadKey> in your program:
  661.  
  662.     use Term::ReadKey;
  663.     ReadMode('raw');
  664.     $ssh->shell;
  665.     ReadMode('restore');
  666.  
  667. In fact, you may want to place the C<restore> line in an I<END>
  668. block, in case your program exits prior to reaching that line.
  669.  
  670. If you need an example, take a look at F<eg/pssh>, which
  671. uses almost this exact code to implement an ssh shell.
  672.  
  673. =head2 $ssh->register_handler($packet_type, $subref [, @args ])
  674.  
  675. Registers an anonymous subroutine handler I<$subref> to handle
  676. packets of type I<$packet_type> during the client loop. The
  677. subroutine will be called when packets of type I<$packet_type>
  678. are received, and in addition to the standard arguments (see
  679. below), will receive any additional arguments in I<@args>, if
  680. specified.
  681.  
  682. The client loop is entered after the client has sent a command
  683. to the remote server, and after any STDIN data has been sent;
  684. it consists of reading packets from the server (STDOUT
  685. packets, STDERR packets, etc.) until the server sends the exit
  686. status of the command executed remotely. At this point the client
  687. exits the client loop and disconnects from the server.
  688.  
  689. When you call the I<cmd> method, the client loop by default
  690. simply sticks STDOUT packets into a scalar variable and returns
  691. that value to the caller. It does the same for STDERR packets,
  692. and for the process exit status. (See the docs for I<cmd>).
  693.  
  694. You can, however, override that default behavior, and instead
  695. process the data itself as it is sent to the client. You do this
  696. by calling the I<register_handler> method and setting up handlers
  697. to be called at specific times.
  698.  
  699. The behavior of the I<register_handler> method differs between
  700. the I<Net::SSH::Perl> SSH-1 and SSH-2 implementations. This is so
  701. because of the differences between the protocols (all 
  702. client-server communications in SSH-2 go through the channel
  703. mechanism, which means that input packets are processed
  704. differently).
  705.  
  706. =over 4
  707.  
  708. =item * SSH-1 Protocol
  709.  
  710. In the SSH-1 protocol, you should call I<register_handler> with two
  711. arguments: a packet type I<$packet_type> and a subroutine reference
  712. I<$subref>. Your subroutine will receive as arguments the
  713. I<Net::SSH::Perl::SSH1> object (with an open connection to the
  714. ssh3), and a I<Net::SSH::Perl::Packet> object, which represents the
  715. packet read from the server. It will also receive any additional
  716. arguments I<@args> that you pass to I<register_handler>; this can
  717. be used to give your callback functions access to some of your
  718. otherwise private variables, if desired. I<$packet_type> should be
  719. an integer constant; you can import the list of constants into your
  720. namespace by explicitly loading the I<Net::SSH::Perl::Constants>
  721. module:
  722.  
  723.     use Net::SSH::Perl::Constants qw( :msg );
  724.  
  725. This will load all of the I<MSG> constants into your namespace
  726. so that you can use them when registering the handler. To do
  727. that, use this method. For example:
  728.  
  729.     $ssh->register_handler(SSH_SMSG_STDOUT_DATA, sub {
  730.         my($ssh, $packet) = @_;
  731.         print "I received this: ", $packet->get_str;
  732.     });
  733.  
  734. To learn about the methods that you can call on the packet object,
  735. take a look at the I<Net::SSH::Perl::Packet> docs, as well as the
  736. I<Net::SSH::Perl::Buffer> docs (the I<get_*> and I<put_*> methods).
  737.  
  738. Obviously, writing these handlers requires some knowledge of the
  739. contents of each packet. For that, read through the SSH RFC, which
  740. explains each packet type in detail. There's a I<get_*> method for
  741. each datatype that you may need to read from a packet.
  742.  
  743. Take a look at F<eg/remoteinteract.pl> for an example of interacting
  744. with a remote command through the use of I<register_handler>.
  745.  
  746. =item * SSH-2 Protocol
  747.  
  748. In the SSH-2 protocol, you call I<register_handler> with two
  749. arguments: a string identifying the type of handler you wish to
  750. create, and a subroutine reference. The "string" should be, at
  751. this point, either C<stdout> or C<stderr>; any other string will
  752. be silently ignored. C<stdout> denotes that you wish to handle
  753. STDOUT data sent from the server, and C<stderr> that you wish
  754. to handle STDERR data.
  755.  
  756. Your subroutine reference will be passed two arguments:
  757. a I<Net::SSH::Perl::Channel> object that represents the open
  758. channel on which the data was sent, and a I<Net::SSH::Perl::Buffer>
  759. object containing data read from the server. In addition to these
  760. two arguments, the callback will be passed any additional
  761. arguments I<@args> that you passed to I<register_handler>; this
  762. can be used to give your callback functions to otherwise private
  763. variables, if desired.
  764.  
  765. This illustrates the two main differences between the SSH-1 and
  766. SSH-2 implementations. The first difference is that, as mentioned
  767. above, all communication between server and client is done through
  768. channels, which are built on top of the main connection between
  769. client and server. Multiple channels are multiplexed over the
  770. same connection. The second difference is that, in SSH-1, you are
  771. processing the actual packets as they come in; in SSH-2, the packets
  772. have already been processed somewhat, and their contents stored in
  773. buffers--you are processing those buffers.
  774.  
  775. The above example (the I<I received this> example) of using
  776. I<register_handler> in SSH-1 would look like this in SSH-2:
  777.  
  778.     $ssh->register_handler("stdout", sub {
  779.         my($channel, $buffer) = @_;
  780.         print "I received this: ", $buffer->bytes;
  781.     });
  782.  
  783. As you can see, it's quite similar to the form used in SSH-1,
  784. but with a few important differences, due to the differences
  785. mentioned above between SSH-1 and SSH-2.
  786.  
  787. =back
  788.  
  789. =head1 ADVANCED METHODS
  790.  
  791. Your basic SSH needs will hopefully be met by the methods listed
  792. above. If they're not, however, you may want to use some of the
  793. additional methods listed here. Some of these are aimed at
  794. end-users, while others are probably more useful for actually
  795. writing an authentication module, or a cipher, etc.
  796.  
  797. =head2 $ssh->config
  798.  
  799. Returns the I<Net::SSH::Perl::Config> object managing the
  800. configuration data for this SSH object. This is constructed
  801. from data passed in to the constructor I<new> (see above),
  802. merged with data read from the user and system configuration
  803. files. See the I<Net::SSH::Perl::Config> docs for details
  804. on methods you can call on this object (you'll probably
  805. be more interested in the I<get> and I<set> methods).
  806.  
  807. =head2 $ssh->sock
  808.  
  809. Returns the socket connection to sshd. If your client is not
  810. connected, dies.
  811.  
  812. =head2 $ssh->debug($msg)
  813.  
  814. If debugging is turned on for this session (see the I<debug>
  815. parameter to the I<new> method, above), writes I<$msg> to
  816. C<STDERR>. Otherwise nothing is done.
  817.  
  818. =head2 $ssh->incoming_data
  819.  
  820. Incoming data buffer, an object of type I<Net::SSH::Perl::Buffer>.
  821. Returns the buffer object.
  822.  
  823. The idea behind this is that we our socket is non-blocking, so we
  824. buffer input and periodically check back to see if we've read a
  825. full packet. If we have a full packet, we rip it out of the incoming
  826. data buffer and process it, returning it to the caller who
  827. presumably asked for it.
  828.  
  829. This data "belongs" to the underlying packet layer in
  830. I<Net::SSH::Perl::Packet>. Unless you really know what you're
  831. doing you probably don't want to disturb that data.
  832.  
  833. =head2 $ssh->session_id
  834.  
  835. Returns the session ID, which is generated from the server's
  836. host and server keys, and from the check bytes that it sends
  837. along with the keys. The server may require the session ID to
  838. be passed along in other packets, as well (for example, when
  839. responding to RSA challenges).
  840.  
  841. =head2 $packet = $ssh->packet_start($packet_type)
  842.  
  843. Starts building a new packet of type I<$packet_type>. This is
  844. just a handy method for lazy people. Internally it calls
  845. I<Net::SSH::Perl::Packet::new>, so take a look at those docs
  846. for more details.
  847.  
  848. =head1 SUPPORT
  849.  
  850. For samples/tutorials, take a look at the scripts in F<eg/> in
  851. the distribution directory.
  852.  
  853. There is a mailing list for development discussion and usage
  854. questions.  Posting is limited to subscribers only.  You can sign up
  855. at http://lists.sourceforge.net/lists/listinfo/ssh-sftp-perl-users
  856.  
  857. Please report all bugs via rt.cpan.org at
  858. https://rt.cpan.org/NoAuth/ReportBug.html?Queue=net%3A%3Assh%3A%3Aperl
  859.  
  860. =head1 AUTHOR
  861.  
  862. Current maintainer is Dave Rolsky, autarch@urth.org.
  863.  
  864. Originally written by Benjamin Trott.
  865.  
  866. =head1 COPYRIGHT
  867.  
  868. Copyright (c) 2001 Benjamin Trott, Copyright (c) 2003 David Rolsky.
  869. All rights reserved.  This program is free software; you can
  870. redistribute it and/or modify it under the same terms as Perl itself.
  871.  
  872. The full text of the license can be found in the LICENSE file included
  873. with this module.
  874.  
  875. =cut
  876.