Mac scp 使用 expect 避免輸入密碼 scpue

在很早之前我都研究過這塊,最終的方案其實有點差強人意,可以看我那篇博客,當時需要預先寫好腳本,通過調用scp2.sh進行路徑名展開,對那時的我而言,能免密就已然足夠了

隨着我手中的服務器日益增多,而且scp操作已不是固定的N條命令,此時的我需要再次尋找出路。上次的經歷讓我得出的重要結論就是:路徑名展開 是 shell 的特性,expect 沒有,只要我在terminal中輸入路徑名,它總會在執行腳本前展開,堵不如疏,展開就展開嘛,我在腳本中操作展開後的參數不就好了?問題迎刃而解

#!/bin/bash
secret="secret.conf"
remote=""
password=""
port=""

if [[ $1 =~ @ ]]; then
    remote=$1
fi

if [[ ${*:$#:1} =~ @ ]]; then
    remote=${*:$#:1}
fi

eval $(grep ${remote%:*} $secret | awk '{printf("password=\"%s\";port=%s",$2,$3)}')

expect -c "set timeout -1;
spawn scp -r -P $port ${*:1:$#-1} ${*:$#:1};
expect \"Password:\";
send \"$password\n\";
expect eof"

如果你對以上腳本不太理解,我覺得多插入些echo打印會幫助到你

secret.conf大致這樣配置

[email protected] 123456 22

secret修改成絕對路徑,腳本命名爲scpue放在/usr/local/bin目錄中,之後就可以如下使用啦

scpue test* [email protected]:/tmp
scpue [email protected]:/tmp/test* .

注:

  1. 新版本MacOS輸入密碼提示是Password,老版本是password,反正首字母不是大寫就是小寫,按需適當修改scpue腳本
  2. 新版本MacOS默認使用zsh,老版本是bashzsh執行scpue [email protected]:/tmp/test* .會報如下錯誤zsh: no matches found: [email protected]:/tmp/test*,此時可以爲參數加單引號
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章