Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

How can I return an error in bash expect?

I have a bash expect script like this (I am using it in Jamf):

spawn firmwarepasswd -setpasswd 
expect { 
    "Enter password:" { 
        send "$oldpass
" 
        exp_continue 
    }
    "Enter new password:" { 
        send "$newpass
" 
        exp_continue
    } 
    "Re-enter new password:" { 
    send "$newpass
"
    exp_continue
    }
}

If the password fails, the script will not exit and jamf will keep trying to execute it. How can I get it to return 1 and exit if the password is wrong?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I don't know Jamf, but I do have a little example for you:

function _cmd {
        local cmd="${@?No command?}"
        echo -ne "Testing $cmd: "
        expect 2>&1 <<-EOF
                set timeout -1
                spawn ${cmd}
                expect eof
                catch wait result
                exit [lindex $result 3]
EOF     
        echo $?
}

function _ssh {
        local status="${@?No command?}"
        read -sp "remote password? " remote_pass
        echo -ne "
Testing ssh: "
        expect 2>&1 <<-EOF
                set timeout -1
                spawn ssh [email protected]
                expect {
                        "yes/no" { send "yes
"; exp_continue }
                        "*password: " { send "${remote_pass}
" }
                }
                expect "*#" { send "exit $status
" }
                expect eof
                catch wait result
                exit [lindex $result 3]
EOF
echo $?
}

_cmd false
_cmd true
_ssh 3

exit 0

The last part after expect eof makes sure that the exit status is shared. The _ssh command will exit with status 3.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...