how to use telnet in script

I am trying to use telnet in shell script but getting following error

error
Connected to crmapp00.agf.ca.
Escape character is '^]'.
Connection closed by foreign host.

Script
#!/bin/ksh
PATH=/usr/sbin/:/usr/bin:/usr/ucb:/etc:/usr/local/bin:.
telnet HOSTNAME <<SCRIPT
user userid password
SCRIPT
exit

i think i am doing something wrong in this area
user userid password

Actually i have tried different way too but didn't work it prompt me for userid and password.
#!/bin/ksh
PATH=/usr/sbin/:/usr/bin:/usr/ucb:/etc:/usr/local/bin:.
telnet HOSTNAME
user userid password
exit

I'll really appreciate if someone can help me...

Thanks in Advance.

You cannot use a here document with telnet.

If this task really must be done with telnet it could best be done with expect, otherwise use a login method which does not need interactive logins such as rsh/rexec or preferably ssh.

I second the above!
Here's the "poor-man's" inline telnet which might not be bullet-proof for all the cases:

    (
    sleep 3
    print user
    sleep 1
    print password
    sleep 2
    print "ls ~"
    sleep 1
    print "exit"
    sleep 3
    ) | telnet hostname

Thank you so much it worked

this one is working, but it exits the telnet session at the end. i want the script to make a permanant connection to the server so that whenever i want to connect, i can just run the script instead of entering all the credinals.

if you have Perl, you can use the Net::Telnet module. eg here

no, i dont ve pearl. i just want a script that can connect to server using telnet and therafter it should end, but not the connection

i ve similar one

#!/bin/csh
setenv PASSWD `cat ~/.passwd`
foreach server_name (`cat hostlist`)
echo "connecting to server $server_name"
(sleep 5;echo $USERID;\
sleep 5;echo $PASSWD;\
sleep 2;echo passwd;\
sleep 2;echo $OLDPASSWD;\
sleep 2;echo $NEWPASSWD;\
sleep 2;echo $NEWPASSWD;\
sleep 2;exit;) | telnet $server_name | tee -a $server_name.log
end

it is useful in automating of changing password to a number of servers or running the same script on a number of servers. it exits each server after changing the pswd

Hi Mady,

I want to thank you for your script post. I was able to use it successfully.
I too did not want to add expect or perl to do the automation task I needed.
This should do just fine for me.

Thanks again.
Well done!

fandi

You cannot reliably automate telnet logins without customizing the telnet source code. The standard workaround is to use expect but this can fail at times. Do a Web search on "automate telnet login" for further information on various workarounds if you want more information.

The best way to overcome this 'limitation' of telnet is to switch to ssh (and scp) which is (1) more secure and (2) can handle automatic logins.