console

SSH 비밀번호 대신 키 파일을 이용한 로그인 방법

여러 서버들을 관리하다 보면 비밀번호를 일일이 입력해서 로그인하는 것도 상당히 번거로운 작업입니다. 게다가 보안을 위한다며 길게 작성한 비밀번호를 여러 개 외워서 사용하기는 무척 힘든 일이죠.

이런 어려움을 해결하기 위해 비밀키(private key)와 공개키 파일(public key)을 생성해 이 키 파일을 이용해 로그인하는 방식을 알아보겠습니다.

작업 환경은 기본적으로 우분투 22.04 LTS 버전 기준입니다.

1. SSH 비밀키-공개키 파일 생성하기

로컬에서 비밀키-공개키 파일을 생성합니다

> ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/doogle/.ssh/id_rsa): (엔터)
Created directory '/home/doogle/.ssh'.
Enter passphrase (empty for no passphrase): (엔터)
Enter same passphrase again: (엔터)
Your identification has been saved in /home/doogle/.ssh/id_rsa
Your public key has been saved in /home/doogle/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:******************************************* doogle@doogle-ubuntu
The key's randomart image is:
+---[RSA 3072]----+
|          =E+ .  |
|         o =.+   |
|        . o . =  |
|         =.o + + |
|   .    S...o.+ .|
|  . .  o.  o+.o.o|
| .   .o. ..oo= + |
|  ..  ooooo.o.+  |
| ...oo..+ooo .   |
+----[SHA256]-----+

위와 같이 명령어를 실행하면 키 파일을 저장할 위치와 비밀번호 입력 및 재입력을 할 수 있는데요.

기본값으로 사용하고 비밀번호 입력 없이 사용하고 싶기 때문에 아무런 입력 없이 엔터키만 누르면 됩니다. 그러면 현재 접속한 터미널에 로그인한 계정의 홈 경로에 비밀키 .ssh/id_rsa 파일과 공개키 .ssh/id_rsa.pub 파일을 생성해 줍니다.

이제 생성한 공개키 파일을 로그인하고자 하는 원격 서버에 설치해 주면 됩니다.

2. 원격 서버에 공개키 설치

우분투 리눅스의 경우 ssh-copy-id 명령을 사용할 수 있습니다.

> ssh-copy-id -i (공개키파일 경로) (원격서버 아이디)@(원격서버 주소)

<예제>
> ssh-copy-id -i ~/.ssh/id_rsa.pub doogle@doogle.link

만약 이미 로그인을 한 적이 있다면 아래와 같은 호스트키 확인 실패 오류가 나올 수 있습니다.

/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/doogle/.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: ERROR: @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
ERROR: @    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
ERROR: @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
ERROR: IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
ERROR: Someone could be eavesdropping on you right now (man-in-the-middle attack)!
ERROR: It is also possible that a host key has just been changed.
ERROR: The fingerprint for the ECDSA key sent by the remote host is
ERROR: SHA256:r****************************************k.
ERROR: Please contact your system administrator.
ERROR: Add correct host key in /home/doogle/.ssh/known_hosts to get rid of this message.
ERROR: Offending ECDSA key in /home/doogle/.ssh/known_hosts:11
ERROR:   remove with:
ERROR:   ssh-keygen -f "/home/doogle/.ssh/known_hosts" -R "[doogle.link]:22"
ERROR: Host key for [doogle.link]:22 has changed and you have requested strict checking.
ERROR: Host key verification failed.

이런 경우 에러 메시지에 나온대로 명령어를 실행해주면 됩니다.

> ssh-keygen -f "/home/doogle/.ssh/known_hosts" -R "[doogle.link]:22"

정상적으로 실행되고 나면 아래와 같은 결과가 뜹니다.

# Host [doogle.link]:22 found: line 11
/home/doogle/.ssh/known_hosts updated.
Original contents retained as /home/doogle/.ssh/known_hosts.old

이제 첫번째 명령문을 다시 실행해 봅니다. 중간에 질문하는데 ‘yes’ 를 입력합니다.

> ssh-copy-id -i ~/.ssh/id_rsa.pub -p22 doogle@doogle.link
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/doogle/.ssh/id_rsa.pub"
The authenticity of host '[doogle.link]:22 ([***.***.***.***]:22)' can't be established.
ED25519 key fingerprint is SHA256:a*********************************s.
This host key is known by the following other names/addresses:
    ~/.ssh/known_hosts:37: [hashed name]
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
doogle@doogle.link's password: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh -p '22' 'doogle@doogle.link'"
and check to make sure that only the key(s) you wanted were added.

이제 정상적으로 설치가 끝났습니다.

ssh-copy-id 명령을 쓸 수 없는 환경에서는 scp 를 이용해 공개키를 업로드하면 됩니다. (Windows 나 MacOS 같은 환경의 경우)

혹은 파일질라같은 SFTP 애플리케이션 등을 활용해 업로드할 수도 있습니다.

> scp (공개키파일 경로) (원격서버 주소):/home/(원격서버 아이디)/id_rsa.pub

<원격 서버에 로그인합니다>

# 먼저 원격 서버 사용자 홈 경로에 .ssh 폴더가 없다면 생성합니다.
> mkdir .ssh

# 위에서 업로드한 공개키를 설치합니다.
> cat id_rsa.pub >> ~/.ssh/authorized_keys

이제 키 파일로 로그인 준비를 마쳤습니다.

만약 키 파일로 접속하고 싶은 원격 서버가 여러 개 있다면 각각의 원격 서버마다 2번 작업을 진행해 공개키를 설치해 주면 됩니다.

3. 키 파일로 SSH 로그인 하기

# 기본 경로에 키 파일들이 존재하는 경우 (~/.ssh/id_rsa, ~/ssh/id_rsa.pub)
> ssh (원격 서버 아이디)@(원격 서버 주소)
<예제>
ssh doogle@doogle.link

# 만약 로컬 서버 아이디와 원격 서버 아이디가 같다면 이것도 생략 가능합니다.
> ssh (원격 서버 주소)
<예제>
ssh doogle.link

# 별도 경로에 키 파일들이 존재하는 경우 
> ssh -i (별도 비밀키파일) (원격 서버 아이디)@(원격 서버 주소)
<예제>
ssh -i /home/doogle/custom_path/private.pem doogle@doogle.link

추가로 AWS EC2 리눅스 인스턴스의 경우 키 파일 로그인을 기본으로 하고 있으므로 반드시 개념과 사용방법을 익혀두시기 바랍니다.

이상으로 키 파일을 이용한 SSH 로그인 방법을 알아보았습니다.

읽어주셔서 감사합니다. ^^

참고

  1. https://confluence.curvc.com/pages/releaseview.action?pageId=79004027
  2. https://docs.aws.amazon.com/ko_kr/AWSEC2/latest/UserGuide/AccessingInstancesLinux.html
  3. man ssh