SHARE
TWEET

jlogin

a guest Mar 29th, 2011 108 Never
  1. /usr/lib/rancid/bin$ cat jlogin
  2. #! /usr/bin/expect --
  3. ##
  4. ## $Id: jlogin.in,v 1.69 2009/04/16 21:22:57 heas Exp $
  5. ##
  6. ## rancid 2.3.2
  7. ## Copyright (c) 1997-2009 by Terrapin Communications, Inc.
  8. ## All rights reserved.
  9. ##
  10. ## This code is derived from software contributed to and maintained by
  11. ## Terrapin Communications, Inc. by Henry Kilmer, John Heasley, Andrew Partan,
  12. ## Pete Whiting, Austin Schutz, and Andrew Fort.
  13. ##
  14. ## Redistribution and use in source and binary forms, with or without
  15. ## modification, are permitted provided that the following conditions
  16. ## are met:
  17. ## 1. Redistributions of source code must retain the above copyright
  18. ##    notice, this list of conditions and the following disclaimer.
  19. ## 2. Redistributions in binary form must reproduce the above copyright
  20. ##    notice, this list of conditions and the following disclaimer in the
  21. ##    documentation and/or other materials provided with the distribution.
  22. ## 3. All advertising materials mentioning features or use of this software
  23. ##    must display the following acknowledgement:
  24. ##        This product includes software developed by Terrapin Communications,
  25. ##        Inc. and its contributors for RANCID.
  26. ## 4. Neither the name of Terrapin Communications, Inc. nor the names of its
  27. ##    contributors may be used to endorse or promote products derived from
  28. ##    this software without specific prior written permission.
  29. ## 5. It is requested that non-binding fixes and modifications be contributed
  30. ##    back to Terrapin Communications, Inc.
  31. ##
  32. ## THIS SOFTWARE IS PROVIDED BY Terrapin Communications, INC. AND CONTRIBUTORS
  33. ## ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
  34. ## TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  35. ## PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COMPANY OR CONTRIBUTORS
  36. ## BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  37. ## CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  38. ## SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  39. ## INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  40. ## CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  41. ## ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  42. ## POSSIBILITY OF SUCH DAMAGE.
  43. #
  44. #  The expect login scripts were based on Erik Sherk's gwtn, by permission.
  45. #
  46. # jlogin - juniper login
  47. #
  48. # Most options are intuitive for logging into a Cisco router.
  49. # The default username password is the same as the vty password.
  50. #
  51.  
  52. # Usage line
  53. set usage "Usage: $argv0 \[-dSV\] \[-c command\] \[-Evar=x\] \
  54. \[-f cloginrc-file\] \[-p user-password\] \[-r passphrase\] \[-s script-file\] \
  55. \[-u username\] \[-t timeout\] \[-x command-file\] \[-y ssh_cypher_type\] \
  56. router \[router...\]\n"
  57.  
  58. # env(CLOGIN) may contain the following chars:
  59. #       x == do not set xterm banner or name
  60.  
  61. # Password file
  62. set password_file $env(HOME)/.cloginrc
  63. # Default is to login to the router
  64. set do_command 0
  65. set do_script 0
  66. # The default is to automatically enable
  67. set avenable 1
  68. # The default is to look in the password file to find the passwords.  This
  69. # tracks if we receive them on the command line.
  70. set do_passwd 1
  71. # Save config, if prompted
  72. set do_saveconfig 0
  73.  
  74. # Find the user in the ENV, or use the unix userid.
  75. if {[ info exists env(CISCO_USER) ]} {
  76.     set default_user $env(CISCO_USER)
  77. } elseif {[ info exists env(USER) ]} {
  78.     set default_user $env(USER)
  79. } elseif {[ info exists env(LOGNAME) ]} {
  80.     set default_user $env(LOGNAME)
  81. } else {
  82.     # This uses "id" which I think is portable.  At least it has existed
  83.     # (without options) on all machines/OSes I've been on recently -
  84.     # unlike whoami or id -nu.
  85.     if [ catch {exec id} reason ] {
  86.         send_error "\nError: could not exec id: $reason\n"
  87.         exit 1
  88.     }
  89.     regexp {\(([^)]*)} "$reason" junk default_user
  90. }
  91. if {[ info exists env(CLOGINRC) ]} {
  92.     set password_file $env(CLOGINRC)
  93. }
  94.  
  95. # Sometimes routers take awhile to answer (the default is 10 sec)
  96. set timeout 120
  97.  
  98. # Process the command line
  99. for {set i 0} {$i < $argc} {incr i} {
  100.     set arg [lindex $argv $i]
  101.  
  102.     switch  -glob -- $arg {
  103.         # Command to run.
  104.         -c* -
  105.         -C* {
  106.             if {! [  regexp .\[cC\](.+) $arg ignore command]} {
  107.                 incr i
  108.                 set command [ lindex $argv $i ]
  109.             }
  110.             set do_command 1
  111.         # Expect debug mode
  112.         } -d* {
  113.             exp_internal 1
  114.         # Environment variable to pass to -s scripts
  115.         } -E* {
  116.             if {[ regexp .\[E\](.+)=(.+) $arg ignore varname varvalue]} {
  117.                 set E$varname $varvalue
  118.             } else {
  119.                 send_user "\nError: invalid format for -E in $arg\n"
  120.                 exit 1
  121.             }
  122.         # alternate cloginrc file
  123.         } -f* {
  124.             if {! [ regexp .\[fF\](.+) $arg ignore password_file]} {
  125.                 incr i
  126.                 set password_file [ lindex $argv $i ]
  127.             }
  128.         # user Password
  129.         } -p* {
  130.             if {! [  regexp .\[pP\](.+) $arg ignore userpasswd]} {
  131.                 incr i
  132.                 set userpasswd [ lindex $argv $i ]
  133.             }
  134.             set do_passwd 0
  135.         # Version string
  136.         } -V* {
  137.             send_user "rancid 2.3.2\n"
  138.             exit 0
  139.         # passphrase
  140.         } -r* {
  141.             if {! [  regexp .\[rR\](.+) $arg ignore passphrase]} {
  142.                 incr i
  143.                 set avpassphrase [ lindex $argv $i ]
  144.             }
  145.         # Expect script to run.
  146.         } -s* {
  147.             if {! [  regexp .\[sS\](.+) $arg ignore sfile]} {
  148.                 incr i
  149.                 set sfile [ lindex $argv $i ]
  150.             }
  151.             if { ! [ file readable $sfile ] } {
  152.                 send_user "\nError: Can't read $sfile\n"
  153.                 exit 1
  154.             }
  155.             set do_script 1
  156.         # save config on exit
  157.         } -S* {
  158.             set do_saveconfig 1
  159.         # Timeout
  160.         } -t* {
  161.             if {! [ regexp .\[tT\](.+) $arg ignore timeout]} {
  162.                 incr i
  163.                 set timeout [ lindex $argv $i ]
  164.             }
  165.         # Username
  166.         } -u* {
  167.             if {! [  regexp .\[uU\](.+) $arg ignore user]} {
  168.                 incr i
  169.                 set username [ lindex $argv $i ]
  170.             }
  171.         # command file
  172.         } -x* {
  173.             if {! [  regexp .\[xX\](.+) $arg ignore cmd_file]} {
  174.                 incr i
  175.                 set cmd_file [ lindex $argv $i ]
  176.             }
  177.             if [ catch {set cmd_fd [open $cmd_file r]} reason ] {
  178.                 send_user "\nError: $reason\n"
  179.                 exit 1
  180.             }
  181.             set cmd_text [read $cmd_fd]
  182.             close $cmd_fd
  183.             set command [join [split $cmd_text \n] \;]
  184.             set do_command 1
  185.         # 'ssh -c' cypher type
  186.         } -y* {
  187.             if {! [  regexp .\[yY\](.+) $arg ignore cypher]} {
  188.                 incr i
  189.                 set cypher [ lindex $argv $i ]
  190.             }
  191.         } -* {
  192.             send_user "\nError: Unknown argument! $arg\n"
  193.             send_user $usage
  194.             exit 1
  195.         } default {
  196.             break
  197.         }
  198.     }
  199. }
  200. # Process routers...no routers listed is an error.
  201. if { $i == $argc } {
  202.     send_user "\nError: $usage"
  203. }
  204.  
  205. # Only be quiet if we are running a script (it can log its output
  206. # on its own)
  207. if { $do_script } {
  208.     log_user 0
  209. } else {
  210.     log_user 1
  211. }
  212.  
  213. #
  214. # Done configuration/variable setting.  Now run with it...
  215. #
  216.  
  217. # Sets Xterm title if interactive...if its an xterm and the user cares
  218. proc label { host } {
  219.     global env
  220.     # if CLOGIN has an 'x' in it, don't set the xterm name/banner
  221.     if [info exists env(CLOGIN)] {
  222.         if {[string first "x" $env(CLOGIN)] != -1} { return }
  223.     }
  224.     # take host from ENV(TERM)
  225.     if [info exists env(TERM)] {
  226.         if [regexp \^(xterm|vs) $env(TERM) ignore ] {
  227.             send_user "\033]1;[lindex [split $host "."] 0]\a"
  228.             send_user "\033]2;$host\a"
  229.         }
  230.     }
  231. }
  232.  
  233. # This is a helper function to make the password file easier to
  234. # maintain.  Using this the password file has the form:
  235. # add password sl*      pete cow
  236. # add password at*      steve
  237. # add password *        hanky-pie
  238. proc add {var args} { global int_$var ; lappend int_$var $args}
  239. proc include {args} {
  240.     global env
  241.     regsub -all "(^{|}$)" $args {} args
  242.     if { [ regexp "^/" $args ignore ] == 0 } {
  243.         set args $env(HOME)/$args
  244.     }
  245.     source_password_file $args
  246. }
  247.  
  248. proc find {var router} {
  249.   upvar int_$var list
  250.   if { [info exists list] } {
  251.     foreach line $list {
  252.       if { [string match [lindex $line 0] $router ] } {
  253.         return [lrange $line 1 end]
  254.       }
  255.     }
  256.   }
  257.   return {}
  258. }
  259.  
  260. # Loads the password file.  Note that as this file is tcl, and that
  261. # it is sourced, the user better know what to put in there, as it
  262. # could install more than just password info...  I will assume however,
  263. # that a "bad guy" could just as easy put such code in the clogin
  264. # script, so I will leave .cloginrc as just an extention of that script
  265. proc source_password_file { password_file } {
  266.     global env
  267.     if { ! [file exists $password_file] } {
  268.         send_user "\nError: password file ($password_file) does not exist\n"
  269.         exit 1
  270.     }
  271.     file stat $password_file fileinfo
  272.     if { [expr ($fileinfo(mode) & 007)] != 0000 } {
  273.         send_user "\nError: $password_file must not be world readable/writable\n"
  274.         exit 1
  275.     }
  276.     if [ catch {source $password_file} reason ] {
  277.         send_user "\nError: $reason\n"
  278.         exit 1
  279.     }
  280. }
  281.  
  282. # Log into the router.
  283. # returns: 0 on success, 1 on failure
  284. proc login { router user passwd cmethod cyphertype identfile} {
  285.     global spawn_id in_proc do_command do_script passphrase prompt
  286.     global sshcmd
  287.     set in_proc 1
  288.  
  289.     # try each of the connection methods in $cmethod until one is successful
  290.     set progs [llength $cmethod]
  291.     foreach prog [lrange $cmethod 0 end] {
  292.         incr progs -1
  293.         if [string match "telnet*" $prog] {
  294.             regexp {telnet(:([^[:space:]]+))*} $prog command suffix port
  295.             if {"$port" == ""} {
  296.                 set retval [ catch {spawn telnet $router} reason ]
  297.             } else {
  298.                 set retval [ catch {spawn telnet $router $port} reason ]
  299.             }
  300.             if { $retval } {
  301.                 send_user "\nError: telnet failed: $reason\n"
  302.                 return 1
  303.             }
  304.         } elseif ![string compare $prog "ssh"] {
  305.             # ssh to the router & try to login with or without an identfile.
  306.             # We use two calls to spawn since spawn does not seem to parse
  307.             # spaces correctly.
  308.             if {$identfile != ""} {
  309.                 if [ catch {spawn $sshcmd -c $cyphertype -x -l $user -i $identfile $router} reason ] {
  310.                     send_user "\nError: failed to $sshcmd: $reason\n"
  311.                     return 1
  312.                 }
  313.             } else {
  314.                 if [ catch {spawn $sshcmd -c $cyphertype -x -l $user $router} reason ] {
  315.                     send_user "\nError: failed to $sshcmd: $reason\n"
  316.                     return 1
  317.                 }
  318.             }
  319.         } elseif ![string compare $prog "rsh"] {
  320.             send_error "\nError: unsupported method: rsh\n"
  321.             if { $progs == 0 } {
  322.                 return 1
  323.             }
  324.             continue
  325.         } else {
  326.             send_user "\nError: unknown connection method: $prog\n"
  327.             return 1
  328.         }
  329.         sleep 0.3
  330.  
  331.         # This helps cleanup each expect clause.
  332.         expect_after {
  333.             timeout {
  334.                 send_user "\nError: TIMEOUT reached\n"
  335.                 catch {close}; catch {wait};
  336.                 if { $in_proc} {
  337.                     return 1
  338.                 } else {
  339.                     continue
  340.                 }
  341.             } eof {
  342.                 send_user "\nError: EOF received\n"
  343.                 catch {close}; catch {wait};
  344.                 if { $in_proc} {
  345.                     return 1
  346.                 } else {
  347.                     continue
  348.                 }
  349.             }
  350.         }
  351.  
  352.         # Here we get a little tricky.  There are several possibilities:
  353.         # the router can ask for a username and passwd and then
  354.         # talk to the TACACS server to authenticate you, or if the
  355.         # TACACS server is not working, then it will use the enable
  356.         # passwd.  Or, the router might not have TACACS turned on,
  357.         # then it will just send the passwd.
  358.         expect {
  359.             -re "(Connection refused|Secure connection \[^\n\r]+ refused|Connection closed by)" {
  360.                 catch {close}; catch {wait};
  361.                 if !$progs {
  362.                    send_user "\nError: Connection Refused ($prog)\n"; return 1
  363.                 }
  364.             }
  365.             eof { send_user "\nError: Couldn't login\n"; wait; return 1
  366.             } -nocase "unknown host\r\n" {
  367.                 catch {close}; catch {wait};
  368.                 send_user "\nError: Unknown host\n"; wait; return 1
  369.             } "Host is unreachable" {
  370.                 catch {close}; catch {wait};
  371.                 send_user "\nError: Host Unreachable!\n"; wait; return 1
  372.             } "No address associated with name" {
  373.                 catch {close}; catch {wait};
  374.                 send_user "\nError: Unknown host\n"; wait; return 1
  375.             }
  376.             "Login incorrect" {
  377.                           send_user "\nError: Check your password for $router\n"
  378.                           catch {close}; catch {wait}; return 1
  379.                         }
  380.             -re "Enter passphrase.*: " {
  381.                 # sleep briefly to allow time for stty -echo
  382.                 sleep 1
  383.                 send -- "$passphrase\r"
  384.                 exp_continue }
  385.             -re "(Host key not found |The authenticity of host .* be established).*\(yes\/no\)\?" {
  386.                 send "yes\r"
  387.                 send_user "\nHost $router added to the list of known hosts.\n"
  388.                 exp_continue }
  389.             -re "HOST IDENTIFICATION HAS CHANGED.* \(yes\/no\)\?" {
  390.                 send "no\r"
  391.                 send_user "\nError: The host key for $router has changed.  Update the SSH known_hosts file accordingly.\n"
  392.                 return 1 }
  393.             -re "Offending key for .* \(yes\/no\)\?" {
  394.                 send "no\r"
  395.                 send_user "\nError: host key mismatch for $router.  Update the SSH known_hosts file accordingly.\n"
  396.                 return 1 }
  397.             -re "(Username|\[\r\n]login):"      {
  398.                                                   send -- "$user\r"
  399.                                                   exp_continue
  400.                                                 }
  401.             "\[Pp]assword:"                     {
  402.                                                   sleep 1; send -- "$passwd\r"
  403.                                                   exp_continue
  404.                                                 }
  405.             -re "$prompt"               { break; }
  406.             denied      { send_user "\nError: Check your password for $router\n"
  407.                           catch {close}; catch {wait}; return 1
  408.                         }
  409.         }
  410.     }
  411.  
  412.     # we are logged in, now figure out the full prompt
  413.     send "\r"
  414.     expect {
  415.         -re "(\r\n|\n)"         { exp_continue; }
  416.         -re "^\[^ ]+$prompt"    { set prompt $expect_out(0,string);
  417.                                   regsub ">" $prompt "\[#>]" prompt;
  418.                                 }
  419.     }
  420.  
  421.     set in_proc 0
  422.     return 0
  423. }
  424.  
  425. # Run commands given on the command line.
  426. proc run_commands { prompt command } {
  427.     global in_proc
  428.     set in_proc 1
  429.  
  430.     send "set cli complete-on-space off\r"
  431.     expect -re $prompt  {}
  432.     send "set cli screen-length 0\r"
  433.     expect -re $prompt  {}
  434.  
  435.     set commands [split $command \;]
  436.     set num_commands [llength $commands]
  437.     for {set i 0} {$i < $num_commands} { incr i} {
  438.         send "[lindex $commands $i]\r"
  439.         expect {
  440.             -re "^\[^\n\r *]*$prompt $" {}
  441.             -re "^\[^\n\r]*$prompt."    { exp_continue }
  442.             -re "(\r\n|\n)"                     { exp_continue }
  443.         }
  444.     }
  445.     send "quit\r"
  446.     expect {
  447.         "\n"                                    { exp_continue }
  448.         timeout                                 { catch {close}; catch {wait};
  449.                                                   return 0
  450.                                                 }
  451.         eof                                     { return 0 }
  452.     }
  453.     set in_proc 0
  454. }
  455.  
  456. #
  457. # For each router... (this is main loop)
  458. #
  459. source_password_file $password_file
  460. set in_proc 0
  461. set exitval 0
  462. foreach router [lrange $argv $i end] {
  463.     set router [string tolower $router]
  464.     send_user "$router\n"
  465.  
  466.     set prompt ">"
  467.  
  468.     # Figure out username
  469.     if {[info exists username]} {
  470.       # command line username
  471.       set loginname $username
  472.     } else {
  473.       set loginname [join [find user $router] ""]
  474.       if { "$loginname" == "" } { set loginname $default_user }
  475.     }
  476.  
  477.     # Figure out loginname's password (if different from the vty password)
  478.     if {[info exists userpasswd]} {
  479.       # command line passwd
  480.       set passwd $userpasswd
  481.     } else {
  482.       set passwd [join [lindex [find userpassword $router] 0] ""]
  483.       if { "$passwd" == "" } {
  484.         set passwd [join [lindex [find password $router] 0] ""]
  485.         if { "$passwd" == "" } {
  486.           send_user "\nError: no password for $router in $password_file.\n"
  487.           continue
  488.         }
  489.       }
  490.     }
  491.  
  492.     # Figure out identity file to use
  493.     set identfile [join [lindex [find identity $router] 0] ""]
  494.  
  495.     # Figure out passphrase to use
  496.     if {[info exists avpassphrase]} {
  497.         set passphrase $avpassphrase
  498.     } else {
  499.         set passphrase [join [lindex [find passphrase $router] 0] ""]
  500.     }
  501.     if { ! [string length "$passphrase"]} {
  502.         set passphrase $passwd
  503.     }
  504.  
  505.     # Figure out ssh cypher type
  506.     if {[info exists cypher]} {
  507.       # command line ssh cypher type
  508.       set cyphertype $cypher
  509.     } else {
  510.       set cyphertype [find cyphertype $router]
  511.       if { "$cyphertype" == "" } { set cyphertype "3des" }
  512.     }
  513.  
  514.     # Figure out connection method
  515.     set cmethod [find method $router]
  516.     if { "$cmethod" == "" } { set cmethod {{telnet} {ssh}} }
  517.  
  518.     # Figure out the SSH executable name
  519.     set sshcmd [find sshcmd $router]
  520.     if { "$sshcmd" == "" } { set sshcmd {ssh} }
  521.  
  522.     # Login to the router
  523.     if {[login $router $loginname $passwd $cmethod $cyphertype $identfile]} {
  524.         incr exitval
  525.         continue
  526.     }
  527.  
  528.     if { $do_command } {
  529.         if {[run_commands $prompt $command]} {
  530.             incr exitval
  531.             continue
  532.         }
  533.     } elseif { $do_script } {
  534.         send "set cli complete-on-space off\r"
  535.         expect -re $prompt      {}
  536.         send "set cli screen-length 0\r"
  537.         expect -re $prompt      {}
  538.         source $sfile
  539.         catch {close};
  540.     } else {
  541.         label $router
  542.         log_user 1
  543.         interact
  544.     }
  545.  
  546.     # End of for each router
  547.     catch {wait};
  548.     sleep 0.3
  549. }
  550. exit $exitval
RAW Paste Data
Top