2

I want to run the same set of Unix commands on multiple machines. I am aware of ssh and something like the below. I want to write a shell script to do this. I have access to bash and ksh and I'm on Linux Red Hat 5.

ssh root@ip "echo \$HOME"

However, I have 2 questions:

  1. I keep getting prompted for a password. How can I have it not prompt me and enter the password automatically?
  2. How can I execute multiple commands?

3 Answers 3

7
  1. You should use key based authentification, possibly coupled with ssh-agent to remember key passphrase.

  2. You can invoke sh -c as the command, and pass it a string containing the list of command to execute. ssh invoke a shell on the remote machine, so you can pass a list of command as a string.

For example:

$ ssh user@ip "echo 'Hello world'; whoami; cd / ; ls"
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you, this information looks helpful. However, even after generating a key on machine 1 and adding it to machine 2 as described in that link, I am still prompted for a password. Do you have any thoughts? Here is what I did: 1.) machine1: ssh-keygen 2.) machine1: ssh-copy-id -i .ssh/id_rsa.pub user@ip
You now need to start up ssh-agent and use ssh-add to add it to your keychain to prevent future password prompting.
Please note, that you need to do that every time you login. You could also create a ssh key without passphrase, but be aware of the security implication (everybody who can get read access to the private key will be able to connect without password).
You don't need the sh -c part, ssh starts a shell anyway. In fact, do not use sh -c, as it requires yet another level of quoting (@Sylvain: your command doesn't work because you haven't put that extra level of quoting).
1

Use ssh-agent to set up authentication for all commands. Or put your multiple commands into a single shell script.

Comments

0
  1. Send a list of commands to the remote shell. Possible solutions:

    • use ", escape line breaks to format code and end each substatement with ;.
      Disadvantage: " should not be used inside the command list.

      ssh user@ip "\
        echo 'Hallo sir, how are you doing?';\
        whoami;\
        cd /;\
        ls\
      "
      
    • use ' and format code with regular line breaks.
      Disadvantage: ' should not be used inside the command list.

      ssh user@ip '
        echo "Hallo sir, how are you doing?"
        whoami
        cd /
        ls
      '
      

Note: using " or ' inside the respective statements will not necessarily result in an error. Though you may get unsuspected results.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.