0

I have below shell script, in which i am login into the particular machine, now i have to execute one command after login in , this command will start/stop/status of particular process.

 #!/usr/bin/expect -f
    spawn ssh root@hostname
    expect "Password:"
    send "password123\r"
    interact  # here it is successfully login into machine, 
    sleep 2
    /sbin/service heartbeat status # I want to execute this command

how I can do it ??

3

You can use

ssh user@hostname "command"

This will open a ssh connection and run the command. You will be prompted for a password, if necessary.

If you want to do this automatically (don't want to enter your password everytime), you should enable a login with a ssh-pub-key.

| improve this answer | |
  • @BhushanPatil then you should click the grey checkmark to accept the answer ;-) – Wayne_Yux Sep 16 '15 at 9:29
0

Once the interactive ssh instance is spawned it takes over the current bash instance, and the following commands are not executed until it has finished its execution.

user@user-X550CL ~ % ssh user@localhost; echo string
user@localhost's password: 
Welcome to Ubuntu 15.04 (GNU/Linux 3.19.0-15-generic x86_64)

 * Documentation:  https://help.ubuntu.com/

Last login: Tue Sep 15 09:10:01 2015 from localhost
user@user-X550CL ~ % exit
Connection to localhost closed.
string

There are multiple ways to solve this;

  1. Pass the command(s) as an argument: spawn ssh root@hostname /sbin/service heartbeat status
user@user-X550CL ~/tmp % ssh user@localhost echo command1
user@localhost's password: 
command1
user@user-X550CL ~/tmp % ssh user@localhost 'echo command1; echo command2; echo command3'
user@localhost's password: 
command1
command2
command3
user@user-X550CL ~/tmp % 
  1. Group the command(s) into another script and pass the script using stdin redirection:
user@user-X550CL ~/tmp % ssh user@localhost <script.sh 
Pseudo-terminal will not be allocated because stdin is not a terminal.
user@localhost's password: 
Welcome to Ubuntu 15.04 (GNU/Linux 3.19.0-15-generic x86_64)

 * Documentation:  https://help.ubuntu.com/

command1
command2
command3
user@user-X550CL ~/tmp % 
| improve this answer | |
  • Thnaks KOS it solved my problem..!! – Bhushan Patil Sep 16 '15 at 9:22
  • 1
    Don't thank me! ;-) If you like the answer, just click the little grey under the "0" now turning it into beautiful green. If you do not like the answer, click on the little grey down-arrow below the 0, and if you really like the answer, click on the little grey checkmark and the little up-arrow... If you have any further questions, just ask another one! – Fabby Sep 17 '15 at 21:18

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.