본문 바로가기

리눅스

SSH 키를 생성하고 배포하여 원격 서버에 SSH 접속하는 방법

728x90

SSH 키를 생성하고 배포하여 원격 서버에 SSH 접속하는 방법

1. SSH 키 생성

[server 작업]

  • 로컬 컴퓨터에서 SSH 키 쌍을 생성해야 합니다. 이를 위해 ssh-keygen 명령을 사용합니다.
  • 터미널에서 다음 명령을 실행하여 SSH 키 쌍을 생성합니다
ssh-keygen -t rsa -b 4096 -C "[email protected]"
  • 위 명령을 실행하면 키 쌍 생성을 위해 몇 가지 옵션을 설정하라는 메시지가 표시됩니다. 엔터를 눌러 기본값을 사용하거나 필요한 옵션을 설정합니다.

ssh-keygen 사용법

더보기
usage: ssh-keygen [-q] [-b bits] [-t dsa | ecdsa | ed25519 | rsa | rsa1]
                  [-N new_passphrase] [-C comment] [-f output_keyfile]
       ssh-keygen -p [-P old_passphrase] [-N new_passphrase] [-f keyfile]
       ssh-keygen -i [-m key_format] [-f input_keyfile]
       ssh-keygen -e [-m key_format] [-f input_keyfile]
       ssh-keygen -y [-f input_keyfile]
       ssh-keygen -c [-P passphrase] [-C comment] [-f keyfile]
       ssh-keygen -l [-v] [-E fingerprint_hash] [-f input_keyfile]
       ssh-keygen -B [-f input_keyfile]
       ssh-keygen -D pkcs11
       ssh-keygen -F hostname [-f known_hosts_file] [-l]
       ssh-keygen -H [-f known_hosts_file]
       ssh-keygen -R hostname [-f known_hosts_file]
       ssh-keygen -r hostname [-f input_keyfile] [-g]
       ssh-keygen -G output_file [-v] [-b bits] [-M memory] [-S start_point]
       ssh-keygen -T output_file -f input_file [-v] [-a rounds] [-J num_lines]
                  [-j start_line] [-K checkpt] [-W generator]
       ssh-keygen -s ca_key -I certificate_identity [-h] [-n principals]
                  [-O option] [-V validity_interval] [-z serial_number] file ...
       ssh-keygen -L [-f input_keyfile]
       ssh-keygen -A
       ssh-keygen -k -f krl_file [-u] [-s ca_public] [-z version_number]
                  file ...
       ssh-keygen -Q -f krl_file file ...
ssh-keygen -t rsa -b 2048 -C "deployment"
$ ssh-keygen -t rsa -b 2048 -C "deployment"
Generating public/private rsa key pair.
Enter file in which to save the key (/home/user1/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/user1/.ssh/id_rsa
Your public key has been saved in /home/user1/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:CqK6eVBjV/ybE/HXJWWDhdeSAgzaoaqx1xpFdH0hcHo deployment
The key's randomart image is:
+---[RSA 2048]----+
|     .. ==+...+=+|
|     .o=.+o.oo+o+|
|     .+.ooE. o.+ |
|  + .o  o.. . .  |
| oooo . S+ .     |
|.. = + .+        |
|..o o o  .       |
|.... o           |
|+o  .            |
+----[SHA256]-----+
$ ls ~/.ssh
id_rsa  id_rsa.pub
$ cat ~/.ssh/id_rsa
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABFwAAAAdzc2gtcn
NhAAAAAwEAAQAAAQEAs8VIoYtkQc7+/DpgrpvdnFDacfchas/QYZGA4fGoKvYQY4pgyj4R
+eTtKgYZYjTcOvYlcSlNAqq9kieN2KgP+9wktXDHahNiEUDbrpiyy/GwaapAHC/AxAVOag
...
BmFM6g1aNkGVwCPlPX9ruayRR4gYqZSCujo2zSmrNH7rXLbj/wDwgTwKrIeMHKEZTK+19p
yCcWuXskLLscMq3SMCNCmB2pwENddheFX3UMdLu3vI9j/YMjTl4enojZOvg+uElVqMHTZG
sO+JkKAKXxvrLpkAAAAKZGVwbG95bWVudAE=
-----END OPENSSH PRIVATE KEY-----
$ cat ~/.ssh/id_rsa.pub 
ssh-rsa AAAAB3NzaC1yc2EAAAADAQ...tlAFfwZLZC08Msj21pRpmGvaclj1t/hTIYv deployment

2. SSH 키 배포

[client 작업]

  • 원격 서버에 공개 키를 배포하여 인증할 수 있도록 해야 합니다.
  • 다음 명령을 사용하여 로컬의 공개 키를 원격 서버의 ~/.ssh/authorized_keys 파일에 추가합니다.
ssh-copy-id user@remote_host
  • user는 원격 서버의 사용자 이름, remote_host는 접속하려는 원격 서버의 주소 또는 호스트 이름입니다.
  • 명령을 실행하면 비밀번호를 입력하라는 메시지가 표시됩니다. 해당 비밀번호를 입력하면 공개 키가 원격 서버로 전송됩니다.

ssh-copy-id 사용법

더보기
Usage: /bin/ssh-copy-id [-h|-?|-f|-n] [-i [identity_file]] [-p port] [[-o <ssh -o options>] ...] [user@]hostname
	-f: force mode -- copy keys without trying to check if they are already installed
	-n: dry run    -- no keys are actually copied
	-h|-?: print this help
728x90
ssh-copy-id [email protected]
$ ssh-copy-id [email protected]
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/user1/.ssh/id_rsa.pub"
The authenticity of host '192.168.0.245 (192.168.0.245)' can't be established.
ED25519 key fingerprint is SHA256:b5i+5jsCHp0iYsZeFltYWwTdBOY79LmuB1CW9SWopYs.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
[email protected]'s password: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh '[email protected]'"
and check to make sure that only the key(s) you wanted were added.
$ ls -l .ssh/authorized_keys 
-rw------- 1 user1 user1 786 Oct 21 08:42 .ssh/authorized_keys
$ cat .ssh/authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAADAQ...tlAFfwZLZC08Msj21pRpmGvaclj1t/hTIYv deployment

[client 작업]

  • .ssh 디렉토리 생성
mkdir -pv /home/user1/.ssh
chmod 700 /home/user1/.ssh

[server 작업]

  • scp 명령어로 SSH Key 배포
scp id_rsa.pub [email protected]:~/.ssh/authorized_keys
scp id_rsa.pub [email protected]:~/.ssh/authorized_keys
scp id_rsa.pub [email protected]:~/.ssh/authorized_keys

3. SSH 접속

[server 작업]

  • SSH 키 배포가 완료되면 다음 명령을 사용하여 원격 서버에 SSH로 접속할 수 있습니다.
ssh user@remote_host
  • user는 원격 서버의 사용자 이름, remote_host는 접속하려는 원격 서버의 주소 또는 호스트 이름입니다.
  • 비밀번호 대신에 SSH 키를 사용하여 인증하므로 비밀번호 입력 없이 접속됩니다.
ssh [email protected] free -m
$ ssh [email protected] free -m
              total        used        free      shared  buff/cache   available
Mem:           7.6G        467M        5.8G        123M        1.4G        6.7G
Swap:          8.0G         32M        8.0G

 

728x90

'리눅스' 카테고리의 다른 글

[iac][ansible] ansible-vault 명령  (0) 2022.08.25
ansible-galaxy 명령어  (0) 2022.08.25
Ansible 설치 및 업그레이드  (0) 2022.08.23
CentOS 7에서 python3 업그레이드  (0) 2022.08.23
[Ansible] inventory(인벤토리) 설정  (0) 2022.08.22