As far as I can tell, spawn's first argument needs to be a string, not a list of string.
And trying to pass a multi-word command line as a single string is going to cause problems. I think you'd have to split on spaces before calling spawn, and that's going to break if one argument contains a space. Maybe it's better to specify the password as the first argument, and the command as the rest of the arguments.
So try something like:
#!/usr/bin/expect
spawn [lindex $argv 1] [lrange $argv 2 end]
expect "password:"
send [lindex $argv 0]
interact
But then even that doesn't work.
According to Re: expect - spawn fails with argument list on comp.lang.tcl (Google Groups version), we have to call eval
to split the list.
So the answer should be:
#!/usr/bin/expect
eval spawn [lrange $argv 1 end]
expect "password:"
send [lindex $argv 0]
interact
Finally, you need to be sending Enter after the password, so you want:
#!/usr/bin/expect
eval spawn [lrange $argv 1 end]
expect "password:"
send [lindex $argv 0]
send '\r'
interact
And then switch the order and don't quote the command when calling it:
./expect.sh "$SERVER1_PASS" ssh root@$SERVER1
But others have already done this. We don't need to re-invent the wheel.
See e.g. expect ssh login script
Your script has no major issues with it, not that would cause spawn
to fail like that. (The comments you have would cause problems, but are trivially fixable by using ;#
instead of #
.) Therefore your problem lies elsewhere (well, with very high probability).
I see that you are trying to control telnet with Expect on Windows. Alas, telnet is a special case that can't be controlled this way — Expect on Windows uses the system debugging facilities to intercept terminal output, but this doesn't work for executables that have special system permissions set, and telnet is one of the programs for which this is true — so you need another approach. The simplest is to get plink.exe
(which is really PuTTY for terminals/automation) and to use that (in “telnet” mode) instead of telnet.
Best Answer
Figured out why. I had generated ssh keys and copied it on to the destination machine. So there was no "Password: " prompt. Hence before send could complete, the ssh connection had closed.
I deleted the ssh keys from the destination machine and ran the script again and observed no issues