2

This is continuation to my previous question :Spawn command not found

After referring to few old posts, I have written those commands, If its wrong, then how I can run ssh to remote server and run some commands ?

dbain
  • 77

2 Answers2

2

One possiblity is: create an expect-syntax file, and call that via a shell script:

 #!/bin/bash
 expect -f my-file.exp $1 # parameter 1 is the server name

In the my-file.exp you would only have expect commands:

spawn ssh "username@[lindex $argv 0]"  # param 1 : server name
                                # expect now reads the input and does what you tell it on certain patterns

expect { 
  "password:" { send "my-password\r"; send "do_this_command\r"; send "do_that_command\r"; exp_continue; }
  "done" { send_user "exiting"; }
}

This example logs on to the server sending the clear-text password, then sends some command and continues.

If it reads "done" from the input, it terminates, Otherwise it will time out after a few seconds.

As long as you do a "exp_continue", it stays inside the expect {}-loop, matching input and doing the appropriate output.

glenn jackman
  • 85,964
gerhard d.
  • 2,188
1

You can also use an expect shebang in your shellscript and write an expect script.

#!/usr/bin/expect -f 
spawn ssh localhost 
expect "password: " 
send "password\r" 
expect "{[#>$]}"         #expect several prompts, like #,$ and >
send -- "command.sh\r"
expect "result of command"
etc...
magor
  • 3,752
  • 2
  • 13
  • 28