Search code examples
bashshellsshsudo

Automate SSH and running commands


I am trying to automate SSH into a machine and then run some commands. However, I am getting stuck at the SSH portion:

for h in ${hosts[*]}; do
        ssh -i foo.pem bc2-user@$h
        echo "here"
        sudo bash
        cd /data/kafka/tmp/kafka-logs/
        exit 
        exit
done

As soon as I run this script, I am able to SSH in but the automation stops at this message:

********************************************************************************
This is a private computer system containing information that is proprietary
and confidential to the owner of the system.  Only individuals or entities
authorized by the owner of the system are allowed to access or use the system.
Any unauthorized access or use of the system or information is strictly
prohibited.

All violators will be prosecuted to the fullest extent permitted by law.
********************************************************************************
Last login: Thu Dec 10 10:19:23 2015 from 10.81.120.55
-bash: ulimit: open files: cannot modify limit: Operation not permitted

When I press control + d, my echo "here" commands executes and then my script exits. Without performing the rest of the commands.

I read around and I tried this but I am getting this syntax error:

./kafka_prefill_count.sh: line 38: warning: here-document at line 26 delimited by end-of-file (wanted `EOF')
./kafka_prefill_count.sh: line 39: syntax error: unexpected end of file

script:

for h in ${hosts[*]}; do
        ssh -i foo.pem bc2-user@$h << EOF
                echo "here"
                sudo bash
                cd /data/kafka/tmp/kafka-logs/
                ls | grep "$dir_name"
                exit
                exit
                bash -l

        EOF
done

Solution

  • Your current script isn't really how you would execute commands remotely using ssh.

    It should look more like this

    shh -i foo.pem user@host 'echo "here" ; hostname'
    

    (hostname command is just example to prove its running on other machine.

    Good resource

    Just saw your edit:

    EOF needs to be all the way to the left.

      ssh -i foo.pem bc2-user@$h << EOF
                echo "here"
                sudo bash
                cd /data/kafka/tmp/kafka-logs/
                ls | grep "$dir_name"
                exit
                exit
                bash -l
    
    EOF