Use expect in bash script to provide password to S

2018-12-31 16:26发布

To those who want to reply that I should use SSH keys please abstain

I'm trying to use expect in an bash script to provide the SSH password. Providing the password works but I don't end up in the SSH session as I should, it goes back strait to bash.

My script:

#!/bin/bash

read -s PWD

/usr/bin/expect <<EOD
spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no usr@$myhost.example.com'
expect "password"
send "$PWD\n" 
EOD
echo "you're out"

The output of my script:

spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no usr@$myhost.example.com
usr@$myhost.example.com's password: you're out

I would like to have my SSH session and only when I exit it to go back to my bash script. The reason why I am using bash before expect is because I have use a menu I can choose which unit to connect to.

Thanks

8条回答
琉璃瓶的回忆
2楼-- · 2018-12-31 17:21

After looking for an answer for the question for months, I finally find a really best solution: writing a simple script.

#!/usr/bin/expect

set timeout 20

set cmd [lrange $argv 1 end]
set password [lindex $argv 0]

eval spawn $cmd
expect "assword:"
send "$password\r";
interact

Put it to /usr/bin/exp, then you can use:

  • exp <password> ssh <anything>
  • exp <password> scp <anysrc> <anydst>

Done!

查看更多
唯独是你
3楼-- · 2018-12-31 17:21

Use the helper tool fd0ssh (from hxtools, not pmt), it works without having to expect a particular prompt from the ssh program.

查看更多
登录 后发表回答