簡體   English   中英

遍歷命令並以bash執行

[英]Iterate through commands and execute in bash

我編寫了一個腳本,將新密鑰傳輸到我的AWS實例。 腳本執行沒有錯誤,但是當我檢查實例上的〜/ .ssh / authorized_keys文件時,看不到新的SSH密鑰。

這是腳本:

aws_instances=(             
                "ssh -i \"priv.pem\" ubuntu@99.99.99.1" #server1
                "ssh -i \"priv.pem\" ubuntu@99.99.99.2" #server2
                "ssh -i \"priv.pem\" ubuntu@99.99.99.3" #server3
              )
IFS=""
for t in ${aws_instances[@]}; do
  cat ~/newKey.pub | eval $t  'cat >> ~/.ssh/authorized_keys && echo "Key copied"'
done

它確實打印出“密鑰已復制”

我已經更改了服務器的IP地址。

如果我只執行以下命令,它將起作用。

cat ~/newKey.pub | ssh -i "priv.pem" ubuntu@99.99.99.1  'cat >> ~/.ssh/authorized_keys && echo "Key copied"'

我的腳本有什么問題?

eval是代碼氣味,避免像蟲子一樣。

我認為您可以實現類似的功能:

#!/usr/bin/env bash

# See: https://tools.ietf.org/html/rfc5737
# 3.  Documentation Address Blocks
#
#   The blocks 192.0.2.0/24 (TEST-NET-1), 198.51.100.0/24 (TEST-NET-2),
#   and 203.0.113.0/24 (TEST-NET-3) are provided for use in
#   documentation.

# Array contains user-name@host-or-ip:ssh-port (ssh-port is optional, default standard 22)
aws_instances=(
  'ubuntu@192.0.2.1'
  'ubuntu@192.0.2.2:2222'
  'ubuntu@192.0.2.3:2022'
)

new_keyfile="${HOME}/newKey.pub"

for instance in "${aws_instances[@]}"; do
  ssh_host="${instance%%:*}" # trim the port if specified
  port="${instance##*:}" # trim the host and keep port if specified
  [[ ${port} == "${instance}" || -z "${port}" ]] && port=22 # use default port

  if ssh-copy-id \
    -i "${new_keyfile}" \
    -p "${port}"
    "${ssh_host}"; then
    printf \
      $"The new key file '%s' has been copied to user@host: '%s', port: %d.\\n" \
      "${new_keyfile}" \
      "${instance}" \
      "${port}"
  else
    printf >&2 \
      $"Could not copy the new key file '%s' to user@host: '%s', port: %d.\\n" \
      "${new_keyfile}" \
      "${instance}" \
      "${port}"
  fi
done

您需要在第二個eval參數周圍加上引號。

例如:

cat ~/newKey.pub | eval $t  "'"'cat >> ~/.ssh/authorized_keys && echo "Key copied"'"'"

問題在於,單引號在第一次調用eval時會丟失,因此它將嘗試執行的命令為

ssh -i "priv.pem" ubuntu@99.99.99.1 cat >> ~/.ssh/authorized_keys && echo "Key copied"

該命令僅將ssh命令的輸出附加到本地 authorized_keys文件,而不是將密鑰添加到遠程主機。

有時越簡單越好。 也許這樣可以消除評估?

for i in 1 2 3
do  ssh -i priv.pem ubuntu@99.99.99.$i 'cat >> ~/.ssh/authorized_keys &&
      echo "Key copied" '< ~/newKey.pub
done

(在會議上,無法測試-警告腳本。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM