SSH 공개 키를 여러 Linux 호스트에 복사

SSH 공개 키를 여러 Linux 호스트에 복사

중앙 서버에서 여러 서버로 .ssh/id_rsa.pub를 복사하려고 합니다. 일반적으로 변경 사항을 다른 서버에 푸시하는 데 사용하는 다음 스크립트가 있습니다.

#!/bin/bash


for ip in $(<IPs); do
    # Tell the remote server to start bash, but since its
    # standard input is not a TTY it will start bash in
    # noninteractive mode.
    ssh -q "$ip" bash <<-'EOF'



EOF

done

하지만 이 경우에는 로컬 서버에서 공개 키를 가져온 다음 이를 여러 서버에 추가해야 합니다. 위에 문서화된 스크립트를 사용하여 다음을 수행할 수 있는 방법이 있습니까?

cat .ssh/id_rsa.pub |ssh [email protected] 'cat > .ssh/authorized_keys'

답변1

이 간단한 루프를 사용하면 모든 원격 서버에 자동화하고 전파할 수 있습니다.

#!/bin/bash
for ip in `cat /home/list_of_servers`; do
    ssh-copy-id -i ~/.ssh/id_rsa.pub $ip
done

답변2

다음은 매번 비밀번호를 묻지 않고 ssh-keygen을 여러 서버에 복사하기 위한 간단한 스크립트입니다.

for server in `cat server.txt`;  
do  
    sshpass -p "password" ssh-copy-id -i ~/.ssh/id_rsa.pub user@$server  
done

이것이 필요하다SSH패스, 패키지 또는 소스와 별도로 설치해야 할 수도 있습니다.

답변3

다른 사람의 공개 키를 여러 컴퓨터에 복사해야 하는 경우 허용되는 답변은 작동하지 않습니다. 그래서 저는 다음과 같은 해결책을 생각해 냈습니다.

cat add-vassal-tc-agents.sh

#!/bin/bash
set -x # enable bash debug mode
if [ -s vassal-public-key.pub ]; then # if file exists and not empty
    for ip in `cat tc-agents-list.txt`; do # for each line from the file
        # add EOL to the end of the file (i.e., after the last line)
        # and echo it into ssh, where it is added to the authorized_keys
        sed -e '$s/$/\n/' -s vassal-public-key.pub | ssh "$ip" 'cat >> ~/.ssh/authorized_keys'
    done
else
    echo "Put new vassal public key into ./vassal-public-key.pub to add it to tc-agents-list.txt hosts"
fi

이 스크립트는 실행 중인 환경에 액세스 권한이 있는 경우 컴퓨터 목록의 사용자에게 새 키를 추가합니다.

tc-agents-list.txt:

[email protected]
[email protected]
[email protected]
[email protected]

참고: 이를 위해서는 GNU sed를 사용해야 합니다. 질문에 "Linux"라고 적혀 있으므로 GNU sed가 있을 가능성이 높습니다.

답변4

다음과 같이 간단한 while 루프와 내장된 서버 목록을 사용하여 이 작업을 수행할 수 있습니다.

while read SERVER
do
    ssh-copy-id user@"${SERVER}"
done <<\EOF
server1
server2
server3
EOF

목록을 스크립트에 배치하면 손실될 수 있는 별도의 데이터 파일이 제거됩니다.

관련 정보