4

When I'm supplying username and password to telnet to login, it is automatically closed after the following command:

echo password | telnet mymachine -l mysuername

The console outputs:

Connected to mymachine.
Connection closed by foreign host.

Then the connection is closed. Is there a way to maintain the connection while still supplying username and password to the login at one time?

Update: I wrote an alias according to the accepted answer that does the login without typing username and password everytime:

alias logon='rm loginscript; echo \#\!\/usr\/bin\/expect >> loginscript ; echo spawn telnet remotemachine -l username >> loginscript ; echo expect Password: >> loginscript ; echo send password"\\r" >> loginscript ; echo expect -- \{\$ \} >> loginscript ; echo interact >> loginscript; chmod 777 loginscript; ./loginscript'
4
  • 1
    You cannot do that, Have a look at expect – Rui F Ribeiro Oct 8 '16 at 8:23
  • expect is best approach, as suggested. A hack using ( sleep 1 ; echo username ; sleep 2 ; echo password ; sleep 2 ; echo ls ) | telnet mymachine is possible but ugly/unreliable. – steve Oct 8 '16 at 8:29
  • Have a look at sshpass. – v7d8dpo4 Oct 8 '16 at 10:03
  • The login command, which is responsible for querying your password, explicitly clears all input characters before prompting for the password, to avoid attacks through the console's clipboard buffer or the xterm window title. – Simon Richter Oct 8 '16 at 15:21
6

If you want to continue with an interactive session, the usual way is to use expect to do the login:

#!/usr/bin/expect
spawn telnet mymachine -l myusername
expect Password:
send password\r
expect -- {$ }
interact
4

Assuming you still want to interact with that telnet session after sending the password, you'd need to feed it input from your local terminal:

(echo password; cat) | telnet -l user host

Depending on how your telnet implementation tries to interact with the local terminal, you may find that you need to do:

saved=$(stty -g); stty raw -echo
(echo password; cat) | telnet -l user host
stty "$saved"

Or even:

saved=$(stty -g); stty raw -echo
(echo password; cat) | telnet -l user host 2>&1 | cat
stty "$saved"

(on some systems, you may need cat -u in place of cat)

Another option is to use expect which uses a pseudo-terminal instead of pipes to interact with the application (note that telnetd also spawns a pty at the other end, so an extra one is not strictly necessary in this case).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.