I need to ssh + sudo and came up with this solution to know if the executed command failed.
But I did not manage to return the real retCode of the executed command, any idea ?
# ----------------------------------------------------
# connect to user@server & execute a command as root with sudo
# usage: f_ssh_sudo "server" "username" "password" "my_script.sh arg1 arg2"
function f_ssh_sudo() {
local server=$1
local username=$2
local pw=$3
local cmd=$4
expect -f - <<-EOF
set timeout 10
spawn ssh -o StrictHostKeyChecking=no ${username}@${server}
expect "*?assword:" { send -- "${pw}n" }
expect "*$*"
send -- "sudo ${cmd} && echo CMD_OK || echo CMD_FAILn"
expect "*${username}*" { send -- "${pw}r" }
expect {
"*CMD_OK*" { send -- "exitn" ; exit 0 }
"*CMD_FAIL*" { send -- "exitn" ; exit 1 }
}
EOF
return $?
}
f_ssh_sudo 192.168.1.50 gandalf "Password1234" "ls -Alph /root"
echo "retCode=$?"
3