NAME

Net::Telnet::Cisco - interact with a Cisco router

SYNOPSIS

use Net::Telnet::Cisco;

my $session = Net::Telnet::Cisco->new(Host => '123.123.123.123');
$session->login('login', 'password');

# Execute a command
my @output = $session->cmd('show version');
print @output;

# Enable mode
if ($session->enable("enable_password") ) {
    @output = $session->cmd('show privilege');
    print "My privileges: @output\n";
} else {
    warn "Can't enable: " . $session->errmsg;
}

$session->close;

DESCRIPTION

Net::Telnet::Cisco provides additional functionality to Net::Telnet for dealing with Cisco routers.

cmd() parses router-generated error messages - the kind that begin with a '%' - and stows them in $obj->errmsg(), so that errmode can be used to perform automatic error-handling actions.

CAVEATS

Before you use Net::Telnet::Cisco, you should have a good understanding of Net::Telnet, so read it's documentation first, and then come back here to see the improvements.

Some things are easier to accomplish with UCD's C-based SNMP module, or the all-perl Net::SNMP. SNMP has three advantages: it's faster, handles errors better, and doesn't use any VTYs on the router. SNMP does have some limitations, so for anything you can't accomplish with SNMP, there's Net::Telnet::Cisco.

METHODS

new - create new Net::Telnet::Cisco object
$session = Net::Telnet::Cisco->new(
    [Always_waitfor_prompt => $boolean,]      # 1
    [Autopage              => $boolean,]      # 1
    [Ignore_warnings       => $boolean,]      # 0
    [More_prompt           => $matchop,]      # '/(?m:^\s*--More--)/',
    [Normalize_cmd         => $boolean,]      # 1
    [Send_wakeup           => $when,]         # 0
    [Waitfor_pause         => $milliseconds,] # 0.1
    [Warnings              => $matchop,]      # see docs

    # Net::Telnet arguments
);

Creates a new object. Read `perldoc perlboot` if you don't understand that.

login - login to a router
$ok = $obj->login($username, $password);

$ok = $obj->login([Name     => $username,]
                  [Password => $password,]
                  [Passcode => $passcode,] # for Secur-ID/XTACACS
                  [Prompt   => $match,]
                  [Timeout  => $secs,]);

All arguments are optional as of v1.05. Some routers don't ask for a username, they start the login conversation with a password request.

cmd - send a command
$ok = $obj->cmd($string);
$ok = $obj->cmd(String   => $string,
                [Output  => $ref,]
                [Prompt  => $match,]
                [Timeout => $secs,]
                [Cmd_remove_mode => $mode,]);

@output = $obj->cmd($string);
@output = $obj->cmd(String   => $string,
                    [Output  => $ref,]
                    [Prompt  => $match,]
                    [Timeout => $secs,]
                    [Cmd_remove_mode => $mode,]
                    [Normalize_cmd => $boolean,]);

Normalize_cmd has been added to the default Net::Telnet args. It lets you temporarily change whether backspace, delete, and kill characters are parsed in the command output. (This is performed by default)

prompt - return control to the program whenever this string occurs in router output
$matchop = $obj->prompt;

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

The default cmd_prompt changed in v1.05. It's suitable for matching prompts like router$ , router# , router> (enable) , and router(config-if)#

Let's take a closer look, shall we?

(?m:          # Net::Telnet doesn't accept quoted regexen (i.e. qr//)
          # so we need to use an embedded pattern-match modifier
          # to treat the input as a multiline buffer.

  ^           # beginning of line

    [\w.-]+       # router hostname

    \s?       # optional space

    (?:       # Strings like "(config)" and "(config-if)", "(config-line)",
          # and "(config-router)" indicate that we're in privileged
      \(config[^\)]*\) # EXEC mode (i.e. we're enabled).
    )?        # The middle backslash is only there to appear my syntax
          # highlighter.

    \s?       # more optional space

    [\$#>]        # Prompts typically end with "$", "#", or ">". Backslash
          # for syntax-highlighter.

    \s?       # more space padding

    (?:       # Catalyst switches print "(enable)" when in privileged
      \(enable\)  # EXEC mode.
    )?

    \s*       # spaces before the end-of-line aren't important to us.

  $           # end of line

)         # end of (?m:

The default prompt published in 1.03 was /^\s*[\w().-]*[\$#>]\s?(?:\(enable\))?\s*$/. As you can see, the prompt was drastically overhauled in 1.05. If your code suddenly starts timing out after upgrading Net::Telnet::Cisco, this is the first thing to investigate.

enable - enter enabled mode
$ok = $obj->enable;

$ok = $obj->enable($password);

$ok = $obj->enable([Name => $name,] [Password => $password,]
               [Passcode => $passcode,] [Level => $level,]);

This method changes privilege level to enabled mode, (i.e. root)

If a single argument is provided by the caller, it will be used as a password. For more control, including the ability to set the privilege-level, you must use the named-argument scheme.

enable() returns 1 on success and undef on failure.

is_enabled - Am I root?
$bool = $obj->is_enabled;

A trivial check to see whether we have a root-style prompt, with either the word "(enable)" in it, or a trailing "#".

Warning: this method will return false positives if your prompt has "#"s in it. You may be better off calling $obj->cmd("show privilege") instead.

disable - leave enabled mode
$ok = $obj->disable;

This method exits the router's privileged mode.

fhopen - use already open filehandle for I/O
$ok = $obj->fhopen($fh);

This method associates the open filehandle $fh with $obj for further I/O. Filehandle $fh must already be opened.

The value 1 is returned success, the error mode action is performed on failure.

ios_break - send a break (control-^)
$ok = $obj->ios_break;

You may have to use errmode(), fork, or threads to break at the an appropriate time.

last_cmd - displays the last command
$match = $obj->last_cmd;

last_cmd() will return '' if the program does not yet have a last command.

last_prompt - displays the last prompt matched by prompt()
$match = $obj->last_prompt;

last_prompt() will return '' if the program has not yet matched a prompt.

always_waitfor_prompt - waitfor and cmd prompt behaviour
$boolean = $obj->always_waitfor_prompt;

$boolean = $obj->always_waitfor_prompt($boolean);

Default value: 1

If you pass a Prompt argument to cmd() or waitfor() a String or Match, they will return control on a successful match of your argument(s) or the default prompt. Set always_waitfor_prompt to 0 to return control only for your arguments.

This method has no effect on login(). login() will always wait for a prompt.

waitfor_pause - insert a small delay before waitfor()
$boolean = $obj->waitfor_pause;

$boolean = $obj->waitfor_pause($milliseconds);

Default value: 0.1

In rare circumstances, the last_prompt is set incorrectly. By adding a very small delay before calling the parent class's waitfor(), this bug is eliminated. If you ever find reason to modify this from it's default setting, please let me know.

autopage - Turn autopaging on and off
$boolean = $obj->autopage;

$boolean = $obj->autopage($boolean);

Default value: 1

IOS pages output by default. It expects human eyes to be reading the output, not programs. Humans hit the spacebar to scroll page by page so autopage() mimicks that behaviour. This is the slow way to handle paging. See the Paging EXAMPLE for a faster way.

normalize_cmd - Turn normalization on and off
$boolean = $obj->normalize_cmd;

$boolean = $obj->normalize_cmd($boolean);

Default value: 1

IOS clears '--More--' prompts with backspaces (e.g. ^H). If you're excited by the thought of having raw control characters like ^H (backspace), ^? (delete), and ^U (kill) in your command output, turn this feature off.

Logging is unaffected by this setting.

more_prompt - Matchop used by autopage()
$matchop = $obj->prompt;

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

Default value: '/(?m:\s*--More--)/'.

Please email me if you find others.

send_wakeup - send a newline to the router at login time
$when = $obj->send_wakeup;

$when = $obj->send_wakeup( 'connect' );
$when = $obj->send_wakeup( 'timeout' );
$when = $obj->send_wakeup( 0 );

Default value: 0

Some routers quietly allow you to connect but don't display the expected login prompts. Sends a newline in the hopes that this spurs the routers to print something.

'connect' sends a newline immediately upon connection. 'timeout' sends a newline if the connection timeouts. 0 turns this feature off.

I understand this works with Livingston Portmasters.

ignore_warnings - Don't call error() for warnings
$boolean = $obj->ignore_warnings;

$boolean = $obj->ignore_warnings($boolean);

Default value: 0

Not all strings that begin with a '%' are really errors. Some are just warnings. By setting this, you are ignoring them. This will show up in the logs, but that's it.

warnings - Matchop used by ignore_warnings().
$boolean = $obj->warnings;

$boolean = $obj->warnings($matchop);

Default value:

/(?mx:^% Unknown VPN
     |^%IP routing table VRF.* does not exist. Create first$
     |^%No CEF interface information
     |^%No matching route to delete$
     |^%Not all config may be removed and may reappear after reactivating
 )/

Not all strings that begin with a '%' are really errors. Some are just warnings. Cisco calls these the CIPMIOSWarningExpressions.

EXAMPLES

Paging

v1.08 added internal autopaging support to cmd(). Whenever a '--Page--' prompt appears on the screen, we send a space right back. It works, but it's slow. You'd be better off sending one of the following commands just after login():

# To a router
$session->cmd('terminal length 0');

# To a switch
$session->cmd('set length 0');

Logging

Want to see the session transcript? Just call input_log().

e.g.
my $session = Net::Telnet::Cisco->new(Host => $router,
                  Input_log => "input.log",
                  );

See input_log() in Net::Telnet for info.

Input logs are easy-to-read translated transcripts with all of the control characters and telnet escapes cleaned up. If you want to view the raw session, see dump_log() in Net::Telnet. If you're getting tricky and using print() in addition to cmd(), you may also want to use output_log().

Big output

Trying to dump the entire BGP table? (e.g. "show ip bgp") The default buffer size is 1MB, so you'll have to increase it.

my $MB = 1024 * 1024;
$session->max_buffer_length(5 * $MB);

Sending multiple lines at once

Some commands like "extended ping" and "copy" prompt for several lines of data. It's not necessary to change the prompt for each line. Instead, send everything at once, separated by newlines.

For:

router# ping
Protocol [ip]:
Target IP address: 10.0.0.1
Repeat count [5]: 10
Datagram size [100]: 1500
Timeout in seconds [2]:
Extended commands [n]:
Sweep range of sizes [n]:

Try this:

my $protocol  = ''; # default value
my $ip       = '10.0.0.1';
my $repeat    = 10;
my $datagram  = 1500;
my $timeout   = ''; # default value
my $extended  = ''; # default value
my $sweep     = ''; # default value

$session->cmd(
"ping
$protocol
$ip
$repeat
$datagram
$timeout
$extended
$sweep
");

If you prefer, you can put the cmd on a single line and replace every static newline with the "\n" character.

e.g.

$session->cmd("ping\n$protocol\n$ip\n$repeat\n$datagram\n"
        . "$timeout\n$extended\n$sweep\n");

Backup via TFTP

Backs up the running-confg to a TFTP server. Backup file is in the form "router-confg". Make sure that file exists on the TFTP server or the transfer will fail!

my $backup_host  = "tftpserver.somewhere.net";
my $device       = "cisco.somewhere.net";
my $type         = "router"; # or "switch";
my $ios_version  = 12;

my @out;
if ($type eq "router") {
    if ($ios_version >= 12) {
        @out = $session->cmd("copy system:/running-config "
              . "tftp://$backup_host/$device-confg\n\n\n");
    } elsif ($ios_version >= 11) {
        @out = $session->cmd("copy running-config tftp\n$backup_host\n"
              . "$device-confg\n");
    } elsif ($ios_version >= 10) {
        @out = $session->cmd("write net\n$backup_host\n$device-confg\n\n");
    }
} elsif ($type eq "switch") {
    @out = $session->cmd("copy system:/running-config "
              . "tftp://$backup_host/$device-confg\n\n\n");
}

SUPPORT

http://NetTelnetCisco.sourceforge.net/

Mailing lists

nettelnetcisco-announce is for important security bulletins and upgrades. Very low traffic, no spam, HIGHLY RECOMMENDED! http://lists.sourceforge.net/lists/listinfo/nettelnetcisco-announce

nettelnetcisco-users is for usage discussion, help, tips, tricks, etc. http://lists.sourceforge.net/lists/listinfo/nettelnetcisco-users

nettelnetcisco-devel is for uber-hackers; you know who you are. http://lists.sourceforge.net/lists/listinfo/nettelnetcisco-devel

Help/discussion forums

http://sourceforge.net/forum/?group_id=48856

Bug tracker

http://sourceforge.net/tracker/?group_id=48856

SEE ALSO

Net::Telnet

Net::SNMP

UCD NetSNMP - http://www.netsnmp.org/

RAT/NCAT - http://ncat.sourceforge.net/

AUTHOR

Joshua_Keroes@eli.net $Date: 2002/06/18 17:17:03 $

It would greatly amuse the author if you would send email to him and tell him how you are using Net::Telnet::Cisco.

As of Mar 2002, 170 people have emailed me. N::T::C is used to help manage over 14,000 machines! Keep the email rolling in!

THANKS

The following people understand what Open Source Software is all about. Thanks Brian Landers, Aaron Racine, Niels van Dijke, Tony Mueller, Frank Eickholt, Al Sorrell, Jebi Punnoose, Christian Alfsen, Niels van Dijke, Kevin der Kinderen, Ian Batterbee, Leonardo Cont, Steve Meier, and Andre Bonhote.

Institutions: infobot.org #perl, perlmonks.org, sourceforge.net, the geeks at geekhouse.org, and eli.net.

Send in a patch and we can make the world a better place.

COPYRIGHT AND LICENSE

Copyright (c) 2000-2002 Joshua Keroes, Electric Lightwave Inc. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.