2017-03-19 97 views
0

我做了一个脚本(下面)进入远程计算机并在其上运行C代码。这个脚本完美地工作,但多次请求密码。我怎样才能让它只要求密码一次?SSH到远程计算机和编译/运行代码

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

公钥认证? – Cyrus

+0

请看看:http://www.shellcheck.net/ – Cyrus

+0

你可以给我看一个例子吗?我曾尝试公钥验证,但它仍然要求密码 – MendyK

回答

0

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

sshpass -pfoobar ssh -o StrictHostKeyChecking=no [email protected] command_to_run 

更多信息,在这里:

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

+0

任何方式,我可以避免依赖?我试图为我和我的同学制作这个脚本 – MendyK

+0

我知道的唯一另一种方式可能是避免使用密码的ssh密钥。检查此:[自动化ssh登录](http://serverfault.com/questions/241588/how-to-automate-ssh-login-with-password) –

+0

我看到了答案。仍然无法做到。这就是为什么我发布我的问题。我认为它不同,如果你试图在脚本中创建私钥 – MendyK

1

您可以使用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 [email protected]_host

    在此之后,该认证由公众进行的远程计算机 - 私人密钥对 ,您可能以后不需要密码。

相关问题