Expect script in ssh to return an invalid command name

I am trying to write a wait script that will be ssh on the server, send sudo su, then check the status of iptables and put the output in a log file on the server. Below is the script.

1 #!/usr/bin/expect
  2 exp_internal 1
  3 log_user 0
  4 set timeout 10
  5 set password  "******"
  6 
  7 spawn /usr/bin/ssh -l subhasish *.*.*.* -p 10022
  8 
  9 expect {
 10      -re "password: " {send "$password\r"}
 11      -re "$ "  {send "sudo su\r"}
 12      -re "[sudo] password for subhasish:" {send "$password\r"}
 13      -re "# "  {send "service iptables status\r"}
 14        }
 15 set output $expect_out(buffer)
 16 send "exit\r"
 17 puts "$output\r\n" >> output.log

But when I start in debug mode, I get an error, for example:

expect -d testcase
expect version 5.44.1.15
argv[0] = expect  argv[1] = -d  argv[2] = testcase  
set argc 0
set argv0 "testcase"
set argv ""
executing commands from command file testcase
parent: waiting for sync byte
parent: telling child to go ahead
parent: now unsynchronized from child
spawn: returns {24105}
invalid command name "sudo"
    while executing
"sudo"
    invoked from within
"expect {
     -re "password: " {send "$password\r"}
     -re "$ "  {send "sudo su\r"}
     -re "[sudo] password for subhasish:" {send "$password\r"}
 ..."
    (file "testcase" line 9)

I don’t know where I am mistaken. It specifies an invalid command name "sudo", I think this is because waiting does not mean that this command understands. How to get around this. Please help. Thank.

+5
source share
2 answers

The problem is in this line.

-re "[sudo] password for subhasish:" {send "$password\r"}

Tcl (, , ) (, backticks ). , , , :

-re {[sudo] password for subhasish:} {send "$password\r"}

: ? , , , : 's', 'u', 'd' 'o ". , , :

-re {\[sudo\] password for subhasish:} {send "$password\r"}

-ex {[sudo] password for subhasish:} {send "$password\r"}
+11

, , . , , , sudo, "sudo su" $prompt, , ,

#!/usr/bin/expect -f
#! /bin/bash

set timeout 60
log_user 1
set host *.*.*.*
set password ****** 
set user subhasish
set logfile output.txt
spawn ssh -p 10022 $user@$host
expect "*?assword:*"
send -- "$password\r"
#log_user 1
sleep 2
expect "$"
send -- "sudo su\r"
expect -gl {*password for subhasish:*}
send -- "$password\r"
expect "#"
send -- "service iptables status\r"
log_file /home/subhasish/output.log
expect "#"
log_file
send -- "exit\r";
send -- "exit\r";
exit 0
+3

All Articles