๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ’ปTech/๐ŸงLinux

[๋ฆฌ๋ˆ…์Šค] ssh ํŒจ์Šค์›Œ๋“œ ์ž…๋ ฅ์—†์ด ์ ‘์† (passwordless)

by _viper_ 2023. 8. 21.
๋ฐ˜์‘ํ˜•

 


๋ฆฌ๋ˆ…์Šค์—์„œ ํŒจ์Šค์›Œ๋“œ ์ž…๋ ฅ ์—†์ด 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