有条件的国家

时间:2016-02-15 20:33:33

标签: bash tcl expect

我正在尝试通过SSH连接登录多个设备。我想抓住我拥有的用户是否能够登录。如果是,则继续执行某些命令,如果不退出脚本。无论我是否拥有权限,我都需要在日志中写入。

这是我的代码:

#!/usr/bin/expect -f

set timeout 10


set host [lindex $argv 0]
set user "username"
set pwd "blahblahblah"
set devicename [lindex $argv 1]

set DATE [exec date +%Y-%m-%d_%H:%M] 

set log_devicename [open log_$devicename.txt "a+"]


spawn ssh -p 20444 $user@$host
log_user 0

expect {
        "*assword: " {
                send "$pwd\r";
                expect "Permission denied, please try again." {puts $log_devicename "User $user does not have access to $host-$devicename at $DATE";exit 22} 
                expect ">" {send "display startup\r"} 
                expect ">" {send "quit\r";puts $log_devicename "User $user have successful access to $host-$devicename at $DATE"}
                expect "timeout" {puts $log_devicename "$host - $devicename it's not reachable at $DATE cannot execute StartUp Script";exit 111}
                exp_continue
                    }

                eof 
        }

我遇到的问题是,当我访问第一行检查是否有错误时会出现错误但完成预期它是正确的,我可以在日志中写出'一切都好,但是这个错误。

expect: continuing expect after update expect: spawn id exp7 not open
    while executing
"expect {
        "*assword: " {
                send "$pwd\r";
                expect "Permission denied, please try again." {puts $log_devicename "Us..."
    (file "test.exp" line 19)

我有没有工作的LOG就是这个。

  

root @ servidor:/ var / www / RED_CENTRAL / Performance / IP_Engine #more   LOG / LOG_DEVICES / log_HIPODR-MEX9039-X8-CA.txt用户registrotpe有   成功访问10.XXX.XX.XX-HIPODR-MEX9039-X8-CA at   2016-02-15_14:24

     

root @ servidor:/ var / www / RED_CENTRAL / Performance / IP_Engine #more   LOG / LOG_DEVICES / log_BENJUA-MEX9297-X8-CA.txt用户registrotpe   无法访问10.XXX.XX.XX-BENJUA-MEX9297-X8-CA   2016-02-15_14:39

我已经尝试在调试模式下执行,但我无法找到解决方案。

你能帮我吗?

1 个答案:

答案 0 :(得分:1)

您的问题在错误消息中是正确的:" spawn id exp7未打开"。您需要在脚本中处理连接问题。这是我用于telnet连接的一个,同样的timeouteof关键字也适用于SSH:

spawn /usr/bin/telnet $hostname

# Allow this script to handle connection issues
expect {
    timeout {
        send_user "\nTimeout - Check $hostname\n\n";
        exit 1
    }
    eof {
        send_user "\nConnection failed - Check $hostname\n\n";
        exit 1
    }
    "*#" {
    }
    "*sername:" {
        send "$username\n"
        expect "*assword:"
        send "$password\n"
    }
}