ssh in shell script

Hi all,

I am trying to write a script in shell which can connect me to a remote server and run some commands my problem is i cant pass the password barrier.I read a lot of articles where bloggers have suggested not to use telnet and to use something more secure like ssh.I tried ssh but as soon as the password is passed the scripts fails...

#!/usr/bin/sh
Server=172.XX.XXX.XX
port=23
login=test
passwd=test
cmd1="cd /export/home/user"

echo ssh ${login}@${Server}
sleep 2
echo ${passwd}
sleep 3
echo ${cmd1}
sleep 2
echo exit

-------------------------------------------
result
---------

ssh test@172.XX.XXX.XX
test
cd /export/home/user
exit

please help

You have to change your script to input into the ssh command. Doing an ssh and then doing an echo won't work for it closes the tty from the ssh command before it executes the echo command. You need to instead provide input into the command using the << syntax. Such as

ssh test@172.xxx.xxx.xxx << EOF
${password}
${cmd}
EOF
[root@sur-core-L001 scripts]# sh msc1.sh 
Pseudo-terminal will not be allocated because stdin is not a terminal.
Password: 

doesnt work ...

Exchanging ssh keys is not an option?

something which i delibrately want to avoid. i would still prefer a way to pass the password to script and mate it work.

Why, exactly, do you want to avoid exchanging keys? It's a lot less maintenance compared to making sure that all scripts use the correct password, and it's much more secure, as there's no password stored in plain-text for everyone to read.

one reason is one of the servers from which i am trying to get the data is revenue critical for my organization and i am not very confident of doing the change in ssh key.

Setting up keys for passwordless authentication isn't rocket science. On the machine you want to connect from run

ssh-keygen -t dsa < /dev/null

That will create a private and a public key called ~/.ssh/id_dsa and id_dsa.pub. Now, copy the contents of id_dsa.pub into the file ~/.ssh/authorized_keys2 on the machine you want to connect to, eg

cat ~/.ssh/id_dsa.pub | ssh user@remote 'mkdir -p .ssh; cat >> .ssh/authorized_keys2'

If you connect afterward, you shouldn't be promped for a password. If you try to connect from a machine that hasn't got the private key, you'll still be asked for a password.

IMHO, it's more secure than passwords in scripts. They're impossible to guess, easy to revoke (just remove the entry from the authorized_keys2 file), and you can even tie access to a specific user on a specific machine (just allow only that one unique key). if you're uncomfortable with the procedure, experiment on some non-critical machines first (eg. some development machines or VMs)

maybe something like this?

#!/usr/bin/expect
set timeout 20
spawn  ssh [server-ip]
expect "[something from the login prompt]"
send "[username]\r"
expect "[something from the passwd prompt]"
send "[passwd]\r"