1
function test1 {
    ssh -i identity file USER@SERVER1 << EOF
    sudo su
    command 1
    command 2
    command 3
    some_other_commands
    exit
EOF
}

function test2 {
    ssh -i identity file USER@SERVER2 << EOF
    sudo su
    command 1
    command 2
    command 3
    some_commands
    exit
EOF
}

function common {

    sudo su
    command 1
    command 2
    command 3
}

I would like to avoid duplications on the scripts by invoking common in test1 and test2. Ideally I want this

function test2 {
    ssh -i identity file USER@SERVER2 << EOF
    common
    some_commands
    exit
EOF
}

Right now it can not be invoked since it does the ssh first and common is not acccessable anymore from SERVER2.

What is the best way to solve this? Can someone guide me?

  • can't you put common as script file on the server ? – pLumo Apr 15 at 13:04
  • yes this is one way that could be done – bhordupur Apr 15 at 13:06
0

You could try executing what you need by redirecting cat yourscript to ssh. If you want the same script to be executed differently on each server, use if condition. For example, you have the next script:

$ cat sshcommands.sh 
#!/bin/bash

main () {
  if [ $(hostname) = 'pc' ]; then
    test1 
    echo "It claims to be PC......................."
  fi

  if [ $(hostname) = 'ubuntu' ]; then
    test2
    echo "It claims to be UBUNTU"
  fi
}

test1 () {
    echo "with common:"
    common
    hostname
    echo "This is pc"
}

test2 () {
    echo "without common"
    hostname
    echo "This is ubuntu"
}

common () {
    echo "Common start *******************"
    ls /
    lshw -C network
    echo "Common end   ********************"
}

main

You could pass it to your ssh server by command:

cat ./sshcommands.sh | ssh user@your_server_IP

How to work with sudo in this case you could see here. Look at sshpass solutions like this:

$ apt-get install sshpass
$ sshpass -p 'password' ssh username@server
| 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.