Ludovico Stevens > Control-CLI-2.00 > Control::CLI

Download:
Control-CLI-2.00.tar.gz

Dependencies

Annotate this POD

CPAN RT

Open  0
View/Report Bugs
Module Version: 2.00   Source  

NAME ^

Control::CLI - Command Line Interface I/O over either Telnet or SSH (IPv4 & IPv6) or Serial port

SYNOPSIS ^

Telnet access

        use Control::CLI;
        # Create the object instance for Telnet
        $cli = new Control::CLI('TELNET');
        # Connect to host
        $cli->connect('hostname');
        # Perform login
        $cli->login(    Username        => $username,
                        Password        => $password,
                   );
        # Send a command and read the resulting output
        $output = $cli->cmd("command");
        print $output;
        $cli->disconnect;

SSH access

        use Control::CLI;
        # Create the object instance for SSH
        $cli = new Control::CLI('SSH');
        # Connect to host - Note that with SSH,
        #  authentication is normally part of the connection process
        $cli->connect(  Host            => 'hostname',
                        Username        => $username,
                        Password        => $password,
                        PublicKey       => '.ssh/id_dsa.pub',
                        PrivateKey      => '.ssh/id_dsa',
                        Passphrase      => $passphrase,
                     );
        # In some rare cases, may need to use login
        #  if remote device accepted an SSH connection without any authentication
        #  and expects an interactive login/password authentication
        $cli->login(Password => $password);
        # Send a command and read the resulting output
        $output = $cli->cmd("command");
        print $output;
        $cli->disconnect;

Serial port access

        use Control::CLI;
        # Create the object instance for Serial port e.g. /dev/ttyS0 or COM1
        $cli = new Control::CLI('/dev/ttyS0');
        # Connect to host
        $cli->connect(  BaudRate        => 9600,
                        Parity          => 'none',
                        DataBits        => 8,
                        StopBits        => 1,
                        Handshake       => 'none',
                     );
        # Send some character sequence to wake up the other end, e.g. a carriage return
        $cli->print;
        # Perform login
        $cli->login(    Username        => $username,
                        Password        => $password,
                   );
        # Send a command and read the resulting output
        $output = $cli->cmd("command");
        print $output;
        $cli->disconnect;

Driving multiple Telnet/SSH connections simultaneously in non-blocking mode

        use Control::CLI qw(poll);                      # Export class poll method
        # Create all the object instances
        foreach my $host (@DeviceIPs) {
                $cli{$host} = new Control::CLI(
                        Use             => 'SSH',       # or TELNET (or lots of serial ports!)
                        Blocking        => 0,           # Use non-blocking mode
        }

        print "Connecting to multiple hosts ";
        foreach my $host (@DeviceIPs) {
                $cli{$host}->connect(
                        Host            =>      $host,
                        Username        =>      $username,
                        Password        =>      $password,
                );
        }
        poll(   # Poll all objects for completion of connect
                Object_list     =>      \%cli,
                Poll_code       =>      sub { local $| = 1; print '.' },
        );
        print " done!\n";

        print "Logging in to multiple hosts ";
        foreach my $host (@DeviceIPs) {
                $cli{$host}->login(
                        Username        =>      $username,
                        Password        =>      $password,
                );
        }
        poll(   # Poll all objects for completion of login
                Object_list     =>      \%cli,
                Poll_code       =>      sub { local $| = 1; print '.' },
        );
        print " done!\n";

        print "Sending same command to multiple hosts ";
        foreach my $host (@DeviceIPs) {
                $cli{$host}->cmd($cmd);
        }
        poll(   # Poll all objects for completion of cmd
                Object_list     =>      \%cli,
                Poll_code       =>      sub { local $| = 1; print '.' },
        );
        print " done!\n";

        # Disconnect from all hosts
        foreach my $host (@DeviceIPs) {
                $cli{$host}->disconnect;
        }

DESCRIPTION ^

A Command Line Interface (CLI) is an interface where the user is presented with a command prompt and has to enter ASCII commands to drive or control or configure that device. That interface could be the shell on a unix system or some other command interpreter on a device such as an ethernet switch or an IP router or some kind of security appliance.

Control::CLI allows CLI connections to be made over any of Telnet, SSH or Serial port. Connection and basic I/O can be performed in a consistent manner regardless of the underlying connection type thus allowing CLI based scripts to be easily converted between or operate over any of Telnet, SSH or Serial port connection. Control::CLI relies on these underlying modules:

Since all of the above are Perl standalone modules (which do not rely on external binaries) scripts using Control::CLI can easily be ported to any OS platform (where either Perl is installed or by simply packaging the Perl script into an executable with PAR::Packer's pp). In particular this is a big advantage for portability to Windows platforms where using Expect scripts is usually not possible.

All the above modules are optional, however if one of the modules is missing then no access of that type will be available. For instance if Win32::SerialPort is not installed (on a Windows system) but both Net::Telnet and Net::SSH2 are, then Control::CLI will be able to operate over both Telnet and SSH, but not Serial port. There has to be, however, at least one of the Telnet/SSH/SerialPort modules installed, otherwise Control::CLI's constructor will throw an error.

Net::Telnet and Net::SSH2 both natively use IO::Socket::INET which only provides IPv4 support; if however IO::Socket::IP is installed, this class will use it as a drop in replacement to IO::Socket::INET and allow both Telnet and SSH connections to operate over IPv6 as well as IPv4.

Net::SSH2 only supports SSHv2 and this class will always and only use Net::SSH2 to establish a channel over which an interactive shell is established with the remote host. Authentication methods supported are 'publickey', 'password' and 'keyboard-interactive'.

As of version 2.00, this module offers non-blocking capability on all of its methods (in the case of connect method, IO::Socket::IP is required). Scripts using this class can now drive multiple hosts simultaneusly without resorting to Perl threads. See the non-blocking example section at the end.

In the syntax layout below, square brackets [] represent optional parameters. All Control::CLI method arguments are case insensitive.

OBJECT CONSTRUCTOR ^

Used to create an object instance of Control::CLI

new() - create a new Control::CLI object
  $obj = new Control::CLI ('TELNET'|'SSH'|'<COM_port_name>');

  $obj = new Control::CLI (
        Use                      => 'TELNET'|'SSH'|'<COM_port_name>',
        [Timeout                 => $secs,]
        [Connection_timeout      => $secs,]
        [Errmode                 => $errmode,]
        [Return_reference        => $flag,]
        [Prompt                  => $prompt,]
        [Username_prompt         => $usernamePrompt,]
        [Password_prompt         => $passwordPrompt,]
        [Input_log               => $fhOrFilename,]
        [Output_log              => $fhOrFilename,]
        [Dump_log                => $fhOrFilename,]
        [Blocking                => $flag,]
        [Prompt_credentials      => $flag,]
        [Read_attempts           => $numberOfReadAttemps,]
        [Readwait_timer          => $millisecs,]
        [Read_block_size         => $bytes,]
        [Output_record_separator => $ors,]
        [Debug                   => $debugFlag,]
  );

This is the constructor for Control::CLI objects. A new object is returned on success. On failure the error mode action defined by "errmode" argument is performed. If the "errmode" argument is not specified the default is to croak. See errmode() for a description of valid settings. The first parameter, or "use" argument, is required and should take value either "TELNET" or "SSH" (case insensitive) or the name of the Serial port such as "COM1" or "/dev/ttyS0". In the second form, the other arguments are optional and are just shortcuts to methods of the same name.

OBJECT METHODS ^

Methods which can be run on a previously created Control::CLI object instance

Main I/O Object Methods

connect() & connect_poll() - connect to host
  $ok = $obj->connect($host [$port]);

  $ok = $obj->connect($host[:$port]); # Deprecated

  $ok = $obj->connect(
        [Host                   => $host,]
        [Port                   => $port,]
        [Username               => $username,]
        [Password               => $password,]
        [PublicKey              => $publicKey,]
        [PrivateKey             => $privateKey,]
        [Passphrase             => $passphrase,]
        [Prompt_credentials     => $flag,]
        [BaudRate               => $baudRate,]
        [Parity                 => $parity,]
        [DataBits               => $dataBits,]
        [StopBits               => $stopBits,]
        [Handshake              => $handshake,]
        [Connection_timeout     => $secs,]
        [Blocking               => $flag,]
        [Errmode                => $errmode,]
  );

  $ok = $obj->connect_poll();   # Only applicable in non-blocking mode

This method connects to the host device. The connection will use either Telnet, SSH or Serial port, depending on how the object was created with the new() constructor. On success a true (1) value is returned. In non-blocking mode (blocking disabled) the connect() method will immediately return with a false, but defined, value of 0. You will then need to call the connect_poll() method at regular intervals until it returns a true (1) value indicating that the connection is complete. Note that for this method to work in non-blocking mode IO::Socket::IP needs to be installed (IO::Socket:INET will always produce a blocking connection call). On connection timeout or other connection failures the error mode action is performed. See errmode(). The deprecated shorthand syntax is still accepted but it will not work if $host is an IPv6 address. The optional "errmode", "connection_timeout" and "blocking" arguments are provided to override the global setting of the corresponding object parameter. When a "connection_timeout" is defined, this will be used to enforce a connection timeout for Telnet and SSH TCP socket connections. Which arguments are used depends on the whether the object was created for Telnet, SSH or Serial port. The "host" argument is required by both Telnet and SSH. The other arguments are optional.

  • For Telnet, these forms are allowed with the following arguments:
      $ok = $obj->connect($host [$port]);
    
      $ok = $obj->connect($host[:$port]); # Deprecated
    
      $ok = $obj->connect(
            Host                    => $host,
            [Port                   => $port,]
            [Connection_timeout     => $secs,]
            [Blocking               => $flag,]
            [Errmode                => $errmode,]
      );

    If not specified, the default port number for Telnet is 23

  • For SSH, these forms are allowed with the following arguments:
      $ok = $obj->connect($host [$port]);
    
      $ok = $obj->connect($host[:$port]); # Deprecated
    
      $ok = $obj->connect(
            Host                    => $host,
            [Port                   => $port,]
            [Username               => $username,]
            [Password               => $password,]
            [PublicKey              => $publicKey,]
            [PrivateKey             => $privateKey,]
            [Passphrase             => $passphrase,]
            [Prompt_credentials     => $flag,]
            [Connection_timeout     => $secs,]
            [Blocking               => $flag,]
            [Errmode                => $errmode,]
      );

    If not specified, the default port number for SSH is 22. A username must always be provided for all SSH connections. If not provided and prompt_credentials is true then this method will prompt for it. Once the SSH connection is established, this method will attempt one of two possible authentication types, based on the accepted authentications of the remote host:

    • Publickey authentication : If the remote host accepts it and the method was supplied with public/private keys. The public/private keys need to be in OpenSSH format. If the private key is protected by a passphrase then this must also be provided or, if prompt_credentials is true, this method will prompt for the passphrase. If publickey authentication fails for any reason and password authentication is possible, then password authentication is attempted next; otherwise the error mode action is performed. See errmode().
    • Password authentication : If the remote host accepts either 'password' or 'keyboard-interactive' authentication methods. A password must be provided or, if prompt_credentials is true, this method will prompt for the password. If password authentication fails for any reason the error mode action is performed. See errmode(). The SSH 'keyboard-interactive' authentication method is supported to match the functionality of 'password' authentication on hosts where the latter is not accepted. Use of either of these SSH authentication methods (which both ultimately provide username & password credentials to the SSH server) remains completely transparent to the code using this class.

    There are some devices, with a crude SSH implementation, which will accept an SSH connection without any SSH authentication, and then perform an interactive login, like Telnet does. In this case, the connect() method, will not perform any SSH authentication and will return success after simply bringing up the SSH connection; but in this case you will most likely have to complete the login authentication by calling the login() method as you would do with Telnet and Serial port connections.

    The optional "prompt_credentials" argument is provided to override the global setting of the parameter by the same name which is by default false. See prompt_credentials().

  • For Serial port, these arguments are used:
      $ok = $obj->connect(
            [BaudRate               => $baudRate,]
            [Parity                 => $parity,]
            [DataBits               => $dataBits,]
            [StopBits               => $stopBits,]
            [Handshake              => $handshake,]
            [Blocking               => $flag,]      # Ignored
            [Errmode                => $errmode,]
      );

    If arguments are not specified, the defaults are: Baud Rate = 9600, Data Bits = 8, Parity = none, Stop Bits = 1, Handshake = none. Allowed values for these arguments are the same allowed by underlying Win32::SerialPort / Device::SerialPort:

    • Baud Rate : Any legal value
    • Parity : One of the following: "none", "odd", "even", "mark", "space"
    • Data Bits : An integer from 5 to 8
    • Stop Bits : Legal values are 1, 1.5, and 2. But 1.5 only works with 5 databits, 2 does not work with 5 databits, and other combinations may not work on all hardware if parity is also used
    • Handshake : One of the following: "none", "rts", "xoff", "dtr"

    Remember that when connecting over the serial port, the device at the far end is not necessarily alerted that the connection is established. So it might be necessary to send some character sequence (usually a carriage return) over the serial connection to wake up the far end. This can be achieved with a simple print() immediately after connect().

If using the connect() method in non-blocking mode, the following example illustrates how this works:

        $ok = $obj->connect(Host => $ip-address, Blocking => 0);
        until ($ok) { # This loop will be executed while $ok = 0
                
                <do other stuff here..>
        
                $ok = $obj->connect_poll;
        }

Or, if you have set an error mode action of 'return':

        $ok = $obj->connect(Host => $ip-address, Blocking => 0, Errmode => 'return');
        die $obj->errmsg unless defined $ok;    # Error connecting
        until ($ok) { # This loop will be executed while $ok = 0
                
                <do other stuff here..>
        
                $ok = $obj->connect_poll;
                die $obj->errmsg unless defined $ok;    # Error or timeout connecting
        }

Some considerations on using connect() in non-blocking mode:

  • There is no delay in establishing a serial port connection, so setting non-blocking mode has no effect on serial port connections and the connection will be established after the first call to connect()
  • For Telnet and SSH connections, if you provided $host as a hostname which needs to resolve via DNS, the DNS lookup will still be blocking. You will either need to supply $host as a direct IP addresses or else write your own non-blocking DNS lookup code (an example is offered in the IO::Socket::IP documentation & examples)
  • For SSH connections, only the TCP socket connection is treated in a true non-blocking fashion. SSH authentication will call Net::SSH2's auth_list(), auth_publickey() and/or auth_password() or auth_keyboard() which all behave in a blocking fashion; to alleviate this the connect() method will return between each of those SSH authentication steps
read() - read block of data from object
  $data || $dataref = $obj->read(
        [Blocking               => $flag,]
        [Timeout                => $secs,]
        [Return_reference       => $flag,]
        [Errmode                => $errmode,]
  );

This method reads a block of data from the object. If blocking is enabled - see blocking() - and no data is available, then the read method will wait for data until expiry of timeout - see timeout() -, then will perform the error mode action. See errmode(). If blocking is disabled and no data is available then the read method will return immediately (in this case the timeout and errmode arguments are not applicable).

In blocking mode, if no error or timeout, this method will always return a defined non-empty string.

In non-blocking mode, if no error and nothing was read, this method will always return a defined empty string.

In case of an error, and the error mode is 'return', this method will always return an undefined value.

The optional arguments are provided to override the global setting of the parameters by the same name for the duration of this method. Note that setting these arguments does not alter the global setting for the object. See also timeout(), blocking(), errmode(), return_reference(). Returns either a hard reference to any data read or the data itself, depending on the applicable setting of "return_reference". See return_reference().

readwait() - read in data initially in blocking mode, then perform subsequent non-blocking reads for more
  $data || $dataref = $obj->readwait(
        [Read_attempts          => $numberOfReadAttemps,]
        [Readwait_timer         => $millisecs,]
        [Blocking               => $flag,]
        [Timeout                => $secs,]
        [Return_reference       => $flag,]
        [Errmode                => $errmode,]
  );

If blocking is enabled - see blocking() - this method implements an initial blocking read followed by a number of non-blocking reads. The intention is that we expect to receive at least some data and then we wait a little longer to make sure we have all the data. This is useful when the input data stream has been fragmented into multiple packets; in this case the normal read() method (in blocking mode) will immediately return once the data from the first packet is received, while the readwait() method will return once all packets have been received. For the initial blocking read, if no data is available, the method will wait until expiry of timeout. If a timeout occurs, then the error mode action is performed as with the regular read() method in blocking mode. See errmode(). If blocking is disabled then no initial blocking read is performed, instead the method will move directly to the non-blocking reads (in this case the "timeout" and "errmode" arguments are not applicable). Once some data has been read or blocking is disabled, then the method will perform a number of non-blocking reads at certain time intervals to ensure that any subsequent data is also read before returning. The time interval is by default 100 milliseconds and can be either set via the readwait_timer() method or by specifying the optional "readwait_timer" argument which will override whatever value is globally set for the object. See readwait_timer(). The number of non-blocking reads is dependent on whether more data is received or not but a certain number of consecutive reads with no more data received will make the method return. By default that number is 5 and can be either set via the read_attempts() method or by specifying the optional "read_attempts" argument which will override whatever value is globally set for the object. See read_attempts(). Therefore note that this method will always introduce a delay of "readwait_timer" milliseconds times the value of "read_attempts" and faster response times can be obtained using the regular read() method. Returns either a hard reference to data read or the data itself, depending on the applicable setting of return_reference. See return_reference().

In blocking mode, if no error or timeout, this method will always return a defined non-empty string.

In non-blocking mode, if no error and nothing was read, this method will always return a defined empty string.

In case of an error, and the error mode is 'return', this method will always return an undefined value.

The optional arguments are provided to override the global setting of the parameters by the same name for the duration of this method. Note that setting these arguments does not alter the global setting for the object. See also read_attempts(), timeout(), errmode(), return_reference().

waitfor() & waitfor_poll() - wait for pattern in the input stream

Backward compatble syntax:

  $data || $dataref = $obj->waitfor($matchpat);

  ($data || $dataref, $match || $matchref) = $obj->waitfor($matchpat);

  $data || $dataref = $obj->waitfor(
        [Match                  => $matchpattern1,
         [Match                 => $matchpattern2,
          [Match                => $matchpattern3,
            ... ]]]
        [Blocking               => $flag,]
        [Timeout                => $secs,]
        [Return_reference       => $flag,]
        [Errmode                => $errmode,]
  );

  ($data || $dataref, $match || $matchref) = $obj->waitfor(
        [Match                  => $matchpattern1,
         [Match                 => $matchpattern2,
          [Match                => $matchpattern3,
            ... ]]]
        [Blocking               => $flag,]
        [Timeout                => $secs,]
        [Return_reference       => $flag,]
        [Errmode                => $errmode,]
  );

New syntax (for non-blocking use):

  $ok = $obj->waitfor(
        Poll_syntax             => 1,
        [Match                  => $matchpattern1,
         [Match                 => $matchpattern2,
          [Match                => $matchpattern3,
            ... ]]]
        [Blocking               => $flag,]
        [Timeout                => $secs,]
        [Return_reference       => $flag,]
        [Errmode                => $errmode,]
  );

  ($ok, $data || $dataref, $match) = $obj->waitfor(
        Poll_syntax             => 1,
        [Match                  => $matchpattern1,
         [Match                 => $matchpattern2,
          [Match                => $matchpattern3,
            ... ]]]
        [Blocking               => $flag,]
        [Timeout                => $secs,]
        [Return_reference       => $flag,]
        [Errmode                => $errmode,]
  );

Polling method (only applicable in non-blocking mode):

  $ok = $obj->waitfor_poll();

  ($ok, $data || $dataref, $match) = $obj->waitfor_poll();

This method reads until a pattern match or string is found in the input stream, or will timeout if no further data can be read. For backwards compatibility this method preserves the original syntax from Net::Telnet (as well as in versions prior to 2.00 of this class) where in scalar context returns any data read up to but excluding the matched string, while list context returns the same data read as well as the actual string which was matched. With the new syntax, in scalar context returns the poll status while in list context the poll status is returned together with the data read up to but excluding the matched string and actual string which was matched; in non-blocking mode the latter 2 will most likely be undefined and will need to be recovered by subsequent calling of waitfor_poll() method. To use the new syntax on the waitfor() method, the 'poll_syntax' argument needs to be set to 1; the waitfor_poll() method only uses the new syntax. On timeout or other failure the error mode action is performed. See errmode(). In the first two forms a single pattern match string can be provided; in the other forms any number of pattern match strings can be provided and the method will wait until a match is found against any of those patterns. In both cases the pattern match can be a simple string or any valid perl regular expression match string (in the latter case use single quotes when building the string). The optional arguments are provided to override the global setting of the parameters by the same name for the duration of this method. Note that setting these arguments does not alter the global setting for the object. See also timeout(), errmode(), return_reference(). Returns either hard reference or the data itself, depending on the applicable setting of return_reference. See return_reference(). In the legacy syntax this applied to both $data and $match strings. In the new poll sysntax this now only applies to the $data output while the $match string is always returned as a scalar. This method is similar (but not identical) to the method of the same name provided in Net::Telnet.

In non-blocking mode (blocking disabled) the waitfor() method will most likely immediately return with a false, but defined, value of 0. You will then need to call the waitfor_poll() method at regular intervals until it returns a true (1) value indicating that the match pattern has been hit. The following example illustrates:

        $ok = $obj->waitfor(Poll_syntax => 1, Match => "seeked regex patterns", Blocking => 0);
        until ($ok) { # This loop will be executed while $ok = 0
                
                <do other stuff here..>
        
                $ok = $obj->waitfor_poll;
        }
        print "Output data up to but excluding match string:", ($obj->waitfor_poll)[1];
        print "Matched string:", ($obj->waitfor_poll)[2];
        # In this order, otherwise output [1] would get flushed while reading just [2]
put() - write data to object
  $ok = $obj->put($string);

  $ok = $obj->put(
        String                  => $string,
        [Errmode                => $errmode,]
  );

This method writes $string to the object and returns a true (1) value if all data was successfully written. On failure the error mode action is performed. See errmode(). This method is like print($string) except that no trailing character (usually a newline "\n") is appended.

print() - write data to object with trailing output_record_separator
  $ok = $obj->print($line);

  $ok = $obj->print(
        [Line                   => $line,]
        [Errmode                => $errmode,]
  );

This method writes $line to the object followed by the output record separator which is usually a newline "\n" - see output_record_separator() - and returns a true (1) value if all data was successfully written. If the method is called with no $line string then only the output record separator is sent. On failure the error mode action is performed. See errmode(). To avoid printing a trailing "\n" use put() instead.

printlist() - write multiple lines to object each with trailing output_record_separator
  $ok = $obj->printlist(@list);

This method writes every element of @list to the object followed by the output record separator which is usually a newline "\n" - see output_record_separator() - and returns a true (1) value if all data was successfully written. On failure the error mode action is performed. See errmode().

Note that most devices have a limited input buffer and if you try and send too many commands in this manner you risk losing some of them at the far end. It is safer to send commands one at a time using the cmd() method which will acknowledge each command as cmd() waits for a prompt after each command.

login() & login_poll() - handle login for Telnet / Serial port
  $ok = $obj->login(
        [Username               => $username,]
        [Password               => $password,]
        [Prompt_credentials     => $flag,]
        [Prompt                 => $prompt,]
        [Username_prompt        => $usernamePrompt,]
        [Password_prompt        => $passwordPrompt,]
        [Blocking               => $flag,]
        [Timeout                => $secs,]
        [Errmode                => $errmode,]
  );

  ($ok, $output || $outputRef) = $obj->login(
        [Username               => $username,]
        [Password               => $password,]
        [Prompt_credentials     => $flag,]
        [Prompt                 => $prompt,]
        [Username_prompt        => $usernamePrompt,]
        [Password_prompt        => $passwordPrompt,]
        [Blocking               => $flag,]
        [Timeout                => $secs,]
        [Return_reference       => $flag,]
        [Errmode                => $errmode,]
  );

Polling method (only applicable in non-blocking mode):

  $ok = $obj->login_poll();

  ($ok, $output || $outputRef) = $obj->login_poll();

This method handles login authentication for Telnet and Serial port access on a generic host. If a login/username prompt is seen, the supplied username is sent; if a password prompt is seen, the supplied password is sent; and once a valid CLI prompt is seen this method completes and returns a true (1) value. This method is usually not required for SSH, where authentication is part of the connection process, however there are some devices where the SSH connection is allowed without any SSH authentication and you might then need to handle an interactive authentication in the SSH channel data stream, in which case you would use login() also for SSH and only the password needs to be supplied as the username will have already have been supplied, and cached, in connect(). In any case calling login() on an SSH connection will allow the script to lock onto the very first CLI prompt received from the host. In the first form only a success/failure value is returned in scalar context, while in the second form, in list context, both the success/failure value is returned as well as any output received from the host device during the login sequence; the latter is either the output itself or a reference to that output, depending on the object setting of return_reference or the argument override provided in this method. For this method to succeed the username & password prompts from the remote host must match the default prompts defined for the object or the overrides specified via the optional "username_prompt" & "password_prompt" arguments. By default these regular expressions are set to:

        '(?i:username|login)[: ]+$'
        '(?i)password[: ]+$'

Following a successful authentication, if a valid CLI prompt is received, the method will return a true (1) value. The expected CLI prompt is either the globally set prompt - see prompt() - or the local override specified with the optional "prompt" argument. By default, the following prompt is expected:

        '.*[\?\$%#>]\s?$'

In non-blocking mode (blocking disabled) the login() method will most likely immediately return with a false, but defined, value of 0. You will then need to call the login_poll() method at regular intervals until it returns a true (1) value indicating that the login is complete. On timeout or failure or if the remote host prompts for the username a second time (the method assumes that the credentials provided were invalid) then the error mode action is performed. See errmode(). If username/password are not provided but are required and prompt_credentials is true, the method will automatically prompt the user for them interactively; otherwise the error mode action is performed. The optional "prompt_credentials" argument is provided to override the global setting of the parameter by the same name which is by default false. See prompt_credentials().

If using the login() method in non-blocking mode, the following examples illustrate how this works:

  • If you do not care to retrieve the login sequence output:
            $ok = $obj->login(Username => "admin", Password => "pwd", Blocking => 0);
            until ($ok) { # This loop will be executed while $ok = 0
                    
                    <do other stuff here..>
            
                    $ok = $obj->login_poll;
            }
  • If you want to retrieve the login output sequence along the way (even in case of error/timeout):
            ($ok, $output) = $obj->login(Username => "admin", Password => "pwd", Blocking => 0, Errmode => 'return');
            die $obj->errmsg unless defined $ok;    # Login failed
            until ($ok) {
                    
                    <do other stuff here..>
            
                    ($ok, $partialOutput) = $obj->login_poll;
                    die $obj->errmsg unless defined $ok;    # Login failed or timeout
                    $output .= $partialOutput;
            }
            print "Complete login sequence output:\n", $output;
  • If you only want to retrieve the full login sequence output at the end:
            $ok = $obj->login(Username => "admin", Password => "pwd", Blocking => 0);
            until ($ok) {
                    
                    <do other stuff here..>
            
                    $ok = $obj->login_poll;
            }
            print "Complete login sequence output:\n", ($obj->login_poll)[1];
cmd() & cmd_poll() - Sends a CLI command to host and returns output data

Backward compatible syntax:

  $output || $outputRef = $obj->cmd($cliCommand);

  $output || $outputRef = $obj->cmd(
        [Command                => $cliCommand,]
        [Prompt                 => $prompt,]
        [Blocking               => $flag,]
        [Timeout                => $secs,]
        [Return_reference       => $flag,]
        [Errmode                => $errmode,]
  );

New syntax (for non-blocking use):

  $ok = $obj->cmd(
        Poll_syntax             => 1,
        [Command                => $cliCommand,]
        [Prompt                 => $prompt,]
        [Blocking               => $flag,]
        [Timeout                => $secs,]
        [Errmode                => $errmode,]
  );

  ($ok, $output || $outputRef) = $obj->cmd($cliCommand);

  ($ok, $output || $outputRef) = $obj->cmd(
        [Poll_syntax            => 1,]
        [Command                => $cliCommand,]
        [Prompt                 => $prompt,]
        [Blocking               => $flag,]
        [Timeout                => $secs,]
        [Return_reference       => $flag,]
        [Errmode                => $errmode,]
  );

Polling method (only applicable in non-blocking mode):

  $ok = $obj->cmd_poll();

  ($ok, $output || $outputRef) = $obj->cmd_poll();

This method sends a CLI command to the host and returns once a new CLI prompt is received from the host. The output record separator - which is usually a newline "\n"; see output_record_separator() - is automatically appended to the command string. If no command string is provided then this method will simply send the output record separator and expect a new prompt back. Before sending the command to the host, any pending input data from host is read and flushed. The CLI prompt expected by the cmd() method is either the prompt defined for the object - see prompt() - or the override defined using the optional "prompt" argument. For backwards compatibility, in scalar context the output data from the command is returned. The new syntax, in scalar context returns the poll status, while in list context, both the poll status together with the output data are returned. Note that to disambiguate the new scalar context syntax the 'poll_syntax' argument needs to be set (while this is not strictly necessary in list context). In non-blocking mode, the poll status will most likely immediately return with a false, but defined, value of 0. You will then need to call the cmd_poll() method at regular intervals until it returns a true (1) value indicating that the command has completed.

The output data returned is either a hard reference to the output or the output itself, depending on the setting of return_reference; see return_reference(). The echoed command is automatically stripped from the output as well as the terminating CLI prompt (the last prompt received from the host device can be obtained with the last_prompt() method). This means that when sending a command which generates no output, either a null string or a reference pointing to a null string will be returned. On I/O failure to the host device, the error mode action is performed. See errmode(). If output is no longer received from the host and no valid CLI prompt has been seen, the method will timeout - see timeout() - and will then perform the error mode action. The cmd() method is equivalent to the following combined methods:

        $obj->read(Blocking => 0);
        $obj->print($cliCommand);
        $output = $obj->waitfor($obj->prompt);

In non-blocking mode (blocking disabled) the cmd() method will most likely immediately return with a false, but defined, value of 0. You will then need to call the cmd_poll() method at regular intervals until it returns a true (1) value indicating that the command is complete. The following example illustrates:

  • If you do not care to retrieve any output from the command:
            $ok = $obj->cmd(Command => "set command", Blocking => 0);
            until ($ok) { # This loop will be executed while $ok = 0
                    
                    <do other stuff here..>
            
                    $ok = $obj->cmd_poll;
            }
  • If you want to retrieve the command output sequence along the way:
            ($ok, $output) = $obj->cmd(Command => "show command", Blocking => 0, Errmode => 'return');
            die $obj->errmsg unless defined $ok;    # Login failed
            until ($ok) {
                    
                    <do other stuff here..>
            
                    ($ok, $partialOutput) = $obj->cmd_poll;
                    die $obj->errmsg unless defined $ok;    # Login failed or timeout
                    $output .= $partialOutput;
            }
            print "Complete command output:\n", $output;

    Note that $partialOutput returned will always terminate at output line boundaries (i.e. you can be sure that the last line is complete and not a fragment waiting for more output from device) so the output can be safely parsed for any seeked informaton.

  • If you only want to retrieve the command output at the end:
            $ok = $obj->cmd(Command => "show command", Blocking => 0);
            until ($ok) {
                    
                    <do other stuff here..>
            
                    $ok = $obj->cmd_poll;
            }
            print "Complete command output:\n", ($obj->cmd_poll)[1];
change_baudrate() - Change baud rate or other serial port parameter on current serial connection
  $ok = $obj->change_baudrate($baudRate);

  $ok = $obj->change_baudrate(
        [BaudRate               => $baudRate,]
        [Parity                 => $parity,]
        [DataBits               => $dataBits,]
        [StopBits               => $stopBits,]
        [Handshake              => $handshake,]
        [Errmode                => $errmode,]
  );

This method is only applicable to an already established Serial port connection and will return an error if the connection type is Telnet or SSH or if the object type is for Serial but no connection is yet established. The serial connection is restarted with the new baudrate (in the background, the serial connection is actually disconnected and then re-connected) without losing the current CLI session. As well as (or instead of) the baudrate, any of Parity, Databits, Stopbits or Handshake can also be changed for the active connection at the same time. If there is a problem restarting the serial port connection with the new settings then the error mode action is performed - see errmode(). If the baudrate (or other parameter) was successfully changed a true (1) value is returned. Note that you have to change the baudrate on the far end device before calling this method to change the connection's baudrate. Follows an example:

        use Control::CLI;
        # Create the object instance for Serial port
        $cli = new Control::CLI('COM1');
        # Connect to host at default baudrate
        $cli->connect( BaudRate => 9600 );
        # Send some character sequence to wake up the other end, e.g. a carriage return
        $cli->print;
        # Set the new baudrate on the far end device
        # NOTE use print as you won't be able to read the prompt at the new baudrate right now
        $cli->print("term speed 38400");
        # Now change baudrate for the connection
        $cli->change_baudrate(38400);
        # Send a carriage return and expect to get a new prompt back
        $cli->cmd; #If no prompt is seen at the new baudrate, we will timeout here
        # Send a command and read the resulting output
        $outref = $cli->cmd("command which generates lots of output...");
        print $$outerf;
        # Restore baudrate before disconnecting
        $cli->print("term speed 9600");
        # Safe to wait a little, to give time to host to process command before disconnecting
        sleep 1;

        $cli->disconnect;
input_log() - log all input sent to host
  $fh = $obj->input_log;

  $fh = $obj->input_log($fh);

  $fh = $obj->input_log($filename);

This method starts or stops logging of all input received from host (e.g. via any of read(), readwait(), waitfor(), cmd(), login() methods). This is useful when debugging. Because most command interpreters echo back commands received, it's likely all output sent to the host will also appear in the input log. See also output_log(). If no argument is given, the log filehandle is returned. An empty string indicates logging is off. If an open filehandle is given, it is used for logging and returned. Otherwise, the argument is assumed to be the name of a file, the file is opened for logging and a filehandle to it is returned. If the file can't be opened for writing, the error mode action is performed. To stop logging, use an empty string as the argument.

output_log() - log all output received from host
  $fh = $obj->output_log;

  $fh = $obj->output_log($fh);

  $fh = $obj->output_log($filename);

This method starts or stops logging of output sent to host (e.g. via any of put(), print(), printlist(), cmd(), login() methods). This is useful when debugging. If no argument is given, the log filehandle is returned. An empty string indicates logging is off. If an open filehandle is given, it is used for logging and returned. Otherwise, the argument is assumed to be the name of a file, the file is opened for logging and a filehandle to it is returned. If the file can't be opened for writing, the error mode action is performed. To stop logging, use an empty string as the argument.

dump_log() - log hex and ascii for both input and output stream
  $fh = $obj->dump_log;

  $fh = $obj->dump_log($fh);

  $fh = $obj->dump_log($filename);

This method starts or stops logging of both input and output. The information is displayed both as a hex dump as well as in printable ascii. This is useful when debugging. If no argument is given, the log filehandle is returned. An empty string indicates logging is off. If an open filehandle is given, it is used for logging and returned. Otherwise, the argument is assumed to be the name of a file, the file is opened for logging and a filehandle to it is returned. If the file can't be opened for writing, the error mode action is performed. To stop logging, use an empty string as the argument.

eof - end-of-file indicator
  $eof = $obj->eof;

This method returns a true (1) value if the end of file has been read. When this is true, the general idea is that you can still read but you won't be able to write. This method simply exposes the method by the same name provided by Net::Telnet. Net::SSH2::Channel also has an eof method but this was not working properly (always returns 0) at the time of implementing the Control::CLI::eof method; so this method adds some logic to eof for SSH connections: if the SSH eof method returns 1, then that value is returned, otherwise a check is performed on Net::SSH::error and if this returns either LIBSSH2_ERROR_SOCKET_NONE or LIBSSH2_ERROR_SOCKET_RECV then we return an eof of 1; otherwise we return an eof of 0. In the case of a serial connection this module simply returns eof true before a connection is established and after the connection is closed or breaks.

break() - send the break signal
  $ok = $obj->break([$millisecs]);

This method generates the break signal on the underlying connection. The break signal is outside the ASCII character set but has local meaning on some end systems. The $millisecs argument, if provided, is only used over Serial connections and is ignored for Telnet and SSH. Over a Serial connection this method calls the underlying pulse_break_on($millisecs) method and if $millisecs argument is not specified the duration timer is set to 300ms which is the most commonly used duration for signalling a break signal. Over a Telnet connection this method simply uses the method by the same name provided by Net::Telnet. Over an SSH connection this method sends '~B' over the open channel though it is not clear whether Net::SSH2 or the libssh2 libraries actually support this; it is hoped that the receiving end accepts this as a break signal.

disconnect - disconnect from host
  $ok = $obj->disconnect;

This method closes the connection. Always returns true.

close - disconnect from host
  $ok = $obj->close;

This method closes the connection. It is an alias to disconnect() method. Always returns true.

poll - poll object(s) for completion
  $ok = $obj->poll(
        [Poll_code              => $codeRef,]
        [Poll_timer             => $millisecs,]
        [Errmode                => $errmode,]
  );

  $running = Control::CLI::poll(\%hash_of_objects | \%array_of_objects);

  ($running, $completed, $failed, \@lastCompleted, \@lastFailed) = Control::CLI::poll(\%hash_of_objects | \%array_of_objects);

  $running = Control::CLI::poll(
        Object_list             => \%hash_of_objects | \%array_of_objects,
        [Poll_code              => $codeRef,]
        [Object_complete        => 'all' | 'next',]
        [Object_error           => 'return' | 'ignore',]
        [Poll_timer             => $millisecs,]
        [Errmode                => $errmode,]
  );

  ($running, $completed, $failed, \@lastCompleted, \@lastFailed) = Control::CLI::poll(
        Object_list             => \%hash_of_objects | \%array_of_objects,
        [Poll_code              => $codeRef,]
        [Object_complete        => 'all' | 'next',]
        [Object_error           => 'return' | 'ignore',]
        [Poll_timer             => $millisecs,]
        [Errmode                => $errmode,]
  );

This is a convenience method to help polling one or more Control::CLI (or inherited) objects for completion. In the first form this method can be called as an object method, alas it will report back the poll status of that single object. The $ok status reported will be either true (1) if the current polled method for the object has comleted, or undef if it failed with an error (and the errmode was set to 'return'). The advantage of this form is that the same poll() method can be used instead of the corresponding <methodName>_poll() method for which you would have to build your own polling loop.

In the second form, this method is called as a class method (not an object method) and the 1st argument is either a hash or an array structure holding multiple Control::CLI (or inherited) objects. Now the poll() method will cycle through all the objects and verify their corresponding status. There are multiple ways in which this method can be configured to return:

  • object_complete = 'all' AND object_error = 'ignore' : Method will only return once all objects have completed whether they completed successfully or failed with an error (and the errmode was set to 'return'); this is the default mode if arguments 'object_complete' and 'object_error' are not specified
  • object_complete = 'all' AND object_error = 'return' : Method will only return once all objects have completed successfully or as soon as one of the objects fails with an error (and the errmode was set to 'return')
  • object_complete = 'next' AND object_error = 'ignore' : Method will return as soon as one (or some) of the objects has/have completed successfully; the method will not return if an object fails with an error (and the errmode was set to 'return')
  • object_complete = 'next' AND object_error = 'return' : Method will return as soon as one (or some) of the objects has/have completed successfully or failed with an error (and the errmode was set to 'return')

When the method returns it will provide the number of objects still running ($running), those that have completed successfully ($completed) and those that have failed with an error ($failed) as well as an array reference of last objects that completed (\@lastCompleted) and one of last objects that failed (\@lastFailed). If the poll method was called with a hash structure, these arrays will hold the keys which completed/failed; if instead a list of objects was supplied then these arrays will hold the indexes which completed/failed.

By default the polling is done every 100 millisecs against all objects. A different timer can be used by specifying the poll_timer argument. If a code reference is provided via the 'poll_code' argument, that code will be called at every polling cycle with arguments ($running, $completed, $failed, \@lastCompleted, \@lastFailed); you may use this to print out some form of activity indication (e.g. print dots). Examples on how to use this method can be found in the examples directory.

If an error mode is set using the 'errmode' argument, this will be used for errors in the class method (which is not tied to a specific object) but will also be used to override whatever the relevant object error method was, for the duration of the poll() method. If instead no error mode argument is specified then the object(s) will use whatever error mode was set for them (or set when the initial poll capable method was called) while errors in the class method (which is not tied to a specific object) will use the class default error mode of 'croak'.

Note that to call poll, as a class method, without specifying the fully qualified package name, it will need to be expressly imported when loading this module:

        use Control::CLI qw(poll);

Error Handling Methods

errmode() - define action to be performed on error/timeout
  $mode = $obj->errmode;

  $prev = $obj->errmode($mode);

This method gets or sets the action used when errors are encountered using the object. The first calling sequence returns the current error mode. The second calling sequence sets it to $mode and returns the previous mode. Valid values for $mode are 'die', 'croak' (the default), 'return', a $coderef, or an $arrayref. When mode is 'die' or 'croak' and an error is encountered using the object, then an error message is printed to standard error and the program dies. The difference between 'die' and 'croak' is that 'die' will report the line number in this class while 'croak' will report the line in the calling program using this class. When mode is 'return' then the method generating the error places an error message in the object and returns an undefined value in a scalar context and an empty list in list context. The error message may be obtained using errmsg(). When mode is a $coderef, then when an error is encountered &$coderef is called with the error message as its first argument. Using this mode you may have your own subroutine handle errors. If &$coderef itself returns then the method generating the error returns undefined or an empty list depending on context. When mode is an $arrayref, the first element of the array must be a &$coderef. Any elements that follow are the arguments to &$coderef. When an error is encountered, the &$coderef is called with its arguments and the error message appended as the last argument. Using this mode you may have your own subroutine handle errors. If the &$coderef itself returns then the method generating the error returns undefined or an empty list depending on context. A warning is printed to STDERR when attempting to set this attribute to something that's not 'die', 'croak', 'return', a $coderef, or an $arrayref whose first element isn't a $coderef.

errmsg() - last generated error message for the object
  $msg = $obj->errmsg;

  $prev = $obj->errmsg($msg);

The first calling sequence returns the error message associated with the object. If no error has been encountered yet an undefined value is returned. The second calling sequence sets the error message for the object. Normally, error messages are set internally by a method when an error is encountered.

error() - perform the error mode action
  $obj->error($msg);

This method sets the error message via errmsg(). It then performs the error mode action. See errmode(). If the error mode doesn't cause the program to die/croak, then an undefined value or an empty list is returned depending on the context.

This method is primarily used by this class or a sub-class to perform the user requested action when an error is encountered.

Methods to set/read Object variables

timeout() - set I/O time-out interval
  $secs = $obj->timeout;

  $prev = $obj->timeout($secs);

This method gets or sets the timeout value that's used when reading input from the connected host. This applies to the read() method in blocking mode as well as the readwait(), waitfor(), login() and cmd() methods. When a method doesn't complete within the timeout interval then the error mode action is performed. See errmode(). The default timeout value is 10 secs.

connection_timeout() - set Telnet and SSH connection time-out interval
  $secs = $obj->connection_timeout;

  $prev = $obj->connection_timeout($secs);

This method gets or sets the Telnet and SSH TCP connection timeout value used when the connection is made in connect(). For backwards compatibility with earlier versions of this module, by default no connection timeout is set which results in the following behaviour:

  • In blocking mode, the underlying OS's TCP connection timeout is used, and this can vary.
  • In non-blocking mode, this module enforces the timeout and if no connection-timeout has been defined then a hard coded value of 20 seconds will be used.

To have a consistent behaviour in blocking and non-blocking modes as well as across different underlying OSes, simply set your own connection timeout value, either via this method or from the object constructor.

read_block_size() - set read_block_size for either SSH or Serial port
  $bytes = $obj->read_block_size;

  $prev = $obj->read_block_size($bytes);

This method gets or sets the read_block_size for either SSH or Serial port access (not applicable to Telnet). This is the read buffer size used on the underlying Net::SSH2 and Win32::SerialPort / Device::SerialPort read() methods. The default read_block_size is 4096 for SSH, 1024 for Win32::SerialPort and 255 for Device::SerialPort.

blocking() - set blocking mode for read methods and polling capable methods
  $flag = $obj->blocking;

  $prev = $obj->blocking($flag);

On the one hand, determines whether the read(), readwait() or waitfor() methods will wait for data to be received (until expiry of timeout) or return immediately if no data is available. On the other hand determines whether polling capable methods connect(), waitfor(), login() and cmd() operate in non-blocking polling mode or not. By default blocking is enabled (1). This method also returns the current or previous setting of the blocking mode. Note that to enable non-blocking mode this method needs to be called with a defined false value (i.e. 0); if called with an undefined value this method will only return the current blocking mode which is by default enabled.

read_attempts() - set number of read attempts used in readwait() method
  $numberOfReadAttemps = $obj->read_attempts;

  $prev = $obj->read_attempts($numberOfReadAttemps);

In the readwait() method, determines how many non-blocking read attempts are made to see if there is any further input data coming in after the initial blocking read. By default 5 read attempts are performed, each at readwait_timer() seconds apart. This method also returns the current or previous value of the setting.

readwait_timer() - set the polling timer used in readwait() method
  $millisecs = $obj->readwait_timer;

  $prev = $obj->readwait_timer($millisecs);

In the readwait() method, determines how long to wait between consecutive reads for more data. By default this is set to 100 milliseconds. This method also returns the current or previous value of the setting.

return_reference() - set whether read methods should return a hard reference or not
  $flag = $obj->return_reference;

  $prev = $obj->return_reference($flag);

This method gets or sets the setting for return_reference for the object. This applies to the read(), readwait(), waitfor(), cmd() and login() methods and determines whether these methods should return a hard reference to any output data or the data itself. By default return_reference is false (0) and the data itself is returned by the read methods, which is a more intuitive behaviour. However, if reading large amounts of data via the above mentioned read methods, using references will result in faster and more efficient code.

output_record_separator() - set the Output Record Separator automatically appended by print & cmd methods
  $ors = $obj->output_record_separator;

  $prev = $obj->output_record_separator($ors);

This method gets or sets the Output Record Separator character (or string) automatically appended by print(), printlist() and cmd() methods when sending a command string to the host. By default the Output Record Separator is a new line character "\n". If you do not want a new line character automatically appended consider using put() instead of print(). Alternatively (or if a different character than newline is required) modify the Output Record Separator for the object via this method.

prompt_credentials() - set whether connect() and login() methods should be able to prompt for credentials
  $flag = $obj->prompt_credentials;

  $prev = $obj->prompt_credentials($flag);

This method gets or sets the setting for prompt_credentials for the object. This applies to the connect() and login() methods and determines whether these methods can interactively prompt for username/password/passphrase information if these are required but not already provided. By default prompt_credentials is false (0).

flush_credentials - flush the stored username, password and passphrase credentials
  $obj->flush_credentials;

The connect() and login() methods, if successful in authenticating, will automatically store the username/password or SSH passphrase supplied to them. These can be retrieved via the username, password and passphrase methods. If you do not want these to persist in memory once the authentication has completed, use this method to flush them. This method always returns 1.

prompt() - set the CLI prompt match pattern for this object
  $string = $obj->prompt;

  $prev = $obj->prompt($string);

This method sets the CLI prompt match pattern for this object. In the first form the current pattern match string is returned. In the second form a new pattern match string is set and the previous setting returned. The default prompt match pattern used is:

        '.*[\?\$%#>]\s?$'

The object CLI prompt match pattern is only used by the login() and cmd() methods.

username_prompt() - set the login() username prompt match pattern for this object
  $string = $obj->username_prompt;

  $prev = $obj->username_prompt($string);

This method sets the login() username prompt match pattern for this object. In the first form the current pattern match string is returned. In the second form a new pattern match string is set and the previous setting returned. The default prompt match pattern used is:

        '(?i:username|login)[: ]*$'
password_prompt() - set the login() password prompt match pattern for this object
  $string = $obj->password_prompt;

  $prev = $obj->password_prompt($string);

This method sets the login() password prompt match pattern for this object. In the first form the current pattern match string is returned. In the second form a new pattern match string is set and the previous setting returned. The default prompt match pattern used is:

        '(?i)password[: ]*$'
debug() - set debugging
  $debugLevel = $obj->debug;

  $prev = $obj->debug($debugLevel);

Enables debugging for the object methods and on underlying modules. In the first form the current debug level is returned; in the second form a debug level is configured and the previous setting returned. By default debugging is disabled. To disable debugging set the debug level to 0. The debug levels defined in this class are tied to bits 1 & 2 only. Higher bit orders are available for sub-classing modules. The following debug levels are defined:

  • 0 : No debugging
  • bit 1 : Debugging activated for for polling methods + readwait() and enables carping on Win32/Device::SerialPort. This level also resets Win32/Device::SerialPort constructor $quiet flag only when supplied in Control::CLI::new()
  • bit 2 : Debugging is activated on underlying Net::SSH2 and Win32::SerialPort / Device::SerialPort; there is no actual debugging for Net::Telnet

To enable both debug flags set a debug level of 3.

Methods to access Object read-only variables

parent - return parent object
  $parent_obj = $obj->parent;

Since there are discrepancies in the way that parent Net::Telnet, Net::SSH2 and Win32/Device::SerialPort bless their object in their respective constructors, the Control::CLI class blesses its own object. The actual parent object is thus stored internally in the Control::CLI class. Normally this should not be a problem since the Control::CLI class is supposed to provide a common layer regardless of whether the underlying class is either Net::Telnet, Net::SSH2 and Win32/Device::SerialPort and there should be no need to access any of the parent class methods directly. However, exceptions exist. If there is a need to access a parent method directly then the parent object is required. This method returns the parent object. So, for instance, if you wanted to change the Win32::SerialPort read_interval (by default set to 100 in Control::CLI) and which is not implemented in Device::SerialPort:

        use Control::CLI;
        # Create the object instance for Serial
        $cli = new Control::CLI('COM1');
        # Connect to host
        $cli->connect( BaudRate => 9600 );

        # Set Win32::SerialPort's own read_interval method
        $cli->parent->read_interval(300);

        # Send a command and read the resulting output
        $outref = $cli->cmd("command");
        print $$outerf;

        [...]

        $cli->disconnect;
socket - return socket object
  $parent_obj = $obj->socket;

Returns the socket object created either with IO::Socket::INET or IO::Socket::IP. Returns undef if the socket has not yet been setup or if the connection is over Serial port. Use this to access any of the socket methods. For example to obtain the local IP address and peer host IP address (in case you provided a DNS hostname to the connect() method) for the Telnet or SSH connection:

        $localIP = $cli->socket->sockhost;

        $peerhostIP = $cli->socket->peerhost;
ssh_channel - return ssh channel object
  $channel_obj = $obj->ssh_channel;

When running an SSH connection a Net::SSH2 object is created as well as a channel object. Both are stored internally in the Control::CLI class. The SSH2 object can be obtained using the above parent method. This method returns the SSH channel object.

connection_type - return connection type for object
  $type = $obj->connection_type;

Returns the connection type of the method: either 'TELNET', 'SSH' or 'SERIAL'

port - return the TCP port / COM port for the connection
  $port = $obj->port;

Returns the TCP port in use for Telnet and SSH modes and undef if no connection exists. Returns the COM port for Serial port mode. Note that the port returned might still be defined if the connection failed to establish. To test that a connection is active, use the connected method instead.

connected - returns status of connection
  $port = $obj->connected;

Returns a true (1) value if a connection is established and a false (0) value if not. Note that this method is simply implemented by negating the status of eof method.

last_prompt - returns the last CLI prompt received from host
  $string = $obj->last_prompt;

This method returns the last CLI prompt received from the host device or an undefined value if no prompt has yet been seen. The last CLI prompt received is updated in both login() and cmd() methods.

username - read username provided
  $username = $obj->username;

Returns the last username which was successfully used in either connect() or login(), or undef otherwise.

password - read password provided
  $password = $obj->password;

Returns the last password which was successfully used in either connect() or login(), or undef otherwise.

passphrase - read passphrase provided
  $passphrase = $obj->passphrase;

Returns the last passphrase which was successfully used in connect(), or undef otherwise.

handshake - read handshake used by current serial connection
  $handshake = $obj->handshake;

Returns the handshake setting used for the current serial connection; undef otherwise.

baudrate - read baudrate used by current serial connection
  $baudrate = $obj->baudrate;

Returns the baudrate setting used for the current serial connection; undef otherwise.

parity - read parity used by current serial connection
  $parity = $obj->parity;

Returns the parity setting used for the current serial connection; undef otherwise.

databits - read databits used by current serial connection
  $databits = $obj->databits;

Returns the databits setting used for the current serial connection; undef otherwise.

stopbits - read stopbits used by current serial connection
  $stopbits = $obj->stopbits;

Returns the stopbits setting used for the current serial connection; undef otherwise.

Methods for modules sub-classing Control::CLI

poll_struct() - sets up the polling data structure for non-blocking polling capable methods
  $obj->poll_struct($methodName, $codeRef, $blocking, $timeout, $errmode, $outputType, $outputRequested, $returnReference, $returnList);

Sets up the $self->{POLL} structure with the following key values:

        method                  =>      $methodName,
        coderef                 =>      $codeRef,
        cache                   =>      [],
        blocking                =>      $blocking,
        timeout                 =>      $timeout,
        endtime                 =>      undef,
        waittime                =>      undef,
        errmode                 =>      $errmode,
        complete                =>      0,
        return_reference        =>      $returnReference,
        return_list             =>      $returnList,
        output_requested        =>      $outputRequested,
        output_type             =>      $outputType,
        output_result           =>      undef,
        output_buffer           =>      '',
        local_buffer            =>      '',
        read_buffer             =>      undef,
        already_polled          =>      undef,
        socket                  =>      undef,

These keys represent common method storage values when a method is being called again and again using its poll method. Method specific storage values should be stored under nested hash $self->{POLL}{$class::$methodName}. This data structure must be setup before a polling method can make use of any of the poll_<name>() methods below.

$outputType should be set to 0 if no output, 1 if output will be stored in key output_buffer, 2 if result will be stored in key output_result and 3 if both an output and a result are to be returned respectively in keys output_buffer & output_result.

$returnReference only applies to output stored in output_buffer key. $returnList only applies to data in output_result key, if it is an ARRAY reference. If key output_result will be used to store an array reference, $returnList will determine how that array will be returned: (1) as a list of values; (0/undef) as a single array reference.

poll_struct_cache() - caches selected poll structure keys, if a nested polled method is called
  $obj->poll_struct_cache($methodName, $timeout);

This method is used within the internal polled method, if called directly, from within an externally called polled method. For example a more complex login() method is written in a sub class, which is also written to support polling (non-blocking mode), and withing this new login() method we want to call poll_waitfor() directly from this class (without having to use the waitfor() and waitfor_poll() methods which would otherwise trample on the poll structure setup by the new login() method). The poll_waitfor() method can tell if it was called directly (without a polling structure for waitfor already in place) and in this case will use this method to cache the poll structure keys that it has to use, so that their values can be restored by poll_struct_restore once the poll_waitfor() method has completed.

poll_struct_restore - restores previously cached poll structure keys, if a nested polled method was called
  $obj->poll_struct_restore;

If an internally polled method was called, and at that time poll_struct_cache() was called, whenever that method has completed this method is automatically triggered inside poll_return() to automatically restore the polling keys used by the externally polled method.

poll_reset - resets poll structure
  $ok = $obj->poll_reset;

Once a polling capable method is called, in non-blocking mode, a polling structure is put in place. The expectation is that the method is polled to completion (or until an error is encountered) before a new polling capable method is called. If a new method is called before the previous has completed, the new method will carp warning messages about the existing polling structure being trampled on before having completed. To avoid that, the poll_reset method can be called once to reset and clear the polling structure before calling the new method. Here is an example:

        $ok = $obj->cmd(Command => "show command", Blocking => 0, Poll_syntax => 1);
        until ($ok) {
                ($ok, $partialOutput) = $obj->cmd_poll;
                if ($partialOutput =~ /<seeked information>/) {

                        < do whatever with information... >

                        $obj->poll_reset; # Reset structure as we are going to quit the loop
                        last;
                }
        }
        # Make sure we have prompt in stream
        $obj->waitfor($obj->prompt); # Now we don't get any carps here
poll_return() - return status and optional output while updating poll structure
  $ok = $obj->poll_return($ok);

  ($ok, $output1 [, $output2]) = $obj->poll_return($ok);

Takes the desired exit status, $ok (which could be set to 1, 0 or undef), updates the poll structure "complete" key with it and returns the same value. If the poll structure "output_requested" key is true then the exit status is returned in list context together with any available output. The poll structure "output_type" key bits 0 and 1 determine what type of output is returned in the list; if bit 0 is set, the contents of poll structure "output_buffer" key are returned (either as direct output or as a reference, depending on whether key "return_reference" is set or not) and at the same time the contents of the "output_buffer" key are deleted to ensure that the same output is not returned again at the next non-blocking call; if bit 1 is set, the contents of poll structure "output_result" key is returned added to the list (the "output_result" key can hold either a scalar value or an array; both cases are handled); if both bit 0 and bit 1 are set then both output types are added to the returned list. Note, a polled method should ALWAYS use this poll_return method to come out; whether it has completed successfully, non-blocking not ready, or encountered an error. Otherwise the calling method's <method>_poll() will not be able to behave correctly.

In the case of an internally called poll method, poll_struct_restore() is automatically invoked and output1 & $output2 are only returned on success ($ok true), as references respectively to output_buffer and output_result poll structure keys; on failure ($ok undef) or not ready ($ok == 0) then output1 & $output2 remain undefined.

poll_open_socket() - opens TCP socket in blocking or non-blocking mode
  ($ok, $socket) = $obj->poll_open_socket($pkgsub, $host, $port);

Uses IO::Socket::IP, if installed, to open a TCP socket in non-blocking or blocking mode while enforcing the connection timeout defined under poll structure key 'timeout'. If no connection timeout is defined then, in blocking mode the system's own TCP timeouts will apply while in non-blocking mode a default 20 sec timeout is used. If IO::Socket::IP is not installed will use IO::Socket::INET instead but this will only work in blocking mode. The $socket is defined and returned only on success ($ok true).

poll_read() - performs a non-blocking poll read and handles timeout in non-blocking polling mode
  $ok = $obj->poll_read($pkgsub [, 'Timeout error string']);

In blocking mode this method is no different from a regular blocking read(). In non-blocking mode this method will allow the calling loop to either quit immediately (if nothing can be read) or to cycle once only (in case something was read) and come out immediately at the next iteration.

If nothing was read then a check is made to see if we have passed the timeout or not; the method will return 0 if the timeout has not expired or $obj->error($pkgsub.'Timeout error string') in case of timeout which, depending on the error mode action may or may not return. If you want the method to always return regardless of the error mode action (because you want the calling loop to handle this) then simply do not provide any timeout string to this method, then in case of timeout this method will always return with an undefined value. In all these above cases the return value from this method is not true and the calling loop should pass this return value (0 or undef) to poll_return() method to come out.

In the case that some output was read, this method will return a true (1) value indicating that the calling loop can process the available output stored in the poll structure "read_buffer" key. When the calling loop comes round to calling this method again, this method will simply immediately return 0, thus forcing the calling loop to come out via poll_return(). The poll structure "already_polled" key is used to keep track of this behaviour and is always reset by poll_return().

Follows an example on how to use this method:

        do {
                my $ok = $self->poll_read($pkgsub, 'Timeout <custom message>');
                return $self->poll_return($ok) unless $ok; # Come out if error (if errmode='return'), or if nothing to read in non-blocking mode

                < process data in $self->{POLL}{read_buffer}>

        } until <loop stisfied condition>;
poll_readwait() - performs a non-blocking poll readwait and handles timeout in non-blocking polling mode
  $ok = $obj->poll_readwait($pkgsub, $firstReadRequired [, $readAttempts [, $readwaitTimer [, 'Timeout error string']]]);

In blocking mode this method is no different from a regular blocking readwait(Read_attempts => $readAttempts, Blocking => $firstReadRequired). In non-blocking mode the same behaviuor is emulated by allowing the calling loop to either quit immediately (if nothing can be read, or if the readwait timer has not yet expired) or to cycle once only (in case something was read and the readwait timer has expired) and come out immediately at the next iteration.

The $firstReadRequired argument determines whether an initial read of data is required (and if we don't get any, then we timeout; just like the readwait() method in blocking mode) or whether we just wait the wait timer and return any data received during this time (without any timeout associated; just like the readwait() method in non-blocking mode).

If some output was read during the 1st call, the poll structure "waittime" is set to the waitread behaviuor where we wait a certain amount of time before making the output available. Subsequent poll calls to this function will only make the output available for processing once the waittime has expired. Before that happens this method will continue returning a 0 value. Once that happens this method will return a true (1) value and the calling loop can then process the output in in the poll structure "read_buffer".

If instead no data has yet been read (and $firstReadRequired was true) then a check is made to see if we have passed the timeout or not; the method will return 0 if the timeout has not expired yet, or $obj->error($pkgsub.'Timeout error string') in case of timeout which, depending on the error mode action may or may not return. If you want the method to always return regardless of the error mode action (because you want the calling loop to handle this) then simply do not provide any timeout string to this method, then in case of timeout this method will always return with an undefined value. For any of the above cases where the return value from this method is not true, the calling loop should pass this return value (0 or undef) to poll_return() method to come out.

Follows an example on how to use this method:

        do {
                my $ok = $self->poll_readwait($pkgsub, 1, $readAttempts, $readwaitTimer, 'Timeout <custom message>');
                return $self->poll_return($ok) unless $ok; # Come out if error (if errmode='return'), or if nothing to read in non-blocking mode

                < process data in $self->{POLL}{read_buffer}>

        } until <loop stisfied condition>;
poll_waitfor() - performs a non-blocking poll for waitfor()
  ($ok, $dataref, $matchref) = $obj->poll_waitfor($pkgsub, $matchpat, [$timeout], [$errmode]);

  ($ok, $dataref, $matchref) = $obj->poll_waitfor($pkgsub, \@matchpats, [$timeout], [$errmode]);

Normally this is the internal method used by waitfor() and waitfor_poll() methods. It is exposed so that sub classing modules can leverage the functionality within new methods themselves implementing polling. These newer methods would have already set up a polling structure of their own. When calling poll_waitfor() directly for the 1st time, it will detect an already existing poll structure and add itself to it (as well as caching some of it's keys; see poll_struct_cache). It will also read in the arguments provided at this point. On subsequent calls, the arguments provided are ignored and the method simply polls the progress of the current task.

Follows an example on how to use this method:

        < processing previous stages >

        if ($newMethod->{stage} < X) { # stage X
                my ($ok, $dataref, $matchref) = $self->poll_waitfor('Login: $', [$timeout], [$errmode]);
                return $self->poll_return($ok) unless $ok;
                $newMethod->{stage}++; # Move to next stage X+1
        }

        < processing of next stages here >
poll_connect() - performs a non-blocking poll for connect()
  $ok = $obj->poll_connect($pkgsub, $host, $port, $username, $password, $publickey, $privatekey, $passphrase,
                             $baudrate, $parity, $databits, $stopbits, $handshake, $promptCredentials, [$timeout], [$errmode]);

Normally this is the internal method used by connect() and connect_poll() methods. It is exposed so that sub classing modules can leverage the functionality within new methods themselves implementing polling. These newer methods would have already set up a polling structure of their own. When calling poll_connect() directly for the 1st time, it will detect an already existing poll structure and add itself to it (as well as caching some of it's keys; see poll_struct_cache). It will also read in the arguments provided at this point. On subsequent calls, the arguments provided are ignored and the method simply polls the progress of the current task.

poll_login() - performs a non-blocking poll for login()
  ($ok, $outputref) = $obj->poll_login($pkgsub, $username, $password, $prompt, $userPrompt, $pwdPrompt, $promptCredentials, [$timeout], [$errmode]);

Normally this is the internal method used by login() and login_poll() methods. It is exposed so that sub classing modules can leverage the functionality within new methods themselves implementing polling. These newer methods would have already set up a polling structure of their own. When calling poll_login() directly for the 1st time, it will detect an already existing poll structure and add itself to it (as well as caching some of it's keys; see poll_struct_cache). It will also read in the arguments provided at this point. On subsequent calls, the arguments provided are ignored and the method simply polls the progress of the current task. Arguments after $ok will only be defined if $ok is true(1).

poll_cmd() - performs a non-blocking poll for cmd()
  ($ok, $outputref) = $obj->poll_cmd($pkgsub, $cmd, $prompt, [$timeout], [$errmode]);

Normally this is the internal method used by cmd() and cmd_poll() methods. It is exposed so that sub classing modules can leverage the functionality within new methods themselves implementing polling. These newer methods would have already set up a polling structure of their own. When calling poll_cmd() directly for the 1st time, it will detect an already existing poll structure and add itself to it (as well as caching some of it's keys; see poll_struct_cache). It will also read in the arguments provided at this point. On subsequent calls, the arguments provided are ignored and the method simply polls the progress of the current task. Arguments after $ok will only be defined if $ok is true(1).

debugMsg() - prints out a debug message
  $obj->debugMsg($msgLevel, $string1 [, $stringRef [,$string2]]);

A logical AND is performed between $msgLevel and the object debug level - see debug(); if the result is true, then the message is printed. The message can be provided in 3 chunks: $string1 is always present, followed by an optional string reference (to dump large amout of data) and $string2.

CLASS METHODS ^

Class Methods which are not tied to an object instance. By default the Control::CLI class does not import anything since it is object oriented. The following class methods should therefore be called using their fully qualified package name or else they can be expressly imported when loading this module:

        # Import all class methods listed in this section
        use Control::CLI qw(:all);

        # Import useTelnet, useSsh, useSerial & useIPv6
        use Control::CLI qw(:use);

        # Import promptClear & promptHide
        use Control::CLI qw(:prompt);

        # Import parseMethodArgs suppressMethodArgs
        use Control::CLI qw(:args);

        # Import just passphraseRequired
        use Control::CLI qw(passphraseRequired);

        # Import just parse_errmode
        use Control::CLI qw(parse_errmode);

        # Import just stripLastLine
        use Control::CLI qw(stripLastLine);

        # Import just poll()
        use Control::CLI qw(poll);
useTelnet - can Telnet be used ?
  $yes = Control::CLI::useTelnet;

Returns a true (1) value if Net::Telnet is installed and hence Telnet access can be used with this class.

useSsh - can SSH be used ?
  $yes = Control::CLI::useSsh;

Returns a true (1) value if Net::SSH2 is installed and hence SSH access can be used with this class.

useSerial - can Serial port be used ?
  $yes = Control::CLI::useSerial;

Returns a true (1) value if Win32::SerialPort (on Windows) or Device::SerialPort (on non-Windows) is installed and hence Serial port access can be used with this class.

useIPv6 - can IPv6 be used with Telnet or SSH ?
  $yes = Control::CLI::useIPv6;

Returns a true (1) value if IO::Socket::IP is installed and hence both Telnet and SSH can operate on IPv6 as well as IPv4.

poll() - poll objects for completion

This method has a double identity, as object method or class method. It was already covered under the Object Methods section.

The remainder of these class methods is exposed with the intention to make these available to modules sub-classing Control::CLI.

promptClear() - prompt for username in clear text
  $username = Control::CLI::promptClear($prompt);

This method prompts (using $prompt) user to enter a value/string, typically a username. User input is visible while typed in.

promptHide() - prompt for password in hidden text
  $password = Control::CLI::promptHide($prompt);

This method prompts (using $prompt) user to enter a value/string, typically a password or passphrase. User input is hidden while typed in.

passphraseRequired() - check if private key requires passphrase
  $yes = Control::CLI::passphraseRequired($privateKey);

This method opens the private key provided (DSA or RSA) and verifies whether the key requires a passphrase to be used. Returns a true (1) value if the key requires a passphrase and false (0) if not. On failure to open/find the private key provided an undefined value is returned.

parseMethodArgs() - parse arguments passed to a method against list of valid arguments
  %args = Control::CLI::parseMethodArgs($methodName, \@inputArgs, \@validArgs);

This method checks all input arguments against a list of valid arguments and generates a warning message if an invalid argument is found. The warning message will contain the $methodName passed to this function. Additionally, all valid input arguments are returned as a hash where the hash key (the argument) is set to lowercase.

suppressMethodArgs() - parse arguments passed to a method and suppress selected arguments
  %args = Control::CLI::suppressMethodArgs(\@inputArgs, \@suppressArgs);

This method checks all input arguments against a list of arguments to be suppressed. Remaining arguments are returned as a hash where the hash key (the argument) is set to lowercase.

parse_errmode() - parse a new value for the error mode and return it if valid or undef otherwise
  $errmode = Control::CLI::parse_errmode($inputErrmode);

This method will check the input error mode supplied to it to ensure that it is a valid error mode. If one of the valid strings 'die', 'croak' or 'return' it will ensure that the returned $errmode has the string all in lowercase. For an array ref it will ensure that the first element of the array ref is a code ref. If the input errmode is found to be invalid in any way, a warning message is printed with carp and an undef value is returned.

stripLastLine() - strip and return last incomplete line from string reference provided
  $lastLine = Control::CLI::stripLastLine(\$stringRef);

This method will take a reference to a string and remove and return the last incomplete line, if any. An incomplete line is constituted by any text not followed by a newline (\n). If the string terminates with a newline (\n) then this method will return an empty string.

NON BLOCKING POLLING MODE ^

Non-blocking mode is useful if you want your Perl code to do something else while waiting for a connection to establish or a command to complete instead of just waiting. It also allows the same (single thread) script to drive the CLI of many host devices in a parallel fashion rather than in a time consuming sequential fashion. But why not use threads instead ? The following bullets are from the author's experience with dealing with both approaches:

This class distribution includes a number of examples on how to achieve the same job using both approaches: (a) using threads & (b) using a single thread in non-blocking mode. You can find these under the examples directory.

AUTHOR ^

Ludovico Stevens <lstevens@cpan.org>

BUGS ^

Please report any bugs or feature requests to bug-control-cli at rt.cpan.org, or through the web interface at http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Control-CLI. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.

SUPPORT ^

You can find documentation for this module with the perldoc command.

    perldoc Control::CLI

You can also look for information at:

ACKNOWLEDGEMENTS ^

A lot of the methods and functionality of this class, as well as some code, is directly inspired from the popular Net::Telnet class. I used Net::Telnet extensively until I was faced with adapting my scripts to run not just over Telnet but SSH as well. At which point I started working on my own class as a way to extend the rich functionality of Net::Telnet over to Net::SSH2 while at the same time abstracting it from the underlying connection type. From there, adding serial port support was pretty straight forward.

LICENSE AND COPYRIGHT ^

Copyright 2015 Ludovico Stevens.

This program is free software; you can redistribute it and/or modify it under the terms of either: the GNU General Public License as published by the Free Software Foundation; or the Artistic License.

See http://dev.perl.org/licenses/ for more information.

syntax highlighting: