我如何使用SSH在全局configuration模式下运行Cisco IOS命令?

我知道Kron,但是没有办法运行全局configuration命令:

Schedule commands with Cisco IOS’ kron

如果我使用Putty连接,Putty可以在login后运行几个命令,并且像魅力一样工作。 事情是我想每晚晚上11点自动进入交换机并closures一系列接口。

我正在尝试使用sshpass,但似乎一次只允许1个命令。

还有一个无密码的方式进入思科交换机,但从IOS 15.0上:

https://www.m00nie.com/2010/12/password-less-ssh-login-using-pki-to-cisco-ios/

这发生在几年前,我有同样的工作要做。 这是我当时所做的,我希望能够帮助:

#!/usr/bin/expect -f set ipadr [lindex $argv 0] set cmd [lindex $argv 1] set fich [lindex $argv 2] if { ${cmd} == 1 } then {set comm "sh flash | tee tftp://TFTP-IP-ADDRESS/essai\r"} else {set comm "copy flash:${fich} tftp://TFTP-IP-ADDRESS\r"} spawn ssh niji@${ipadr} expect { "password:" { send "YOURPASSWORDHERE\r" } "(yes/no)?" { send "yes\r"; expect { "password:" { send "YOURPASSWORDHERE\r"; }}} "Name:" { send "YOURUSERNAMEHERE\r"; sleep 3 ; send "YOURPASSWORDHERE\r"; } "Connection refused" { exit } } expect { ">" { send "en\r" ; sleep 3; send "EN-PASSWD\r";} "#" { send "\r" } } expect { "#" { send "${comm}" ; sleep 5; send "\r" ;send "\r" } } expect { "#" { send "exit\r"; send "quit\r" } } 

这将IOS设备连接到作为参数提供的IP地址。 密码和用户名是硬编码的,所以我想你会想改善。

发送给路由器的命令是“copy run tftp”或类似的东西,但是你可以把它改成任何你需要的东西。

就在不久前,如果我现在不得不重新使用它,我想我会做一些重新工作,但这可能是一个很好的基础。

干杯,

好的,我发现这个:

/ usr / local / bin / sshpass -p密码ssh [email protected] <ios-cmds.txt

其中ios-cmds.txt包含所有在单独的行中的命令,就像我按顺序input它们一样。

另外,我的一个同事build议使用linux命令:

 expect 

编辑:有一点要小心的是,如果SSH会话从未发生过,与交换机的证书交换部分将使命令失败默默无闻。 首先连接交换机手动接受证书,然后SSHPASS将很高兴地login并执行命令。

编辑2:在YBounya的评论后,我结束了这个脚本,基本上循环通过连续的IP,并closures了一系列的接口,脚本收到“开”或“关”作为一个参数进行开机或关机操作:

 #!/usr/bin/expect -f if { [lindex $argv 0] eq "on"} { set action "no shut\r" puts "Turning on switchports\n" } elseif { [lindex $argv 0] eq "off" } { set action "shut\r" puts "Turning off switchports\n" } else { puts "No power action found. Provide \"on\" or \"off\"." exit } proc shutPort {ip action} { spawn ssh [email protected].$ip expect { "(yes/no)" { send "yes\r"; expect { "assword:" { send -- "REAL_PASSWORD\r"; }}} "assword: " { send -- "REAL_PASSWORD\r" } "No route to host" { return } ;# switch uses Telnet or just not listen on port 22 "Connection refused" { return } ;# switch is not reachable "modulus too small" { return } ;# RSA key is not acceptable } expect ">" send -- "en\r" expect "assword: " send -- "REAL_PASSWORD\r" expect -re "\r\n#" send -- "conf t\r" expect "(config)#" send -- "int ran gig1/0/7-48\r" expect { "config-if-range" { send -- $action } ; # if previous sends succeeds, enter interface range mode "marker" { send "int ran gig0/7-48\r"; # interface syntax didn't work expect { "config-if-range" { send -- $action } "marker" { send "int ran fas0/7-48\r"; expect { "config-if-range" { send -- $action } "marker" { send "int ran fas0/7-24\r"; expect { "config-if-range" { send -- $action } } } } } } } } send -- "exi\r" send -- "exi\r" send -- "exi\r" expect eof } for {set i 42} {$i < 51} {incr i} { shutPort $i $action }