0

I'm using a bash script to log into a telnet server and execute a number of commands. It looks like:

login_and_run.sh

#!/bin/bash

unset TELNET_USER_NAME_STRING
unset TELNET_PASSWORD_STRING
unset TELNET_USER_NAME
unset TELNET_PASSWORD

TELNET_USER_NAME_STRING=`cat SAP_output`
TELNET_PASSWORD_STRING="Password:"

TELNET_USER_NAME="UserNam3\r"
TELNET_PASSWORD="Passw0rd\r"

# Expect script starts here
expect <<- DONE
        spawn telnet localhost 50008
        expect '$TELNET_USER_NAME_STRING'
        send "$TELNET_USER_NAME"
        sleep 3
        expect "$TELNET_PASSWORD_STRING"
        send "$TELNET_PASSWORD"
        sleep 3
        spawn ls
        expect eof
DONE

where

SAP_output:

Trying ::1...
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.

   ***********************************************
   **********************************************
   ****###*******####*****#######**************
   **##***##****##**##****##****##************
   ***##*******##****##***##****##**********
   *****##*****########***######***********
   ******##****##****##***##*************
   **##***##**##******##**##************
   ****###****##******##**##**********
   **********************************
   ********************************

   Telnet Administration
   SAP Java EE Application Server v7.50


User name:

telnet logs in, I get the banner, but it stops there (as if the strings are not matching). Would it be safer to use wildcards instead of the exact response (and match only " User name: ")?

  • 1
    Note that single quotes have no special meaning in expect/tcl. You are expecting to see literal single quotes. – glenn jackman Aug 16 at 13:47
  • 1
    Also, expect uses \r\n for newlines, and that file, I'm guessing, does not contain carriage returns. – glenn jackman Aug 16 at 13:49
  • 1
    When composing an expect program, turn on verbose debugging with exp_internal 1 -- that will show you when your patterns are not matching. – glenn jackman Aug 16 at 13:49
0

Figured it out:

TELNET_USER_NAME_STRING='*name:*'

TELNET_PASSWORD_STRING='*assword:*'

TELNET_USER_NAME='UserNam3\r'
TELNET_PASSWORD='Passw0rd\r'

# Expect script starts here
expect <<- DONE
        spawn telnet localhost 50008
        expect '$TELNET_USER_NAME_STRING'
        send "$TELNET_USER_NAME"
        expect '$TELNET_PASSWORD_STRING'
        send "$TELNET_PASSWORD"
        # Check if we're logged in
        expect eof
DONE

Use wildcards instead of the full banner and return line character '\r' to 'press' enter.

Edit:

This is a far more elegant answer.

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.