SSH Auto Login (RSA 키 사용)

ssh를 이용하여 원격지에 접속 시, 비밀번호 입력 없이 접속할 수 있습니다. production 서버에서는 귀찮더라도 비밀번호를 이용합시다. (너무 위험함)

인증에 필요한 RSA 키 생성

ssh-keygen 툴을 이용하여 rsa 키 페어를 생성합니다. 중간에 passphrase를 입력하면 원격지에 접속 시마다 암호를 물어보니 그냥 Enter를 눌러 건너뛰어줍니다.

MacBook-Pro:~ leenit$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/leenit/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /Users/leenit/.ssh/id_rsa.
Your public key has been saved in /Users/leenit/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:udanJpAFAugIcB77iWu4HCef3cYTWCxolLAIpsI3M0g [email protected]
The key's randomart image is:
+---[RSA 3072]----+
|+E=..            |
|Xoo=. .          |
|B++=....         |
|o..=+o o..       |
|  o o +oS        |
| . . .o. o       |
|.oo.  ..+ . .    |
|.o= o .=. .o     |
|.. o ....o.      |
+----[SHA256]-----+

원격지에 인증키 등록 (ssh-copy-id 명령어 이용)

로컬에 ssh-copy-id 명령어가 사용 가능하다면 아래와 같이 간단하게 등록이 가능합니다.

MacBook-Pro:~ leenit$ ssh-copy-id -i ~/.ssh/id_rsa [email protected]
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: ".ssh/id_rsa.pub"
/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.

원격지에 인증키 등록 (ssh-copy-id 명령어가 없을 때)

로컬에 생성된 id_rsa.pub 공개키 파일을 원격지에 업로드하여 인증키 정보를 수동으로 추가할 수 있습니다.

MacBook-Pro:~ leenit$ scp ~/.ssh/id_rsa.pub [email protected]:/home/was/.ssh/
[email protected]'s password: 
id_rsa.pub                                     100%  593     1.2MB/s   00:00    

MacBook-Pro:~ leenit$ ssh [email protected]
[email protected]'s password: 
Last failed login: Fri Apr 24 22:12:46 KST 2020 from 192.168.56.1 on ssh:notty
There was 1 failed login attempt since the last successful login.
Last login: Fri Apr 24 22:10:29 2020 from 192.168.56.1
[was@localhost ~]$ cd ~/.ssh
[was@localhost .ssh]$ cat id_rsa.pub >> authorized_keys
[was@localhost .ssh]$ rm id_rsa.pub

추가 작업 후 보안을 위해 파일 권한을 수정해 줍니다.

[was@localhost ~]$ chmod 700 .ssh
[was@localhost ~]$ chmod 600 .ssh/authorized_keys

모든 작업이 완료되면 원격지에 패스워드 입력 없이 접속이 가능합니다!

MacBook-Pro:~ leenit$ ssh [email protected]
Last login: Fri Apr 24 22:16:51 2020 from 192.168.56.1
[was@localhost ~]$