how to run a local script in remote server using expect and bash script

15,517

Try something like this:

#!/usr/bin/expect
spawn ssh usert@server
expect "user@server's password:" {send "$password\r"}
expect "$ " {send "hostname\n"}
expect "$ " {send "ls -alrth\n"}
expect "$ " {send "exit\n"}

Not sure if it is the most efficient way of doing it, but it seems to work in my test. (spaces after $)

Also, you can put this at the top of your script "exp_internal 1".

This will aid in the debugging process!

Share:
15,517

Related videos on Youtube

user1760929
Author by

user1760929

Updated on September 18, 2022

Comments

  • user1760929
    user1760929 over 1 year

    I want to make a script that will connect to a server and do some CRUD operation on the server and again return to local. I do not want to upload the script to server..

    I have made a script that will help to connect to the server but I am not able to do any any operation through the help of the script.

    please make my doubt clear regarding the fact that weather its possible to run a local script (as in my case ) in the remote server.

    If yes how please specify the script also for which I will be grateful to you .

    till now my script is

    #!/usr/bin/expect
    set ip neviss
    set user user
    set password 1234
    spawn ssh "$user\@$ip"
    expect "Password:"
    send "$password\r";
    interact ( after this line any command is not getting executed) 
    ls -lrt 
    
  • user1760929
    user1760929 over 11 years
    many many thanks sir for answering my query.but can you just explain more like how does it work and what i need to right at the expect "#" {send "hostname\n"} i mean hostname . please reply i am in middle of a problem .please help .
  • user1760929
    user1760929 over 11 years
    I tried in the above process its not working for me ...please help ....
  • bourne
    bourne over 11 years
    Hey sorry for late response. From what I understand you are basically trying to tell the script what to 'expect' after issuing each command. So for instance after sending the password, you would be at a normal command prompt. Now where you might be having a tough time right now is at the pound "#" sign. If you are using root then use the pound "#" sign. If you are using a regular user then use the dollar "$" sign. Regular users use the "$" sign on their command prompt. I will modify the script above
  • bourne
    bourne over 11 years
    Weird. I tested this myself just now and it doesn't seem to work as a regular user. If you do it as root it works as expected. I will keep playing with it.
  • bourne
    bourne over 11 years
    Okay sorry I figured it out. Something stupid. Add a space after the "$".. "$ ". I also found something else very useful.. will add above
  • user1760929
    user1760929 over 11 years
    Thanks sir for everything but still my requirement is not fulfilled .plz help !!!