0

Shell script which i have is having two different part.

  1. Setting Environment Platform
  2. Scripts for package installation on remote host.

Example:

#!/bin/bash
# Setting Environment Platform
init(){
    echo "Enter username of guest machine"
    read USERNAME    
    echo "Enter IP of guest machine"
    read GUEST_IP
    echo "Guest IP : $GUEST_IP"   
    echo "Guest Username $USERNAME"
    echo "running === ssh -l $USERNAME $GUEST_IP"
    if ssh -l $USERNAME $GUEST_IP; then
        install_packages
        echo SUCCESS
    else 
        retry_connection
        echo FAIL
    fi
}
# Scripts for package installation on remote host.
install_packages(){
    sudo apt-get -y update && apt-get -y upgrade
    sudo apt-get -y install aptitude
    sudo apt-get -y install default-jre
    sudo apt-get -y install default-jdk
}
retry_connection(){
    if ssh -l $USERNAME $GUEST_IP; then
        install_packages
        echo SUCCESS
    else 
        retry_connection
        echo FAIL
    fi
}

So, in this the first part init() should run in my machine itself. On success of the ssh connection install_packages() should run in guest machine which is entered in init(). How can i do it?

Vicky
  • 469
  • 3
  • 9
  • 22

1 Answers1

1

You'll have to pass your function definition to the remote side and then call it there. To do that instead of calling install_packages you might do something like this:

ssh ${USERNAME}@${GUEST_IP} "$(typeset -f install_packages); install_packages;"

References: Shell script: Run function from script over ssh, https://serverfault.com/questions/649359/executing-local-function-code-on-a-remote-server

Community
  • 1
  • 1
dekkard
  • 6,121
  • 1
  • 16
  • 26