Execute sudo using expect inside ssh from bash

2020-04-18 06:05发布

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 ""

3条回答
相关推荐>>
2楼-- · 2020-04-18 06:37

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
查看更多
趁早两清
3楼-- · 2020-04-18 06:38

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
查看更多
在下西门庆
4楼-- · 2020-04-18 06:40

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"
查看更多
登录 后发表回答