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 ?


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

 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.

|improve this answer|||||

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"
|improve this 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.