πŸ’»Tech/🐧Linux

[λ¦¬λˆ…μŠ€] ssh νŒ¨μŠ€μ›Œλ“œ μž…λ ₯없이 접속 (passwordless)

_viper_ 2023. 8. 21. 16:37
λ°˜μ‘ν˜•

 


λ¦¬λˆ…μŠ€μ—μ„œ νŒ¨μŠ€μ›Œλ“œ μž…λ ₯ 없이 ssh μ ‘μ†ν•˜λŠ” 2가지 방법 μ •λ¦¬ν•©λ‹ˆλ‹€.

 

1. νŒ¨μŠ€μ›Œλ“œ μž…λ ₯ 없이 접속할 μ„œλ²„μ— μ•”ν˜Έν™” ν‚€λ₯Ό λ“±λ‘ν•˜μ—¬ μžλ™λ‘œκ·ΈμΈμ„ ν•©λ‹ˆλ‹€.

β—Ύ rsa ν‚€ 생성이 μ•ˆλ˜μžˆμ„ 경우 생성해 μ€λ‹ˆλ‹€.

ssh-keygen -t rsa

Enter file in which to save the key (/home/hadoop/.ssh/id_rsa):    ## ()κ΄„ν˜Έ μœ„μΉ˜λ‘œ μ‚¬μš©ν•  κ±°λ©΄ Enter
Enter passphrase (empty for no passphrase):                        ## νŒ¨μŠ€μ›Œλ“œ 없이 μ‚¬μš©ν•  κ±°λ©΄ Enter
Enter same passphrase again:                                       ## Enter

 

β—Ύ authorized_keys 파일이 μ—†μœΌλ©΄ μƒμ„±ν•˜λ©΄ λ©λ‹ˆλ‹€.

chmod 700 ~/.ssh                   ## 700으둜 κΆŒν•œ λ³€κ²½
cd ~/.ssh                          ## .ssh경둜 이동
cat id_rsa.pub >> authorized_keys  ## λ³΅μ‚¬ν•œ κ³΅κ°œν‚€λ₯Ό 인증킀 νŒŒμΌμ— μž…λ ₯ν•΄μ€Œ
chmod 600 authorized_keys          ## private key의 νΌλ―Έμ…˜μ΄ λ„ˆλ¬΄ openλ˜μ–΄ 있으면 접속할 수 μ—†μ–΄μ„œ λ³€κ²½ν•΄μ€Œ

rsync -av .ssh server01:/root      ## passwordless μ„€μ •ν•  μ„œλ²„λ“€μ— .ssh 디렉토리 볡사
rsync -av .ssh server02:/root
rsync -av .ssh server03:/root


## λ¬Έμ œμ‹œ μ•„λž˜ ν•­λͺ© 확인
chmod 600 ~/.ssh/id_rsa
chmod 644 ~/.ssh/id_rsa.pub  
chmod 644 ~/.ssh/known_hosts

[root@localhost ~]# ll -d /root
dr-xr-x---. 5 root root 4096 Feb 28 16:22 /root  ## root κΆŒν•œμ΄ 550으둜 λ˜μ–΄ μžˆμ–΄μ•Όν•¨

 

β—Ύ passwordless μ„€μ • ν›„ 원격 μž‘μ—…λ•Œ μœ μš©ν•œ λ°©λ²•μž…λ‹ˆλ‹€.
2021.03.04 - [Tech/Linux] - [λ¦¬λˆ…μŠ€] μ—¬λŸ¬ μ„œλ²„ 원격 μž‘μ—… (parallel-ssh, ssh remote shell)

 

2. sshpass λͺ…λ Ήμ–΄λ‘œ νŒ¨μŠ€μ›Œλ“œ μž…λ ₯ν•˜μ—¬ ssh 접속 (sshpass μ„€μΉ˜ ν•„μš”)

sshpass λͺ…λ Ήμ–΄λ₯Ό μ‚¬μš©ν•˜λ©΄ νŒ¨μŠ€μ›Œλ“œλŠ” μž…λ ₯ν•˜λ‚˜ λ³„λ„μ˜ νŒ¨μŠ€μ›Œλ“œ 확인 단계 없이 접속 κ°€λŠ₯ν•©λ‹ˆλ‹€.

그리고 sshpassλ₯Ό μ‚¬μš©ν•˜μ—¬ μ™ΈλΆ€ λ‹€λ₯Έ μ„œλ²„μ— λͺ…λ Ήμ–΄λ₯Ό ν˜ΈμΆœν•˜μ—¬ μž‘μ—…λ„ ν•  수 μžˆμŠ΅λ‹ˆλ‹€.

"command" > μ—¬κΈ° μž…λ ₯ν•˜μ„Έμš”.

sshpass -p'password' ssh root@hostname "command"

 

πŸ”Ž μ°Έκ³ 

μ—¬λŸ¬ μ„œλ²„μ— μ μš©ν•˜λŠ” remote μ‰˜μž…λ‹ˆλ‹€.

  • hosts νŒŒμΌμ— μ μš©ν•  μ„œλ²„ λͺ©λ‘λ“€μ„ μ €μž₯ν•©λ‹ˆλ‹€
#!/bin/bash
for target_host in `cat hosts`
do
        sshpass -p '$password' ssh -o StrictHostKeyChecking=no ${target_host} 'mkdir -p ~/.ssh' && cat ~/.ssh/id_rsa.pub | sshpass -p 'hadoop' ssh ${target_host} "cat > ~/.ssh/authorized_keys && chmod 700 ~/.ssh && chmod 0644 ~/.ssh/authorized_keys"
        echo "---------------------------------------------------"
done