Jayaprakash Nagarajan Jayaprakash Nagarajan - 4 years ago 126
Bash Question

how to add timout while scp the file to remote server and if no privilege to sudo via expect script

I want to add timeouts if there is no privilege on /tmp folder while scp the file and if there is no sudo privilege while executing the sudo command in below script.Could you please suggest

spawn scp -o StrictHostKeyChecking=no \
/tmp/rem_script.sh $env(user_name)@$env(first_db_node_ip):/tmp
expect "password:"
send -- "$env(rem_password)\r"
expect eof

spawn ssh -o StrictHostKeyChecking=no $env(user_name)@$env(first_db_node_ip)
expect "password:"
send -- "$env(rem_password)\r"

expect -ex $
send "PS1=UGLY-PROMPT'# '\r"
expect "UGLY-PROMPT# "

send "sudo chmod 777 /tmp/rem_script.sh\r"
expect {
"password:" {
send -- "$env(rem_password)\r"
exp_continue
}
"UGLY-PROMPT# " {}
}

send "sudo sh /tmp/rem_script.sh $env(asrm_name) $env(com_str)\r"
expect {
"password:" {
send -- "$env(rem_password)\r"
exp_continue
}
-timeout 60 "UGLY-PROMPT# " {}
}

send "exit\r"
expect eof

Answer Source

You need a "timeout" pattern if you want to do something on the timeout rather than just stop waiting for the listed patterns. Something like the following:

send "sudo sh /tmp/rem_script.sh $env(asrm_name) $env(com_str)\r"
expect -timeout 60 {
    "password:" {
        send -- "$env(rem_password)\r"
        exp_continue
    }
    timeout { send_user "timed out!" } 
    "UGLY-PROMPT# " {}
}

Or whatever you want to do when waiting for the other patterns times out.

You may also want to add patterns specifically looking for the error messages if you don't have the sudo or other priviledges that you expect to have.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download