通过 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

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

以下是步骤:

  • 生成 RSA 密钥 -

    ssh-keygen -t rsa

    这将在/home/<user>/.ssh/ id_rsa下生成两个文件(私人(和id_rsa.pub(公共(

  • 第二个文件是您的公钥。您必须复制以下内容此文件将该文件附加到要登录并追加的远程计算机它/home/<user>/.ssh/authorized_keys或使用ssh-copy-id实用程序(如果可用( ( ssh-copy-id username@remote_host (

    在此之后,身份验证由公钥-私钥对完成从此以后,您可能不需要密码。

您可以使用 sshpass。下面是一个示例:

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

更多信息,请点击此处:

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

最新更新