Question

How can I use expect to send a password to an ssh connection.

say the password was p@ssword and the ssh command was ssh me@127.0.0.1

What would I do with expect to a make it input the password when it says

me@127.0.0.1's password:
?

The proper action of using an SSH key pair isn't an option because I would have to use ssh (scp) to put the key on the server, which would ask for a password.

Was it helpful?

Solution

I always used the "proper" solution, but I used expect in other situations.

Here I found following suggestion:

#!/usr/local/bin/expect
spawn  sftp  -b cmdFile user@yourserver.com
expect "password:"
send "shhh!\n";
interact

OTHER TIPS

Would it not be easier to use public key authentication and use a key with no passphrase?

As the user on the source machine do this to make an RSA key

ssh-keygen -t rsa

Now copy ~/.ssh/id_rsa.pub to the target machine and append it to the authorized_keys file of the target user

Your quickest way forward (unless you want to become a Tcl expert, which would be... unusual... in 2009) is probably to use autoexpect. Here's the man page:

http://expect.nist.gov/example/autoexpect.man.html

In short, fire up autoexpect, run your ssh session, finish up what you need to do, stop autoexpecting and then beat your keyboard over the resulting mess until it works :) I'm assuming you don't need anything more than a quick hack to get your keys sorted out and then, well it sounds like you know the score already with that.

And there's this question which already contains an example close to what you seek.

Cygwin has autoexpect just not in the bin package. run setup.exe and search for expect and check the source checkbox. you will see the resulting tree in /usr/src and in there there is a expect/expect/examples directory. in there lives a copy of the autoexpect script.

Key solution will not work... because the keys have to be readable only by the person running ssh. On xp you cannot create key structure with the correct permissions. So ssh will not read them. This may have changed, but last i checked it still not not work.

I'm pretty sure it is not possible to do what you're trying to do. Most *nix applications that prompt for a password read from the TTY directly, not stdin, so you can't pipe the password in. You can, as others have mentioned, configure SSH to not prompt for a password, as explained here.

After I was downvoted for no apparent reason, I went and did a little more research on the expect command and discovered that it has a send_tty command that sends to /dev/tty instead of stdin, which might actually do what you want... I was previously unaware of this feature. I still recommend putting the key on the server, however.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top