#!/usr/bin/expect
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
# bos720 src/bos/usr/bin/cdat/telnet.exp 1.4 
#  
# Licensed Materials - Property of IBM 
#  
# COPYRIGHT International Business Machines Corp. 2010,2011 
# All Rights Reserved 
#  
# US Government Users Restricted Rights - Use, duplication or 
# disclosure restricted by GSA ADP Schedule Contract with IBM Corp. 
#  
# IBM_PROLOG_END_TAG 
# @(#)28    1.4  src/bos/usr/bin/cdat/telnet.exp, cdat, bos720 7/14/11 17:56:29
set user [lindex $argv 0]
set host [lindex $argv 1]
set cmd [lindex $argv 2]

set pattern1 "*ogin: "
catch { set pattern1 $env(EXPECT_PATTERN1) }
set pattern2 "*assword:"
catch { set pattern2 $env(EXPECT_PATTERN2) }
set passwd ""
catch { set passwd $env(EXPECT_PASSWORD) }
set prompt "(%|#|\\$) $"

log_user 0

# start telnet to specified host

spawn -noecho /usr/bin/telnet $host

# wait for login prompt
expect "$pattern1" {
    send "$user\r"
}

# wait for password prompt (unless password is empty)
if { [ string compare "$passwd" "" ] != 0 } {
    expect "$pattern2" {
	send -- "$passwd\r"
    }
}

send "\r";	# force a new line
# wait for command line prompt
expect -re $prompt {
    # enter specified command in a sub-shell
    send "/bin/sh\r"
    expect -re $prompt
    log_user 1
    send "( $cmd )\r"
}

# wait for prompt after command (command may take a lot of time)
set timeout -1
expect -re $prompt {
    log_user 0
    send_user "\n"
    # retrieve exit status of command
    send "echo \$\?\r"
}

# wait for echo command
set timeout 5
expect -re "(\[0-9\]+)" {
    send "exit\r"
    # exit from expect using same exit status as remote command
    exit $expect_out(1,string)
}