SSH进入远程计算机并编译/运行代码

时间:2017-03-19 18:07:28

标签: bash shell unix ssh

我创建了一个脚本(下面),它进入远程计算机并在其上运行C代码。此脚本工作正常,但多次要求输入密码。如何才能让它只询问一次密码?

#!/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

2 个答案:

答案 0 :(得分:1)

您可以使用SSH-Key身份验证技术进行无密码登录 -

以下是步骤:

  • 生成RSA密钥 -

    VC3

    这会在ssh-keygen -t rsa /home/<user>/.ssh/下生成两个文件 (私人)和id_rsa(公开)

  • 第二个文件是您的公钥。你必须复制的内容 此文件到您要登录和追加的远程计算机 它到id_rsa.pub或使用/home/<user>/.ssh/authorized_keys 实用程序(ssh-copy-id

    此后,身份验证由公钥 - 私钥对完成 此后你可能不需要密码。

答案 1 :(得分:0)

您可以使用sshpass。这是一个例子:

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

更多信息,这里:

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