The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

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(  Host            => 'hostname',
                        Terminal_type   => 'vt100',     # Optional
                     );
        # 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,
                        Terminal_type   => 'vt100',     # Optional
                     );
        # 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

        sub hostError { # Prepend hostname before error its cli object generated
                my ($host, $errmsg) = @_;
                die "\n$host -> $errmsg"; 
        }

        sub bulkDo { # Repeat for all hosts
                my ($cliHashRef, $method, $argsRef) = @_;
        
                foreach my $host (keys %$cliHashRef) { # Call $method for every object
                        my $codeRef = $cliHashRef->{$host}->can($method);
                        $codeRef->($cliHashRef->{$host}, @$argsRef);
                }
                poll(   # Poll all objects for completion of $method
                        Object_list     =>      $cliHashRef,
                        Poll_code       =>      sub { local $| = 1; print '.' },
                );
                print " done!\n";
        }

        # Create and Connect 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
                        Errmode         => [\&hostError, $host],# Error handler will add host-ip to msg
                );
                $cli{$host}->connect(
                        Host            =>      $host,
                        Username        =>      $username,
                        Password        =>      $password,
                );
        }
        print "Connecting to all hosts ";
        poll(   # Poll all objects for completion of connect
                Object_list     =>      \%cli,
                Poll_code       =>      sub { local $| = 1; print '.' },
        );
        print " done!\n";

        print "Performing login on all hosts ";
        bulkDo(\%cli, 'login', [Password => $password]);        # Not strictly necessary with SSH

        print "Entering PrivExec on all hosts ";
        bulkDo(\%cli, 'cmd', ['enable']);

        print "Entering Config mode on all hosts ";
        bulkDo(\%cli, 'cmd', ['config terminal']);

        print "Pushing config command on all hosts ";
        bulkDo(\%cli, 'cmd', ['snmp-server contact Jack']);

        print "Disconnecting from all hosts ";
        bulkDo(\%cli, '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:

  • Net::Telnet for Telnet access

  • Net::SSH2 for SSH access

  • IO::Socket::IP for IPv6 support

  • Win32::SerialPort or Device::SerialPort for Serial port access respectively on Windows and Unix systems

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.

For both Telnet and SSH this module allows setting of terminal type (e.g. vt100 or other) and windows size, which are not easy to achieve with Net::Telnet as they rely on Telnet option negotiation. Being able to set the terminal type is important with some devices which might otherwise refuse the connection if a specific virtual terminal type is not negotiated from the outset.

Note that 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,]
        [Errmsg_format           => $msgFormat,]
        [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,]
        [Data_with_error         => $flag,]
        [Read_block_size         => $bytes,]
        [Output_record_separator => $ors,]
        [Terminal_type           => $string,]
        [Window_size             => [$width, $height],]
        [Report_query_status     => $flag,]
        [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,]
        [ForceBaud              => $flag,]
        [Parity                 => $parity,]
        [DataBits               => $dataBits,]
        [StopBits               => $stopBits,]
        [Handshake              => $handshake,]
        [Connection_timeout     => $secs,]
        [Blocking               => $flag,]
        [Errmode                => $errmode,]
        [Terminal_type          => $string,]
        [Window_size            => [$width, $height],]
        [Callback               => \&codeRef,]
        [Atomic_connect         => $flag,]
  );

  $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. The "terminal_type" and "window_size" arguments are not overrides, they will change the object parameter as these settings are only applied during a connection. 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,]
            [Terminal_type          => $string,]
            [Window_size            => [$width, $height],]
            [Atomic_connect         => $flag,]
      );

    If not specified, the default port number for Telnet is 23. Arguments "terminal_type" and "window_size" are negotiated via Telnet options; to debug telnet option negotiation use Net::Telnet's own option_log() method.

  • 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,]
            [Terminal_type          => $string,]
            [Window_size            => [$width, $height],]
            [Callback               => \&codeRef,]
            [Atomic_connect         => $flag,]
      );

    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().

    If a code reference is provided via the 'callback' argument, that code will be called immediately after setting up the SSH connection and before attempting any authentication. You can use this callback to check the key of the remote host against a list of known host keys so as to determine whether or not the connection should proceed. A code reference will be called with as argument this class object id, from which the underlying Net::SSH2 object id can be obtained, which is required in order to call Net::SSH2's remote_hostkey and known_hosts methods. An example on how to verify the host key against your known hosts is provided in the documentation of Net::SSH2::KnownHosts. Note that Net::SSH2 methods remote_hostkey and known_hosts methods only exists as of version 0.54. This class does not require a minimum version of Net::SSH2 but your code will need to require a version of 0.54, or verify the availability of those methods, if you intend to use those methods in your callback. Instead of a code reference, an array reference can also be used provided that the first element in the array is a code reference. In this case the remainder of the array elements will be inserted as arguments to the code being called to which this class object id will be appended as last argument.

      $ok = &$codeRef($netSsh2Obj);
    
      ($ok, [$error_message]) = &$codeRef($netSsh2Obj);
    
      $ok = &{$codeRef->[0]}($codeRef->[1], $codeRef->[2], $codeRef->[3], ..., $controlCliObj);
    
      ($ok, [$error_message]) = &{$codeRef->[0]}($codeRef->[1], $codeRef->[2], $codeRef->[3], ..., $controlCliObj);

    Your callback should return a true value (for $ok) if the SSH connection is to proceed. Whereas a false/undefined value indicates that the connection should not go ahead; in this case an optional error message can be provided which will be used to perform the error mode action of this class. Otherwise a standard error message will be used.

    The "atomic_connect" argument is only useful if using the connect() method in non-blocking mode across many objects of this class and using the Control::CLI poll() method to poll progress across all of them. Since SSH authentication is not handled in non-blocking fashion in Net::SSH2, polling many SSH connections would result in all of them setting up the socket at the first poll cycles, and then one by one would have to go through SSH authentication; however the far end SSH server will typically timeout the socket if it sees no SSH authentication within the next 10 secs or so. Setting the "atomic_connect" argument will ensure that the connect() method will treat socket setup + SSH authentication as one single poll action and avoid the problem. The same argument can also work with Telnet by treating socket setup + hand-over to Telnet as one single poll action, however Telnet does not suffer from the same problem.

  • For Serial port, these arguments are used:

      $ok = $obj->connect(
            [BaudRate               => $baudRate,]
            [ForceBaud              => $flag,]
            [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"

    On Windows systems the underlying Win32::SerialPort module can have issues with some serial ports, and fail to set the desired baudrate (see bug report https://rt.cpan.org/Ticket/Display.html?id=120068); if hitting that problem (and no official Win32::SerialPort fix is yet available) set the ForceBaud argument; this will force Win32::SerialPort into setting the desired baudrate even if it does not think the serial port supports it.

    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,]
        [Data_with_error        => $flag,]
        [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. In the event that some data was initially read, but a read error occured while trying to read in subsequent data (for example the connection was lost), the "data_with_error" flag will determine how the readwait method behaves. If the "data_with_error" flag is not set, as per default, then the readwait method will immediately perform the error mode action. If instead the "data_with_error" flag is set, then the error is masked and the readwait method will immediately return the data which was read without attempting any further reads. Note that in the latter case, any subsequent read will most likely produce the same error condition. See also data_with_error(). 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,
            ... ]]]
        [Match_list             => \@arrayRef,]
        [Blocking               => $flag,]
        [Timeout                => $secs,]
        [Return_reference       => $flag,]
        [Errmode                => $errmode,]
  );

  ($data || $dataref, $match || $matchref) = $obj->waitfor(
        [Match                  => $matchpattern1,
         [Match                 => $matchpattern2,
          [Match                => $matchpattern3,
            ... ]]]
        [Match_list             => \@arrayRef,]
        [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,
            ... ]]]
        [Match_list             => \@arrayRef,]
        [Blocking               => $flag,]
        [Timeout                => $secs,]
        [Return_reference       => $flag,]
        [Errmode                => $errmode,]
  );

  ($ok, $data || $dataref, $match) = $obj->waitfor(
        Poll_syntax             => 1,
        [Match                  => $matchpattern1,
         [Match                 => $matchpattern2,
          [Match                => $matchpattern3,
            ... ]]]
        [Match_list             => \@arrayRef,]
        [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 (using "match" and "match_list" arguments) and the method will wait until a match is found against any of those patterns. In all 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:user(?: ?name)?|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?$'

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().

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. 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(Poll_syntax => 1, 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;    # Sending command failed
            until ($ok) {
                    
                    <do other stuff here..>
            
                    ($ok, $partialOutput) = $obj->cmd_poll;
                    die $obj->errmsg unless defined $ok;    # 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(Poll_syntax => 1, 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_baudrate_poll() - Change baud rate or other serial port parameter on current serial connection
  $ok = $obj->change_baudrate($baudRate);

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

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

  $ok = $obj->change_baudrate_poll();

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. This method will introduce a 100 millisec delay between tearing down and re-establishing the serial port connection, hence it is polling enabled should it be used in non-blocking mode. 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;
        # Perform login (or just lock onto 1st prompt)
        $cli->login( Username => $username, Password => $password );
        # 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;

  $ok = $obj->disconnect($close_logs_flag);

  $ok = $obj->disconnect(
        [Close_logs             => $flag,]
  );

This method closes the connection. Always returns true. If the close_logs flag is set and any of the logging methods input_log() or output_log() or dump_log() or even Net::Telnet's option_log() are active then their respective filehandle is closed and the logging is disabled.

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,]
        [Errmsg_format          => $msgFormat,]
  );

  ($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,]
        [Errmsg_format          => $msgFormat,]
  );

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')

Since the SSH connect() method is not truly non-blocking (during the authentication phase) and in order to avoid this class from timing out all objects when polling many, the poll method keeps track of cycle durations (for each object, time taken to poll other objects) and at every cycle re-credits the amount on each object timeout. Still, SSH connections polled in this way are still likely to fail beyond 10 objects due to the far end host timing out the incomming SSH connection; in which case you will need to stagger the jobs or make use of the connect() "atomic_connect" flag.

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. Instead of a code reference, an array reference can be used provided that the first element in the array is a code reference; in this case the remainder of the array elements will be inserted as arguments to the code being called to which arguments ($running, $completed, $failed, \@lastCompleted, \@lastFailed) will be appended.

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' the method in this class 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();

  $msg = $obj->errmsg(
        [Errmsg_format           => $msgFormat,]
  );

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

  $prev = $obj->errmsg(
        [Set_message             => $msg,]
        [Errmsg_format           => $msgFormat,]
  );

The first calling sequences return the error message associated with the object. If no error has been encountered yet an undefined value is returned. The last two calling sequences set the error message for the object. Normally, error messages are set internally by a method when an error is encountered. The 'errmsg_format' argument can be used as an override of the object's same setting; see errmsg_format().

errmsg_format() - set the format to be used for object error messages
  $format = $obj->errmsg_format;

  $prev = $obj->errmsg_format($format);

This class supports three different error message formats which can be set via this method. The first calling sequence returns the current format in use. The second calling sequence sets it to $format and returns the previous format. Valid values for $format are (non-case sensitive):

  • 'verbose': The error message is returned with the Control::CLI method name pre-pended to it, and in some cases it is appened with an upstream error message. For example:

      "Control::CLI::login: Failed reading login prompt // Control::CLI::read: Received eof from connection"
  • 'default': The error message is returned with the Control::CLI method name pre-pended to it. For example:

      "Control::CLI::login: Failed reading login prompt"
  • 'terse': Just the error message is returned, without any Control::CLI method name pre-pended. For example:

      "Failed reading login prompt"

In all cases above, an error message is always a single line of text.

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.

data_with_error() - set the readwait() method behaviour in case a read error occurs after some data was read
  $flag = $obj->data_with_error;

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

In the readwait() method, if some data was initially read but an error occurs while trying to read in subsequent data this flag determines the behaviour for the method. By default data_with_error is not set, and this will result in readwait() performing the error mode action regardless of whether some data was already read in or not. If however data_with_error is set, then the readwait() method will hold off from performing the error mode action (only if some data was already read) and will instead return that data without completing any further read_attempts. 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 | \&codeRef | \@arrayRef);

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. Note that enabling prompt_credentials is incompatible with using the object in non-blocking mode.

Prompt_credentials may be set to a code reference or an array reference (provided that the first element of the array is a code reference); in this case if the user needs to be prompted for a credential, the code reference provided will be called, followed by any arguments in the array (if prompt_credentials was set to an array reference) to which these arguments will be appended:

  • $privacy : Will be set to either 'Clear' or 'Hide', depending on whether a username or password/passphrase is requested

  • $credential : This will contain the text of what information is seeked from user; e.g. "Username", "Password", "Passphrase", etc.

The ability to use a code reference is also true on the prompt_credentials argument override that connect() and login() offer.

If prompt_credentials is set to a true value (which is not a reference) then the object will make use of class methods promptClear() and promptHide() which both make use of Term::ReadKey. 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:user(?: ?name)?|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[: ]*$'
terminal_type() - set the terminal type for the connection
  $string = $obj->terminal_type;

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

This method sets the terminal type which will be setup/negotiated during connection. In the first form the current setting is returned. Currently a terminal type is only negotiated with a SSH or TELNET connection, and only at connection time. By default no terminal type is defined which results in TELNET simply not negotiating any terminal type while SSH will default to 'vt100'. Once a terminal type is set via this method, both TELNET and SSH will negotiate that terminal type. Use an empty string to undefine the terminal type.

window_size() - set the terminal window size for the connection
  ($width, $height) = $obj->window_size;

  ($prevWidth, $prevHeight) = $obj->window_size($width, $height);

This method sets the terminal window size which will be setup/negotiated during connection. In the first form the current window size is returned. Currently a terminal window size is only negotiated with a SSH or TELNET connection, and only at connection time. By default no terminal window size is set which results in TELNET simply not negotiating any window size while SSH will default to 80 x 24. Once a terminal window size is set via this method, both TELNET and SSH will negotiate that window size during connect(). To undefine the window size call the method with either or both $width and $height set to 0 (or empty string).

report_query_status() - set if read methods should automatically respond to Query Device Status escape sequences
  $flag = $obj->report_query_status;

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

Some devices use the ANSI/VT100 Query Device Status escape sequence - <ESC>[5n - to check whether a terminal is still connected. A real VT100 terminal will automatically respond to these with a Report Device OK escape sequence - <ESC>[0n - otherwise the connection is reset. This is sometimes done on serial port connections to detect when the terminal is disconnected (serial cable removed) so as to reset the connection. The Query Device Status sequence can be sent as often as every second. While this is uncommon on Telnet and SSH connections, it can happen when SSH or Telnet accessing serial connections via some terminal server device. In order to successfully script such connections using this class it is necessary for the script to be able to generate the appropriate Report Device OK escape sequence in a timely manner. This method activates the ability for the read methods of this class to (a) detect a Query Device Status escape sequence within the received data stream, (b) remove it from the data stream which they ultimately return and (c) automatically send a Report Device OK escape sequence back to the connected device. This functionality, by default disabled, is embedded within the read methods of this class and is active for all of the following methods in both blocking and non blocking modes: read(), readwait(), waitfor(), login(), cmd(). However the script will need to interact with the connection (using the above mentioned methods) on a regular basis otherwise the connection will get reset. If you don't need to read the connection for more than a couple of seconds or you are just doing print() or printlist() to the connection, you will have to ensure that some non-blocking reads are done at regular intervals, either via a thread or within your mainloop.

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. An undefined value is returned if no SSH connection is established.

ssh_authentication - return ssh authentication type performed
  $auth_mode = $obj->ssh_authentication;

If an SSH connection is established, returns the authentication mode which was used, which will take one of these values: 'publickey', 'password' or 'keyboard-interactive'. An undefined value is returned if no SSH connection is established.

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

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

host - return the host for the connection
  $host = $obj->host;

Returns the hostname or IP supplied to connect() for Telnet and SSH modes and undef if no connection exists or if in Serial port mode. Note that the host returned might still be defined if the connection failed to establish. To test that a connection is active, use the connected method instead.

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 reference or a hash reference; in the case of an array reference either the array reference or the actual array list can be returned depnding on whether the poll structure "return_list" key is set or not); 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_sleep() - performs a sleep in blocking or non-blocking mode
  $ok = $obj->poll_sleep($pkgsub, $seconds);

In blocking mode this method is no different from a regular Time::HiRes::sleep. In non-blocking mode it will only return a true (1) value once the $seconds have expired while it will return a false (0) value otherwise.

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', $dataWithError]);

In blocking mode this method is no different from a regular blocking readwait(Read_attempts => $readAttempts, Blocking => $firstReadRequired). In non-blocking mode the same behaviour 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 behaviour 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 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.

The $dataWithError flag can be set to obtain the equivalent behaviuor of readwait() when some data has been read and a read error occurs during subsequent reads.

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,
        [Match                  => $matchpattern | \@matchpatterns
        [Timeout                => $secs,]
        [Errmode                => $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(
                                                                Match   => 'Login: $',
                                                                Timeout => [$timeout],
                                                                Errmode => [$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                   => $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,]
        [Errmode                => $errmode,]
        [Terminal_type          => $string,]
        [Window_size            => [$width, $height],]
  );

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               => $username,]
        [Password               => $password,]
        [Prompt_credentials     => $flag,]
        [Prompt                 => $prompt,]
        [Username_prompt        => $usernamePrompt,]
        [Password_prompt        => $passwordPrompt,]
        [Timeout                => $secs,]
        [Errmode                => $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. Return values 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,
        [Command                => $cliCommand,]
        [Prompt                 => $prompt,]
        [Timeout                => $secs,]
        [Errmode                => $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. Return values after $ok will only be defined if $ok is true(1).

poll_change_baudrate() - performs a non-blocking poll for change_baudrate()
  $ok = $obj->poll_change_baudrate($pkgsub,
        [BaudRate               => $baudRate,]
        [Parity                 => $parity,]
        [DataBits               => $dataBits,]
        [StopBits               => $stopBits,]
        [Handshake              => $handshake,]
        [Errmode                => $errmode,]
  );

Normally this is the internal method used by change_baudrate() method. 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_change_baudrate() 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.

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 & promptCredential
        use Control::CLI qw(:prompt);

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

        # Import validCodeRef callCodeRef
        use Control::CLI qw(:coderef);

        # 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.

promptCredential() - prompt for credential using either prompt class methods or code reference
  $credential = Control::CLI::promptCredential($prompt_credentials, $privacy, $credentialNeeded);

This method should only be called when prompt_credentials is set and the value of prompt_credentials should be passed as the first argument. If prompt_credentials is not a reference and is set to a true value and privacy is 'Clear' then promptClear($credentialNeeded) is called; whereas if privacy is 'Hide' then promptHide($credentialNeeded) is called. If instead prompt_credentials is a valid reference (verified by validCodeRef) then the code reference is called with $privacy and $credentialNeeded as arguments.

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, $noCarpFlag);

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. The warning message can be suppressed by setting the $noCarpFlag argument. 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.

validCodeRef() - validates reference as either a code ref or an array ref where first element is a code ref
  $ok = Control::CLI::validCodeRef($value);

This method will verify that the value provided is either a code reference or an array reference where the first element is a code reference and if so will return a true value. If not, it will return an undefined value.

callCodeRef() - calls the code ref provided (which should be a code ref or an array ref where first element is a code ref)
  $ok = Control::CLI::callCodeRef($codeOrArrayRef, @arguments);

If provided with a code reference, this method will call that code reference together with the provided arguments. If provided with an array reference, it will shift the first element of the array and call that as a code reference. The arguments provided to code being called will be the remainder of the elements of the array reference to which the provided arguments are appended. Note that this method does not do any checks on the validy of the reference it is provided with; use the validCodeRef() class method to verify the validity of the reference before calling this method with it.

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:

  • Writing code with threads is easier than trying to achieve the same thing using a single thread using non-blocking mode

  • But code written with threads is harder to troubleshoot

  • Code using threads will use a larger memory footprint than a single thread

  • Code written using threads can be faster than a single thread in non-blocking mode; however if you have to provide a result at the end, you will have to wait for the slowest thread to complete anyway

  • If you need interaction (e.g. sharing variables) or synchronisation (doing the same step across all CLI objects at the same time) then a single thread non-blocking approach is easier to implement. A thread approach would require the use of threads::shared which adds more complexity for sharing variables as well as attempting to keep the child threads synchronized with one another

  • If you have ~10-30 threads chances are your code will work well; if you have hundreds of threads then things start to go wrong; some threads will then die unexpectedly and it becomes hell to troubleshoot; your code will then need to become more complex to handle failed threads... (author's experience here is mostly on Windows systems using either ActiveState or Strawberry)

  • The Perl distribution you find on most Unix distributions is not always compiled for thread use

  • Some Perl modules do not work properly with threads; if you need to use such a module, you will either have to abandon the threads approach or try and fix that module

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 2020 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.