/usr/share/perl5/Net/Telnet/Cisco.pm is in libnet-telnet-cisco-perl 1.10-5.2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 | package Net::Telnet::Cisco;
#-----------------------------------------------------------------
# Net::Telnet::Cisco - interact with a Cisco router
#
# $Id: Cisco.pm,v 1.11 2002/12/31 00:12:32 jkeroes Exp $
#
# Code wraps at 120 chars/line. Join us.
#
# TODO: Use hash as object base instead of filestream.
#
# POD documentation at end of file.
#
#-----------------------------------------------------------------
require 5.005;
use strict;
use Net::Telnet 3.03;
use AutoLoader;
use Carp;
use vars qw($AUTOLOAD @ISA $VERSION $DEBUG);
@ISA = qw(Net::Telnet);
$VERSION = '1.10_085';
$^W = 1;
$DEBUG = 0;
$|++;
#------------------------------
# Public Methods
#------------------------------
sub new {
my $class = shift;
my ($self, $host, %args);
# Add default prompt to args if none present.
push @_, (-Prompt =>
'/(?m:^[\r\b]?[\w.-]+\s?(?:\(config[^\)]*\))?\s?[\$\#>]\s?(?:\(enable\))?\s*$)/')
unless grep /^-?prompt$/i, @_;
# There's a new cmd_prompt in town.
$self = $class->SUPER::new(@_) or return;
# *Must* define all defaults here. They're used below to parse incoming args.
*$self->{net_telnet_cisco} = {
last_prompt => '',
last_cmd => '',
waitfor_pause => 0.1,
always_waitfor_prompt => 1,
autopage => 1,
normalize_cmd => 1,
send_wakeup => 0,
ignore_warnings => 0,
more_prompt => '/(?m:^[\s\0]*--More--)/',
errors => '/(?mx:^Unknown\ command\ "[^\"]*"\ Use\ \'help\'\ for\ more\ info
|\%\ Unknown\ command\ or\ computer\ name
)/',
warnings => '/(?mx:^%\s?Unknown\ VPN
|^\%\s?IP\ routing\ table\ VRF.*\ does\ not\ exist\.\ Create\ first$
|^\%\s?No\ CEF\ interface\ information
|^\%\s?No\ matching\ route\ to\ delete$
|^\%\s?Not\ all\ config\ may\ be\ removed\ and\ may\ reappear\ after\ reactivating
|^\%\s?Warning:
)/',
};
if (@_ == 2) { # one positional arg given
$host = $_[1];
} elsif (@_ > 2) { # named args
%args = @_;
## Parse the errmode named arg first then all other named args.
foreach my $method ( 'errmode', keys %{ * $self->{net_telnet_cisco} } ) {
for ( grep defined, @args{$method, "-$method", "\u\L$method", "-\u\L$method" } ) {
$self->$method( $_ );
}
}
}
$self;
} # end sub new
# The new prompt() stores the last matched prompt for later
# fun 'n amusement. You can access this string via $self->last_prompt.
#
# It also parses out any router errors and stores them in the
# correct place, where they can be acccessed/handled by the
# Net::Telnet error methods.
#
# No POD docs for prompt(); these changes should be transparent to
# the end-user.
sub prompt {
my( $self, $prompt ) = @_;
my( $prev, $stream );
$stream = $ {*$self}{net_telnet_cisco};
$prev = $self->SUPER::prompt;
## Parse args.
if ( @_ == 2 ) {
defined $prompt or $prompt = '';
$self->_match_check($prompt);
$self->SUPER::prompt($prompt);
} elsif (@_ > 2) {
return $self->error('usage: $obj->prompt($match_op)');
}
return $prev;
} # end sub prompt
# cmd() now parses errors and sticks 'em where they belong.
#
# This is a routerish error:
# routereast#show asdf
# ^
# % Invalid input detected at '^' marker.
#
# "show async" is valid, so the "d" of "asdf" raised an error.
#
# If an error message is found, the following error message
# is sent to Net::Telnet's error()-handler:
#
# Last command and router error:
# <last command prompt> <last command>
# <error message fills remaining lines>
sub cmd {
my $self = shift;
my $ok = 1;
select((select($self), $|=1)[$[]); # don't buffer writes
my $normalize = $self->normalize_cmd;
my @page_args;
# Parse args
if (@_ == 1) {
$ {*$self}{net_telnet_cisco}{last_cmd} = $_[0];
} elsif ( @_ >= 2 ) {
my @args = @_;
while (my ($k, $v) = splice @args, 0, 2) {
$ {*$self}{net_telnet_cisco}{last_cmd} = $v if $k =~ /^-?[Ss]tring$/;
$normalize = $v if $k =~ /^-?[Nn]ormalize_cmd$/;
# Save some arguments for autopaging
next if $k =~ /^(?:-?[Ss]tring|-?[Cc]md_remove_mode)$/;
push @page_args, $k, $v;
}
}
my $cmd = $ {*$self}{net_telnet_cisco}{last_cmd};
my $old_ors = $self->output_record_separator;
my $need_more = 0;
my @out;
$ {*$self}{net_telnet_cisco}{err} = 0;
while($ {*$self}{net_telnet_cisco}{err} == 0) {
# Send a space (with no newline) whenever we see a "More" prompt.
if ($need_more) {
$self->output_record_separator('');
# We saw a more prompt, so put it in the command output.
#
# Send the <space>, taking care not to discard the top line.
# Also need to send the user's args to this:
my @tmp =
( $self->last_prompt,
$self->SUPER::cmd(String => " ",
Cmd_remove_mode => 0,
Prompt => $self->more_prompt,
@page_args,
)
);
push @out, $self->normalize_cmd
? _normalize(@tmp)
: @tmp;
} else {
$self->output_record_separator($old_ors);
if (scalar @_ == 1) {
push @out, $self->autopage
? $self->SUPER::cmd( -Prompt => $self->more_prompt,
-String => +shift )
: $self->SUPER::cmd( +shift );
} else {
push @out, $self->autopage
? $self->SUPER::cmd( -Prompt => $self->more_prompt,
@_ )
: $self->SUPER::cmd( @_ );
}
}
if ($self->find_errors(@out) ) {
$ok = 0;
last;
}
# Restore old settings
$self->output_record_separator($old_ors);
# redo the while loop if we saw a More prompt.
my $more_re = $self->re_sans_delims($self->more_prompt);
if ($self->autopage && ( $self->last_prompt =~ /$more_re/
|| $out[-1] =~ /$more_re/ )
) {
$need_more = 1;
} else {
last;
}
}
return wantarray ? @out : $ok;
}
sub find_errors {
my ($self, @out) = @_;
my $stream = $ {*$self}{net_telnet_cisco};
my $cmd = $stream->{last_cmd};
my $is_err = 0;
# Look for errors in output
for ( my ($i, $lastline) = (0, '');
$i <= $#out;
$lastline = $out[$i++] ) {
# This may have to be a pattern match instead.
if ( ( substr $out[$i], 0, 1 ) eq '%' ) {
if ( $out[$i] =~ /'\^' marker/ ) { # Typo & bad arg errors
chomp $lastline;
$self->error( join "\n",
"Last command and router error: ",
( $self->last_prompt . $cmd ),
$lastline,
$out[$i],
);
splice @out, $i - 1, 3;
} else { # All other errors.
chomp $out[$i];
$self->error( join "\n",
"Last command and router error: ",
( $self->last_prompt . $cmd ),
$out[$i],
);
splice @out, $i, 2;
}
$is_err++;
# Handle special case errors
} elsif ($stream->{errors}) {
my $errors_re = $self->re_sans_delims($stream->{errors});
if ( $out[$i] =~ /$errors_re/ ) {
chomp $out[$i];
$self->error( join "\n",
"Last command and router error: ",
( $self->last_prompt . $cmd ),
$out[$i],
);
# XXX: splice out correct number of lines. This isn't flexible.
# Sure wish I had a CatOS box to experiment with. Cisco, are
# you listening? :-)
splice @out, $i, 2;
$is_err++;
}
}
}
return $is_err;
}
# waitfor now stores prompts to $obj->last_prompt()
sub waitfor {
my $self = shift;
return unless @_;
# $all_prompts will be built into a regex that matches all currently
# valid prompts.
#
# -Match args will be added to this regex. The current prompt will
# be appended when all -Matches have been exhausted.
my $all_prompts = '';
# Literal string matches, passed in with -String.
my @literals = ();
# Parse the -Match => '/prompt \$' type options
# waitfor can accept more than one -Match argument, so we can't just
# hashify the args.
if (@_ >= 2) {
my @args = @_;
while ( my ($k, $v) = splice @args, 0, 2 ) {
if ($k =~ /^-?[Ss]tring$/) {
push @literals, $v;
} elsif ($k =~ /^-?[Mm]atch$/) {
$all_prompts = $self->prompt_append($all_prompts, $v);
}
}
} elsif (@_ == 1) {
# A single argument is always a -match.
$all_prompts = $self->prompt_append($all_prompts, $_[0]);
}
my $all_re = $self->re_sans_delims($all_prompts);
my $prompt_re = $self->re_sans_delims($self->prompt);
my $more_re = $self->re_sans_delims($self->more_prompt);
# Add the current prompt if it's not already there. You can turn this behavior
# off by setting always_waitfor_prompt to a false value.
if ($self->always_waitfor_prompt && index($all_re, $prompt_re) == -1) {
unshift @_, "-Match" if @_ == 1;
push @_, (-Match => $self->prompt);
$all_prompts = $self->prompt_append($all_prompts, $self->prompt);
$all_re = $self->re_sans_delims($all_prompts);
}
# Add the more prompt if it's not present. See autopage() docs
# to turn this behaviour off.
if ($self->autopage && index($all_re, $more_re) == -1) {
unshift @_, "-Match" if @_ == 1;
push @_, (-Match => $self->more_prompt);
$all_prompts = $self->prompt_append($all_prompts, $self->more_prompt);
$all_re = $self->re_sans_delims($all_prompts);
}
return $self->error("Godot ain't home - waitfor() isn't waiting for anything.")
unless $all_prompts || @literals;
# There's a timing issue that I can't quite figure out.
# Adding a small pause here seems to make it go away.
select undef, undef, undef, $self->waitfor_pause;
my ($prematch, $match) = $self->SUPER::waitfor(@_);
# If waitfor saw a prompt then store it.
if ($match) {
for (@literals) {
if (index $match, $_) {
return wantarray ? ($prematch, $match) : 1;
}
}
if ($match =~ /($all_re)/m ) {
$ {*$self}{net_telnet_cisco}{last_prompt} = $1;
return wantarray ? ($prematch, $match) : 1;
}
}
return wantarray ? ( $prematch, $match ) : 1;
}
sub login {
my($self) = @_;
my(
$cmd_prompt,
$endtime,
$error,
$lastline,
$match,
$orig_errmode,
$orig_timeout,
$prematch,
$reset,
$timeout,
$usage,
$sent_wakeup,
);
my ($username, $password, $tacpass, $passcode ) = ('') x 4;
my (%args, %seen);
local $_;
select((select($self), $|=1)[$[]); # don't buffer writes
## Init vars.
$timeout = $self->timeout;
$self->timed_out('');
return if $self->eof;
$cmd_prompt = $self->prompt;
$sent_wakeup = 0;
print "login:\t[orig: $cmd_prompt]\n" if $DEBUG;
$usage = 'usage: $obj->login([Name => $name,] [Password => $password,] '
. '[Passcode => $passcode,] [Prompt => $matchop,] [Timeout => $secs,])';
if (@_ == 3) { # just username and passwd given
($username, $password) = (@_[1,2]);
}
else { # named args given
## Get the named args.
(undef, %args) = @_;
## Parse the named args.
foreach (keys %args) {
if (/^-?name$/i) {
$username = $args{$_};
} elsif (/^-?passw/i) {
$password = $args{$_};
} elsif (/^-?passcode/i) {
$passcode = $args{$_};
} elsif (/^-?prompt$/i) {
# login() always looks for a cmd_prompt. This is not
# controllable via always_waitfor_prompt().
$cmd_prompt = $self->prompt_append($cmd_prompt, $args{$_});
} elsif (/^-?timeout$/i) {
$timeout = _parse_timeout($args{$_});
} else {
return $self->error($usage);
}
}
}
print "login:\t[after args: $cmd_prompt]\n" if $DEBUG;
## Override these user set-able values.
$endtime = _endtime($timeout);
$orig_timeout = $self->timeout($endtime);
$orig_errmode = $self->errmode;
## Create a subroutine to reset to original values.
$reset
= sub {
$self->errmode($orig_errmode);
$self->timeout($orig_timeout);
1;
};
## Create a subroutine to generate an error for user.
$error
= sub {
my($errmsg) = @_;
&$reset;
if ($self->timed_out) {
return $self->error($errmsg);
} elsif ($self->eof) {
($lastline = $self->lastline) =~ s/\n+//;
return $self->error($errmsg, ": ", $lastline);
} else {
return $self->error($self->errmsg);
}
};
# Send a newline as the wakeup-call
if ($self->send_wakeup eq 'connect') {
$sent_wakeup = 1;
my $old_sep = $self->output_record_separator;
$self->output_record_separator("\n");
$self->print('');
$self->output_record_separator($old_sep);
}
while (1) {
(undef, $_) = $self->waitfor(
-match => '/(?:[Ll]ogin|[Uu]sername|[Pp]assw(?:or)?d)[:\s]*$/',
-match => '/(?i:Passcode)[:\s]*$/',
-match => $cmd_prompt,
);
unless ($_) {
return &$error("read eof waiting for login or password prompt")
if $self->eof;
# We timed-out. Send a newline as the wakeup-call.
if ($sent_wakeup == 0 && $self->send_wakeup eq 'timeout') {
$sent_wakeup = 1;
my $old_sep = $self->output_record_separator;
$self->output_record_separator("\n");
$self->print('');
$self->output_record_separator($old_sep);
next;
}
return &$error("timed-out during login process");
}
my $cmd_prompt_re = $self->re_sans_delims($cmd_prompt);
if (not defined) {
return $self->error("login failed: access denied or bad name, passwd, etc");
} elsif (/sername|ogin/) {
$self->print($username) or return &$error("login disconnected");
$seen{login}++ && $self->error("login failed: access denied or bad username");
} elsif (/[Pp]assw/) {
$self->print($password) or return &$error("login disconnected");
$seen{passwd}++ && $self->error("login failed: access denied or bad password");
} elsif (/(?i:Passcode)/) {
$self->print($passcode) or return &$error("login disconnected");
$seen{passcode}++ && $self->error("login failed: access denied or bad passcode");
} elsif (/($cmd_prompt_re)/) {
&$reset; # Success. Reset obj to default vals before continuing.
last;
} else {
$self->error("login received unexpected prompt. Aborting.");
}
}
1;
} # end sub login
# Overridden to support ignore_warnings()
# Also sets err flag
sub error {
my $self = shift;
my $stream = $ {*$self}{net_telnet_cisco};
$stream->{err} = 1;
# Ignore warnings
if ($self->ignore_warnings) {
my $errmsg = join '', @_;
my $warnings_re = $self->re_sans_delims($stream->{warnings});
return if $errmsg =~ /$warnings_re/;
}
return $self->SUPER::error(@_);
}
# Tries to enter enabled mode with the password arg.
sub enable {
my $self = shift;
my $usage = 'usage: $obj->enable([Name => $name,] [Password => $password,] '
. '[Passcode => $passcode,] [Level => $level] )';
my ($en_username, $en_password, $en_passcode, $en_level) = ('') x 4;
my ($error, $lastline, $orig_errmode, $reset, %args, %seen);
select((select($self), $|=1)[$[]); # don't buffer writes
if (@_ == 1) { # just passwd given
($en_password) = shift;
} else { # named args given
%args = @_;
foreach (keys %args) {
if (/^-?name$|^-?login$|^-?user/i) {
$en_username = $args{$_};
} elsif (/^-?passw/i) {
$en_password = $args{$_};
} elsif (/^-?passc/i) {
$en_passcode = $args{$_};
} elsif (/^-?level$/i) {
$en_level = $args{$_};
} else {
return $self->error($usage);
}
}
}
## Create a subroutine to generate an error for user.
$error = sub {
my($errmsg) = @_;
if ($self->timed_out) {
return $self->error($errmsg);
} elsif ($self->eof) {
($lastline = $self->lastline) =~ s/\n+//;
return $self->error($errmsg, ": ", $lastline);
} else {
return $self->error($errmsg);
}
};
return &$error("enable() failed: -Level was passed an undef.")
unless defined $en_level;
# Store the old prompt without the //s around it.
my ($old_prompt) = $self->re_sans_delims($self->prompt);
# We need to expect either a Password prompt or a typical
# prompt. If the user doesn't have enough access to run the
# 'enable' command, the device won't even query for a password, it
# will just ignore the command and display another [boring] prompt.
$self->print("enable $en_level");
{
my ($prematch, $match) = $self->waitfor(
-match => '/[Ll]ogin[:\s]*$/',
-match => '/[Uu]sername[:\s]*$/',
-match => '/[Pp]assw(?:or)?d[:\s]*$/',
-match => '/(?i:Passcode)[:\s]*$/',
-match => "/$old_prompt/",
) or do {
return &$error("read eof waiting for enable login or password prompt")
if $self->eof;
return &$error("timed-out waiting for enable login or password prompt");
};
if (not defined $match) {
return &$error("enable failed: access denied or bad name, passwd, etc.");
} elsif ($match =~ /sername|ogin/) {
$self->print($en_username) or return &$error("enable failed");
$seen{login}++
&& return &$error("enable failed: access denied or bad username");
redo;
} elsif ($match =~ /[Pp]assw/ ) {
$self->print($en_password) or return &$error("enable failed");
$seen{passwd}++
&& return &$error("enable failed: access denied or bad password");
redo;
} elsif ($match =~ /(?i:Passcode)/ ) {
$self->print($en_passcode) or return &$error("enable failed");
$seen{passcode}++
&& return &$error("enable failed: access denied or bad passcode");
redo;
} elsif ($match =~ /$old_prompt/) {
## Success! Exit the block.
last;
} else {
return &$error("enable received unexpected prompt. Aborting.");
}
}
if (not $en_level or $en_level =~ /^[1-9]/) {
# Prompts and levels over 1 give a #/(enable) prompt.
return $self->is_enabled ? 1 : &$error('Failed to enter enable mode');
} else {
# Assume success
return 1;
}
}
# Leave enabled mode.
sub disable {
my $self = shift;
select((select($self), $|=1)[$[]); # don't buffer writes
$self->cmd('disable');
return $self->is_enabled ? $self->error('Failed to exit enabled mode') : 1;
}
# Send control-^ (without newline)
sub ios_break {
my $self = shift;
select((select($self), $|=1)[$[]); # don't buffer writes
my $old_ors = $self->output_record_separator;
$self->output_record_separator('');
my $ret = $self->print("\c^b", @_);
$self->output_record_separator($old_ors);
return $ret;
}
# Displays the last prompt.
sub last_prompt {
my $self = shift;
my $stream = $ {*$self}{net_telnet_cisco};
exists $stream->{last_prompt} ? $stream->{last_prompt} : undef;
}
# Displays the last command.
sub last_cmd {
my $self = shift;
my $stream = $ {*$self}{net_telnet_cisco};
exists $stream->{last_cmd} ? $stream->{last_cmd} : undef;
}
# Examines the last prompt to determine the current mode.
# Some prompts may be hard set to #, so this won't always return a valid answer.
# This is a pretty weak heuristic. $session->cmd('show priv') is the better way.
#
# 1 => enabled.
# undef => not enabled.
sub is_enabled { $_[0]->last_prompt =~ /\#|enable|config/ ? 1 : undef }
# Create all get/set methods:
for my $sub (qw/always_waitfor_prompt waitfor_pause autopage
normalize_cmd send_wakeup ignore_warnings/) {
no strict 'refs';
*$sub = sub {
my ($self, $arg) = @_;
my $stream = $ {*$self}{net_telnet_cisco};
$stream->{$sub} = $arg if defined $arg;
return $stream->{$sub};
};
}
# Creates all prompt get/set methods:
for my $sub (qw/errors warnings more_prompt/) {
no strict 'refs';
*$sub = sub {
my ($self, $arg) = @_;
my $stream = $ {*$self}{net_telnet_cisco};
if (defined $arg) {
$self->_match_check($arg);
$stream->{$sub} = $arg;
}
return $stream->{$sub};
}
}
# Join two or more regexen into one on "|".
sub prompt_append {
my $self = shift;
my $orig = shift || '';
return $self->error("usage: \$obj->prompt_append(orig, new, [new...])")
unless @_;
print "prompt_append:\t[original: $orig]\n" if $DEBUG;
if ($orig) {
if ($self->_match_check($orig)) {
$orig = $self->re_sans_delims($orig);
return $self->error("Can't parse prompt: '$orig'") unless $orig;
}
}
for (@_) {
print "prompt_append:\t[append: $_]\n" if $DEBUG;
if ($self->_match_check($_)) {
my $re = $self->re_sans_delims($_);
unless ($re) {
$self->error("Can't parse prompt: '$_'");
next;
}
$orig .= $orig ? "|$re" : $re;
}
}
print "prompt_append:\t[return: /$orig/]\n\n" if $DEBUG;
return "/$orig/";
}
# Return a Net::Telnet regular expression without the delimiters.
# XXX: an excellent candidate for memoization.
sub re_sans_delims {
my ($self, $str) = @_;
return $self->error("usage: \$obj->re_sans_delims(\$matchop)")
unless $str;
$self->_match_check($str);
my ($delim, $re) = $str =~ /^\s*m?\s*(\W)(.*)\1\s*$/ms;
return $re;
}
#------------------------------
# Private methods
#------------------------------
# strip backspaces, deletes, kills, and the character they
# pertain to, from an array.
sub _normalize {
$_ = join "", @_;
1 while s/[^\cH\c?][\cH\c?]//mg; # ^H ^?
s/^.*\cU//mg; # ^U
return wantarray ? split /$/, $_ : $_; # ORS instead?
}
# Lifted from Net::Telnet en toto
sub _match_check {
my ($self, $code) = @_;
return unless $code;
my $error;
my @warns = ();
print "_match_check:\t[Checking: $code]\n" if $DEBUG;
## Use eval to check for syntax errors or warnings.
{
local $SIG{'__DIE__'} = 'DEFAULT';
local $SIG{'__WARN__'} = sub { push @warns, @_ };
local $^W = 1;
local $_ = '';
eval "\$_ =~ $code;";
}
if ($@) {
## Remove useless lines numbers from message.
($error = $@) =~ s/ at \(eval \d+\) line \d+.?//;
chomp $error;
return $self->error("bad match operator: $error");
}
elsif (@warns) {
## Remove useless lines numbers from message.
($error = shift @warns) =~ s/ at \(eval \d+\) line \d+.?//;
$error =~ s/ while "strict subs" in use//;
chomp $error;
return $self->error("bad match operator: $error");
}
1;
} # end sub _match_check
#------------------------------
# Class methods
#------------------------------
# Look for subroutines in Net::Telnet if we can't find them here.
# This ranks a 4 on the OOP naughtiness scale.
sub AUTOLOAD {
my ($self) = @_;
confess "$AUTOLOAD passed an [unexpected] object, aborting" if ref $self;
$AUTOLOAD =~ s/.*::/Net::Telnet::/;
goto &$AUTOLOAD;
}
1;
__END__
#------------------------------------------------------------
# Docs
#------------------------------------------------------------
=head1 NAME
Net::Telnet::Cisco - interact with a Cisco router
=head1 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;
=head1 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-E<gt>errmsg(), so that
errmode can be used to perform automatic error-handling actions.
=head1 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.
=head1 METHODS
=over 4
=item B<new> - create new Net::Telnet::Cisco object
$session = Net::Telnet::Cisco->new(
[Autopage => $boolean,] # 1
[More_prompt => $matchop,] # '/(?m:^[\s\0]*--More--)/',
[Always_waitfor_prompt => $boolean,] # 1
[Waitfor_pause => $milliseconds,] # 0.1
[Normalize_cmd => $boolean,] # 1
[Send_wakeup => $when,] # 0
[Ignore_warnings => $boolean,] # 0
[Warnings => $matchop,] # see docs
[Errors => $matchop,] # see docs
# Net::Telnet arguments
[Binmode => $mode,]
[Cmd_remove_mode => $mode,]
[Dump_Log => $filename,]
[Errmode => $errmode,]
[Fhopen => $filehandle,]
[Host => $host,]
[Input_log = => $file,]
[Input_record_separator => $chars,]
[Option_log => $file,]
[Ors = => $chars,]
[Output_log => $file,]
[Output_record_separator => $chars,]
[Port => $port,]
[Prompt = => $matchop,] # see docs
[Rs => $chars,]
[Telnetmode => $mode,]
[Timeout => $secs,]);
);
Creates a new object. Read `perldoc perlboot` if you don't understand that.
=item B<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.
=item B<cmd> - send a command
$ok = $obj->cmd($string);
$ok = $obj->cmd(String => $string,
[Output => $ref,]
[Cmd_remove_mode => $mode,]
[Errmode => $mode,]
[Input_record_separator => $chars,]
[Ors => $chars,]
[Output_record_separator => $chars,]
[Prompt => $match,]
[Rs => $chars,]
[Timeout => $secs,]);
@output = $obj->cmd($string);
@output = $obj->cmd(String => $string,
[Output => $ref,]
[Cmd_remove_mode => $mode,]
[Errmode => $mode,]
[Input_record_separator => $chars,]
[Ors => $chars,]
[Output_record_separator => $chars,]
[Prompt => $match,]
[Rs => $chars,]
[Timeout => $secs,]);
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)
=item B<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 C<router$ >, C<router# >, C<routerE<gt>
(enable) >, and C<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
\r? # optional linefeed
[\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
C</^\s*[\w().-]*[\$#E<gt>]\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.
=item B<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.
=item B<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 "#".
B<Warning>: this method will return false positives if your prompt has
"#"s in it. You may be better off calling C<$obj-E<gt>cmd("show
privilege")> instead.
=item B<disable> - leave enabled mode
$ok = $obj->disable;
This method exits the router's privileged mode.
=item B<ios_break> - send a break (control-^)
$ok = $obj->ios_break( [ additional strings to print, ... ] );
You may have to use errmode(), fork, or threads to break at the
an appropriate time.
=item B<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.
=item B<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.
=item B<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.
=item B<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.
=item B<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.
=item B<more_prompt> - Matchop used by autopage()
$matchop = $obj->prompt;
$prev = $obj->prompt($matchop);
Default value: '/(?m:^(?:[\s\0]*--More--)/',
Please email me if you find others.
=item B<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.
=item B<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.
=item B<warnings> - Matchop used by ignore_warnings().
$boolean = $obj->warnings;
$boolean = $obj->warnings($matchop);
Default value:
'/(?mx:^%\s?Unknown\ VPN
|^%\s?IP\ routing\ table\ VRF.*\ does\ not\ exist\.\ Create\ first$
|^%\s?No\ CEF\ interface\ information
|^%\s?No\ matching\ route\ to\ delete$
|^%\s?Not\ all\ config\ may\ be\ removed\ and\ may\ reappear\ after\ reactivating
|^%\s?Warning:
)/',
Not all strings that begin with a '%' are really errors. Some are just
warnings. Cisco calls these the CIPMIOSWarningExpressions.
=item B<errors> - Matchop used to catch special-cased errors.
$boolean = $obj->errors;
$boolean = $obj->errors($matchop);
Default value:
'/(?mx:^Unknown\ command\ "[^\"]*"\ Use\ \'help\'\ for\ more\ info\.)/',
Some errors don't begin with a '%'. Trap them here.
=back
=head1 EXAMPLES
=head2 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');
=head2 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 L<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 L<Net::Telnet>. If you're getting
tricky and using print() in addition to cmd(), you may also want to use
output_log().
=head2 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);
=head2 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");
=head2 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");
}
=head2 Sending control characters
Use print() if you expect to get a prompt back.
Use cmd() if you don't.
$session->print("\c^"); # send control-^
$session->cmd("\cZ"); # send control-Z
See also: C<ios_break()>
=head1 SUPPORT
http://NetTelnetCisco.sourceforge.net/
=head2 Mailing lists
I<nettelnetcisco-announce> is for important security bulletins and upgrades. Very low traffic, no spam, B<HIGHLY RECOMMENDED!>
http://lists.sourceforge.net/lists/listinfo/nettelnetcisco-announce
I<nettelnetcisco-users> is for usage discussion, help, tips, tricks, etc.
http://lists.sourceforge.net/lists/listinfo/nettelnetcisco-users
I<nettelnetcisco-devel> is for uber-hackers; you know who you are.
http://lists.sourceforge.net/lists/listinfo/nettelnetcisco-devel
=head2 Help/discussion forums
http://sourceforge.net/forum/?group_id=48856
=head2 Bug tracker
http://sourceforge.net/tracker/?group_id=48856
=head1 SEE ALSO
L<Net::Telnet>
L<Net::SNMP>
UCD NetSNMP - http://www.netsnmp.org/
RAT/NCAT - http://ncat.sourceforge.net/
=head1 AUTHOR
Joshua_Keroes@eli.net $Date: 2002/12/31 00:12:32 $
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, over 200 people have emailed me or posted to the
Net::Telnet::Cisco site. N::T::C is used to help manage over 14,000
machines! Keep the email rolling in!
=head1 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, Andre Bonhote, Rob Patrick, FtR, James "mcaizjb3" Brown,
and Hiro "Paul" Protagonist.
Paul gets a ++ for code-ninja skills.
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.
=head1 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.
|