Question

I have an expect/Tcl script as part of my bash script that logs into a remote router. Now, for testing purposes I am trying to handle the issue of time-out's. My problem is that the expect/Tcl script is not logging to my log file, and when it does it is logging everything the SSH connection is printing to my prompt which is not what I want.

Here's my expect script:

/usr/bin/expect<<EOF
    set timeout 5
    set send_human {.1 .3 1 .05 2}
    set myStamp [exec date +\[%d\/%m\/%Y\ \%T\]]

    set log_file ~/mylogfile.log

    spawn ssh -o "StrictHostKeyChecking no" "me\@$1"

    expect {
        "password: " { send -h "mypassword\r" }
        "No route to host" { exit 1 }
        timeout { send_log "\$myStamp Timed out to $1\n"]; exit 1 }
    }

    send -h "reboot in 1\r"
    sleep 1
    send -h "exit\r"
    expect eof
EOF

Please bear in mind that this is part of a function within my bash script that is passed the router name, hence the argument $1.

Any ideas?

Était-ce utile?

La solution

You want to use the log_file command, not set a log_file variable

log_file ~/mylogfile.log

Other notes:

  • Tcl has a very nice builtin command to handle time, don't need to call out to date:

    set myStamp [clock format [clock seconds] -format {[%d/%m/%Y %T]}]
    
  • the @ character is not special in Tcl/expect and does not need to be escaped:

    spawn ssh -o "StrictHostKeyChecking no" "me@$1"
    

As noted, log_file logs a transcript of the session. Just to log specific messages, you can use plain Tcl:

/usr/bin/expect <<EOF

    proc log_msg {msg {to_stdout no}} {
        set log_line "[timestamp -format {[%Y-%m-%d %T]}] \$msg"
        set fh [open ~/mylogfile.log a]
        puts \$fh \$log_line
        close \$fh
        if {\$to_stdout} {puts \$log_line}
    }

    # ...
    expect {
        "No route to host" {
            log_msg "No route to host" yes
            exit 1 
        }
        timeout { log_msg "Timed out to $1"]; exit 1 }
    }

    # ...
EOF

This opens and closes the log for each message, which adds a bit of overhead. If milliseconds are important, open the log in the global scope, and use the global variable holding the file hendle in the log_msg proc.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top