MendyK
MendyK

Reputation: 1488

SSH into remote computer and compile/run code

I made a script (below) that goes into a remote computer and runs C code on it. This script works perfectly but asks for the password multiple times. How can I make it only ask for the password once?

#!/bin/bash

USER=myusername
COMP=remote_computer_name
OUTPUT=$1
ARGS=${@:2}
CODE_DIR="Dir_$$"
SCRIPT_NAME=$(basename $0)
LAST_CREATED_DIR=$(ls -td -- */ | head -n 1)

#Check if we are on local computer. If so, we copy the 
#current directory to the remote run this script on the remote 
if [ "${HOSTNAME}" != "${COMP}" ]; then
  if [ "$#" -lt  1 ]; then
    echo "Incorrect usage."
    echo "Usage: ./${SCRIPT_NAME} <compiled_c_output_name> <arg1> <arg2> ... <argN>"
    exit
  fi
  # Check if there is no makefile in the current directory
  if [ ! -e [Mm]akefile ]; then
    echo "There is no makefile in this directory"
    exit
  fi
  echo "On local. Copying current directory to remote..."
  scp -r ./ ${USER}@${COMP}:/ilab/users/${USER}/${CODE_DIR}
  ssh ${USER}@${COMP} "bash -s" < ./${SCRIPT_NAME} ${OUTPUT} ${ARGS}

else
  echo "On remote. Compiling code..."
  cd $LAST_CREATED_DIR
  make clean
  make all
  if [ -e $OUTPUT ]; then
    echo "EXECUTING \"./${OUTPUT} ${ARGS}\" ON REMOTE ($COMP)"
    ./${OUTPUT} ${ARGS}
  fi
fi

Upvotes: 0

Views: 573

Answers (2)

Ashish K
Ashish K

Reputation: 935

You can use SSH-Key authentication technique for password less login -

Here are the steps :

  • Generate RSA key -

    ssh-keygen -t rsa

    This generates two files under /home/<user>/.ssh/ id_rsa (Private) and id_rsa.pub (Public)

  • The second file is your public key. You have to copy the contents of this file over to the remote computer you want to log into and append it to /home/<user>/.ssh/authorized_keys or use ssh-copy-id utility if available (ssh-copy-id username@remote_host)

    After this, the authentication is done by the public-private key pair and you may not require a password henceforth.

Upvotes: 1

Michael Becerra
Michael Becerra

Reputation: 411

You can use sshpass. Here is an example:

sshpass -pfoobar ssh -o StrictHostKeyChecking=no user@host command_to_run

More info, here:

https://askubuntu.com/questions/282319/how-to-use-sshpass

Upvotes: 0

Related Questions