2017-03-19 103 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

    在此之後,該認證由公衆進行的遠程計算機 - 私人密鑰對 ,您可能以後不需要密碼。

相關問題