gpt4 book ai didi

linux - 遍历命令并在 bash 中执行

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:43:25 25 4
gpt4 key购买 nike

我编写了一个脚本,用于将新 key 传输到我的 AWS 实例。脚本执行时没有错误,但是当我检查实例上的 ~/.ssh/authorized_keys 文件时,我没有看到新的 SSH key 。

这是脚本:

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

它确实打印出“ key 已复制”

我已经更改了服务器的 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

关于linux - 遍历命令并在 bash 中执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57083252/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com