Ludovico Stevens > Control-CLI-1.05 > Control::CLI

Download:
Control-CLI-1.05.tar.gz

Dependencies

Annotate this POD

CPAN RT

Open  0
View/Report Bugs
Module Version: 1.05   Source   Latest Release: Control-CLI-1.06

NAME ^

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

SYNOPSIS ^

Telnet access

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

SSH access

        use Control::CLI;
        # Create the object instance for SSH
        $cli = new Control::CLI('SSH');
        # Connect to host - Note that with SSH,
        #  authentication is normally part of the connection process
        $cli->connect(  Host            => 'hostname',
                        Username        => $username,
                        Password        => $password,
                        PublicKey       => '.ssh/id_dsa.pub',
                        PrivateKey      => '.ssh/id_dsa',
                        Passphrase      => $passphrase,
                     );
        # In some rare cases, may need to use login
        #  only 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;

DESCRIPTION ^

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

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

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

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

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

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

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

OBJECT CONSTRUCTOR ^

Used to create an object instance of Control::CLI

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

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

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

OBJECT METHODS ^

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

Main I/O Object Methods

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

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

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

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. 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" argument is provided to override the global setting of the object error mode action. The optional "connection_timeout" argument can be used to set a connection timeout for Telnet and SSH TCP connections. Which arguments are used depends on the whether the object was created for Telnet, SSH or Serial port. The "host" argument is required by both Telnet and SSH. The other arguments are optional.

  • For Telnet, two 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,]
            [Errmode                => $errmode,]
      );

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

  • For SSH, two 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,]
            [Errmode                => $errmode,]
      );

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

    • Publickey authentication : If the remote host accepts it and the method was supplied with public/private keys. The public/private keys need to be in OpenSSH format. If the private key is protected by a passphrase then this must also be provided or, if prompt_credentials is true, this method will prompt for the passphrase. If publickey authentication fails for any reason and password authentication is possible, then password authentication is attempted next; otherwise the error mode action is performed. See errmode().
    • Password authentication : If the remote host accepts it. 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().

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

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

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

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

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

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

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). 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,],
        [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 0.1 seconds intervals to ensure that any subsequent data is also read before returning. 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 0.1 seconds times the value of "read_attempts" and faster response times can be obtained using the regular read() method. Returns either a hard reference to data read or the data itself, depending on the applicable setting of return_reference. See return_reference(). 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() - wait for pattern in the input stream
  $data || $dataref = $obj->waitfor($matchpat);

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

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

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

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. In scalar context returns any data read up to but excluding the matched string. In list context returns the same data read as well as the actual string which was matched. 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 last two forms any number of pattern match strings can be provided and the method will wait until a match is found against any of those patterns. In both cases the pattern match can be a simple string or any valid perl regular expression match string (in the latter case use single quotes when building the string). In the second form only, 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 references for the outputs ($data & $match) or the data itself, depending on the applicable setting of return_reference. See return_reference(). This method is similar (but not identical) to the method of the same name provided in Net::Telnet.

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() - handle login for Telnet / Serial port
  $ok = $obj->login(
        [Username               => $username,]
        [Password               => $password,]
        [Prompt_credentials     => $flag,]
        [Prompt                 => $prompt,]
        [Username_prompt        => $usernamePrompt,]
        [Password_prompt        => $passwordPrompt,]
        [Timeout                => $secs,]
        [Errmode                => $errmode,]
  );

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

This method handles login authentication for Telnet and Serial port access on a generic host (note that for SSH, authentication is normally part of the connection process; the exception is when 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). In the first form only a success/failure value is returned in scalar context, while in the second form, in list context, both the success/failure value is returned as well as any output received from the host device during the login sequence; the latter is either the output itself or a reference to that output, depending on the object setting of return_reference or the argument override provided in this method. For this method to succeed the username & password prompts from the remote host must match the default prompts defined for the object or the overrides specified via the optional "username_prompt" & "password_prompt" arguments. By default these regular expressions are set to:

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

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

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

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

cmd() - Sends a CLI command to host and returns output data
  $output || $outputRef = $obj->cmd($cliCommand);

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

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. Either a hard reference to the output or the output itself is returned, 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);
change_baudrate() - Change baud rate on current serial connection
  $ok = $obj->change_baudrate($baudrate);

  $ok = $obj->change_baudrate(
        BaudRate                => $baudrate,
        [Errmode                => $errmode,]
  );

This method is only applicable to an already established Serial port connection and will return an error if the connection type is Telnet or SSH or if the object type is for Serial but no connection is yet established. The serial connection is restarted with the new baudrate (in the background, the serial connection is actually disconnected and then re-connected) without losing the current CLI session. If there is a problem restarting the serial port connection at the new baudrate then the error mode action is performed - see errmode(). If the baudrate 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. Follows an example:

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

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

break - send the break signal
  $ok = $obj->break;

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. Over a Serial connection this method calls the underlying pulse_break_on($milliseconds) method with duration timer set to 300ms. Over a Telnet connection this method simply exposes the method by the same name provided by Net::Telnet. Over an SSH connection this method sends '~B' over the open channel though it is not clear whether Net::SSH2 or the libssh2 libraries actually support this; it is hoped that the receiving end accepts this as a break signal.

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

This method closes the connection. Always returns true.

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

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

Error Handling Methods

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

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

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

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

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

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

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

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

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

Methods to set/read Object variables

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

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

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

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

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

This method gets or sets the Telnet and SSH TCP connection timeout value used when the connection is made in connect(). By default no connection timeout is set, which results in the underlying OS's TCP connection timeout being used.

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
  $flag = $obj->blocking;

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

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. By default blocking is enabled (1). This method also returns the current or previous setting of the blocking mode.

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 0.1 seconds apart. This method also returns the current or previous value of the setting.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Enables debugging for the object methods and on underlying modules. In the first form the current debug level is returned; in the second form a debug level is configured and the previous setting returned. By default debugging is disabled. To disable debugging set the debug level to 0. The following debug levels are defined:

  • 0 : No debugging
  • 1 : Debugging activated for readwait() + Win32/Device::SerialPort constructor $quiet flag is reset. Note that to clear the $quiet flag, the debug argument needs to be supplied in Control::CLI::new()
  • 2 : Debugging is activated on underlying Net::SSH2 and Win32::SerialPort / Device::SerialPort; there is no actual debugging for Net::Telnet

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;
ssh_channel - return ssh channel object
  $channel_obj = $obj->ssh_channel;

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

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

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

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

Returns the TCP port in use for Telnet and SSH modes and undef if no connection exists. Returns the COM port for Serial port mode.

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.

CLASS METHODS ^

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

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

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

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

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

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

        # Import just parse_errmode
        use Control::CLI qw(parse_errmode);
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.

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

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

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

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

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

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

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

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

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

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

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

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

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

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 2010 Ludovico Stevens.

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

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

syntax highlighting: