问题
I want to create a script that automates a installation on multiple linux hosts. I login to the hosts using ssh keys and inside the login I want to do a sudo, I am trying to use expect, which I have on the stations but I don't have on the server which runs the script. How do I do this, this is my try, but no luck with it:
#!/bin/bash
ssh user@station04 <<EOF
expect -d -c "
send \"sudo ls\"
expect {
\"password:\" { send '1234'; exp_continue }
\"$user@\"{
send "exit\r"
}
default {exit 1}
}"
EOF
exit
The result:
send: sending "sudo ls" to { exp0 }
expect: does "" (spawn_id exp0) match glob pattern "password:"? no
expect: read eof
expect: set expect_out(spawn_id) "exp0"
expect: set expect_out(buffer) ""
argv[0] = expect argv[1] = -d argv[2] = -c argv[3] =
send "sudo ls\r"
expect {
"password:" { send '1234'; exp_continue }
"@"{
send exitr
}
default {exit 1}
}
set argc 0
set argv0 "expect"
set argv ""
回答1:
A.K
What about this? <- just make sure of the expected prompts.
#!/bin/bash
expect <<'END'
spawn ssh user@station04
expect "password:"
send "$pw\r"
expect "#"
send "sudo ls\r"
END
回答2:
I suggest you would use public key authentication for the ssh part, then just use something like:
ssh -t username@server-ip -C "echo sudo-password | /usr/bin/sudo -S ls"
回答3:
You got the usage of expect
not quite right - don't send
a command; rather spawn
the command and send
just its input. So, your script becomes:
ssh … <<EOF
expect -d -c "
spawn sudo ls
expect -nocase password: { send 1234\r }
expect eof
"
exit
EOF
来源:https://stackoverflow.com/questions/27324374/execute-sudo-using-expect-inside-ssh-from-bash