Expect script - sometimes no log generated
I have a simple expect script that supplies password 4 times. I am logging the output to a log file using
log_file -a /home/applusr/e291505/logs/ADD.log spawn /home/root/admin/add.mims.user $username "$firstname $lastname"
#!/usr/local/bin/expect
set username [lindex $argv 0]
set firstname [lindex $argv 1]
set lastname [lindex $argv 2]
set mypassword [lindex $argv 3]
set userpassword [lindex $argv 4]
set LOG_FILE [open /home/applusr/e291505/logs/ADD.log a]
set today [ exec /bin/date +%Y-%m-%d-%T]
puts $LOG_FILE "\n------------------ADD_SCRIPT - $today----$username--$firstname--$lastname---"
set timeout 10
log_user 1
log_file -a /home/applusr/e291505/logs/ADD.log
spawn /home/root/admin/add.mims.user $username "$firstname $lastname"
expect "e291505's Password:*" { send "$mypassword\n" }
expect "$username's New password:*" { send "$userpassword\n" }
expect "Enter the new password again:*" { send "$userpassword\n" }
expect "Password:*" { send "$mypassword\n" }If I run the script:
Sometimes the output is in the log file. No issues. Sometimes, there is no put in the log file except the puts statement output.
puts $LOG_FILE "\n------------------ADD_SCRIPT - $today----$username--$firstname--$lastname---"
How do I guarantee that log file will always have output?
31 Answer
(edited for completeness to include comment by glenn jackman, and later ones by me).
You need to
close $LOG_FILEbefore usinglog_fileor you have 2 independent file descriptors to the same file, and it seems to be indeterminate in which order the writes will be done.To get all output logged:
expectwill only copy input it has read to the log. Your last line getsexpectto read and look for the password prompt. Then your program stops. You need to add something more to get it to read any further output, so that it can be logged too. Typically, you wait for the spawned command to finish and close the file descriptor by addingexpect eofThe log shows only what is received, so normally sent passwords are not seen as echo will be turned off at that point. If you do see the 4th password then you may need to add a small delay after matching the prompt to let the remote switch echo off. eg:
{ sleep 1; send "$mypassword\n" }