목차
Types of SSH Authentication Methods
What is SSH Key-based Authentication?
Advantages of Key-based Authentication
Configure SSH Key-based Authentication in Linux
Step 1: Generate SSH Key Pair in Local System
Step 2: Copy SSH Public Key to SSH Server (Remote System)
Step 3: Disable SSH Password-based Authentication in Remote SSH Server
Step 4: Test SSH Key-based Authentication
Step 5: Adding New Client System's Keys to SSH Server
Frequently Asked Questions
Conclusion
시스템 튜토리얼 리눅스 Linux에서 SSH 키 기반 인증을 구성하는 방법

Linux에서 SSH 키 기반 인증을 구성하는 방법

Mar 22, 2025 am 09:51 AM

This guide provides an overview of different SSH authentication methods, with a particular focus on SSH key-based authentication. Additionally, this guide will walk you through the steps on how to configure SSH key-based authentication in Linux and Unix-like operating systems.

This Step-By-Step guide covers the following topics:

  • Types of SSH Authentication methods,
  • Overview of SSH Key-based authentication method,
  • Advantages of Key-based authentication method,
  • Generating a key pair,
  • Copy the public key to the SSH server,
  • Disable password-based authentication,
  • Test SSH password authentication,
  • And finally add new clients to SSH server.

Table of Contents

Types of SSH Authentication Methods

Secure Shell, shortly SSH, is the cryptographic network protocol that allows you to securely communicate/access a remote system over unsecured network, for example Internet.

Whenever you send a data over an unsecured network using SSH, the data will be automatically encrypted in the source system, and decrypted in the destination side.

SSH provides four authentication methods namely password-based authentication,key-based authentication, Host-based authentication, and Keyboard authentication.

The most commonly used authentication methods are password-based and key-based authentication methods.

In password-based authentication, all you need is the password of the remote system's user. If you know the password of remote user, you can access the respective system using "ssh user@remote-system-ip" command.

On the other hand, in key-based authentication, you need to generate SSH key pairs and upload the SSH public key to the remote system in order to communicate it via SSH.

Each SSH key pair consists of a private key and public key. The private key should be kept within the client system, and the public key should be uploaded to the remote systems. You should not disclose the private key to anyone.

What is SSH Key-based Authentication?

SSH key-based authentication is a method of authenticating a user to an SSH server using a pair of cryptographic keys. The keys are generated using a key-pair generator, such as the ssh-keygen command. The private key is kept secret by the user, while the public key is shared with the SSH server.

When the user attempts to connect to the SSH server, the server will first check the user's public key against a list of authorized keys. If the public key is found, the server will then challenge the user to provide the corresponding private key. If the user can successfully provide the private key, they will be authenticated and granted access to the SSH server.

SSH key-based authentication is considered to be more secure than password-based authentication because it does not rely on passwords, which can be easily guessed or stolen. Additionally, SSH key-based authentication can be used to automate logins, which can be useful for tasks such as running scripts or transferring files.

Key-based authentication is the most secure type of SSH authentication. However, it can be more difficult to set up and use than password-based or keyboard-interactive authentication.

Here are the steps on how to set up SSH key-based authentication:

  • Generate a key pair on your computer using the ssh-keygen command.
  • Copy the public key to the SSH server's authorized_keys file.
  • Disable password-based authentication on the SSH server.
  • Once you have set up SSH key-based authentication, you can connect to the SSH server without having to enter a password.

Advantages of Key-based Authentication

Here are some advantages of SSH key-based authentication:

  1. Enhanced Security: SSH key-based authentication is significantly more secure than password-based authentication. It is resistant to brute-force attacks and is highly unlikely to be guessed or cracked.
  2. Protection Against Password Theft: Since there are no passwords involved, there's no risk of someone intercepting and stealing your password during the authentication process.
  3. Key Pairs for User and Server: SSH key pairs consist of a public key and a private key. The public key is placed on the server, and the private key is kept on the client machine. This separation adds an extra layer of security, as the private key never leaves your device.
  4. Convenience: Once set up, SSH key-based authentication allows you to log in without having to remember or type passwords. It's especially useful for frequent logins or automation tasks.
  5. Automation and Scripting: SSH key-based authentication is widely used in automation and scripting, as it allows processes to securely connect to remote servers without manual password input.
  6. Multi-Factor Authentication (MFA) Support: SSH key-based authentication can be used in conjunction with MFA, providing an additional layer of security by requiring a second authentication factor (e.g., a passphrase or a hardware token) in addition to the key.
  7. Revocation and Key Management: If a private key is compromised or needs to be revoked for any reason, you can simply remove the corresponding public key from the authorized keys list on the server. This immediate control over access is advantageous.
  8. Auditing and Accountability: SSH key-based authentication provides a clear audit trail of who accessed a server, as each user's access is tied to their unique key. This can be beneficial for compliance and security monitoring.
  9. Compatibility: SSH key-based authentication is widely supported across different operating systems and SSH clients, making it a versatile and cross-platform solution.
  10. Reduced Password Fatigue: Users don't have to remember or manage complex passwords for multiple servers, reducing the risk of using weak or reused passwords.
  11. Longer Key Lengths: SSH key pairs use longer cryptographic keys compared to typical passwords, making them more resilient to attacks.

In summary, SSH key-based authentication offers a combination of strong security and convenience, making it a preferred choice for securing remote access to servers and systems.

Hope you got the basic idea about SSH and its authentication methods. Now let us move on to see how to configure SSH key-based authentication in Linux step by step.

Configure SSH Key-based Authentication in Linux

For the purpose of this guide, I will be using two Debian Linux systems. Debian 11 with IP address 192.168.1.101 is the local system and Debian 12 server with IP address 192.168.1.20 acts as remote system i.e. ssh server.

Local system details:

  • OS : Debian 11 Cinnamon Desktop
  • IP address : 192.168.1.101 /24

Remote system (SSH Server) details:

  • OS : Debian 12 Server
  • IP address : 192.168.1.20/24

Step 1: Generate SSH Key Pair in Local System

As stated already, in SSH key-based authentication method, the public key should be uploaded to the remote system that you want to access via SSH. The public keys will usually be stored in a file called ~/.ssh/authorized_keysin the remote SSH systems.

Important note: Do not generate key pairs as root, as only root would be able to use those keys. Create key pairs as normal user.

Now, let us create the SSH key pair in the local system. To do so, run the following command in your local client system.

$ ssh-keygen
로그인 후 복사
로그인 후 복사

The above command will create a 3072 bit RSA key pair. Enter the passphrase twice. More importantly, remember your passphrase. You'll need it later.

Sample output:

Generating public/private rsa key pair.
Enter file in which to save the key (/home/ostechnix/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/ostechnix/.ssh/id_rsa
Your public key has been saved in /home/ostechnix/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX ostechnix@pvedebian
The key's randomart image is:
+---[RSA 3072]----+
| Bo..o..o.o      |
|* =.o.o  o .     |
|.+ + o+..        |
|..o =.E+         |
|oX + .. S        |
|O * o            |
|++ =             |
|.oX              |
|*=o+             |
+----[SHA256]-----+
로그인 후 복사

Linux에서 SSH 키 기반 인증을 구성하는 방법

In case you have already created the key pair, you will see the following message. Just type "y" to overwrite the existing key .

/home/username/.ssh/id_rsa already exists.
Overwrite (y/n)?<strong>y</strong>
로그인 후 복사

Note:

Please be mindful that providing passphrase is optional. If you give one, you'll be asked to enter the password every time when you try to SSH into a remote system unless you are using any SSH agent to store the password.

If you don't want passphrase (not safe though), simply press ENTER key twice when you are prompted to provide the passphrase. However, I recommend you to use a passphrase.

Using a password-less ssh key is generally not a good idea from a security point of view. They should be limited to very specific cases such as services having to access a remote system without the user intervention (e.g. remote backups with rsync, unison, …).

If you already have a ssh key without a passphrase in private file ~/.ssh/id_rsa and wanted to update key with passphrase, use the following command:

$ ssh-keygen -p -f ~/.ssh/id_rsa
로그인 후 복사

Sample output:

Enter new passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved with the new passphrase.
로그인 후 복사

Step 2: Copy SSH Public Key to SSH Server (Remote System)

We have created the key pair in the local system. Next, copy the SSH public key to your remote SSH server using command:

$ ssh-copy-id ostechnix@192.168.1.20
로그인 후 복사

Here, I will be copying the local (Debian 11 Desktop) system's public key to the remote system (Debian 12 Server in my case).

Technically speaking, the above command will copy the contents of local system's ~/.ssh/id_rsa.pub key into remote system's ~/.ssh/authorized_keys file. Clear? Good.

Type yes to continue connecting to your remote SSH server and then enter the sudo (or root user's) password of the remote system.

/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
ostechnix@192.168.1.20's password: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'ostechnix@192.168.1.20'"
and check to make sure that only the key(s) you wanted were added.
로그인 후 복사

Linux에서 SSH 키 기반 인증을 구성하는 방법

If you have already copied the key, but want to update the key with new passphrase, use -f option to overwrite the existing key like below.

$ ssh-copy-id -f ostechnix@192.168.1.20
로그인 후 복사

We have successfully added the local system's SSH public key to the remote system.

We can now completely disable the password-based authentication in the remote system. Because, we already configured key-based authentication, so we don't need password-base authentication anymore.

Step 3: Disable SSH Password-based Authentication in Remote SSH Server

You need to perform the following commands as root or sudo user.

To disable password-based authentication, go to your remote system's console andedit /etc/ssh/sshd_config configuration file using any editor:

$ sudo nano /etc/ssh/sshd_config
로그인 후 복사

Find the following line. Uncomment it and set it's value as no.

PasswordAuthentication no
로그인 후 복사

Linux에서 SSH 키 기반 인증을 구성하는 방법

Restart sshd service to take effect the changes.

$ sudo systemctl restart sshd
로그인 후 복사

Step 4: Test SSH Key-based Authentication

To verify if you've correctly configured the key-based authentication, you need to access the remote system from the local system via SSH.

Go to your local system and SSH into your remote server using command:

$ ssh ostechnix@192.168.1.20
로그인 후 복사

You will be prompted to enter the passphrase to login to the remote ssh system. Type the password for the key and hit ENTER key.

Linux에서 SSH 키 기반 인증을 구성하는 방법

If you try to access the remote system from a CLI-only system, you will see the following output:

<strong>Enter passphrase for key '/home/sk/.ssh/id_rsa':</strong> 
Last login: Thu Sep  7 14:12:11 2023 from 192.168.1.101
ostechnix@debian12:~$ 
로그인 후 복사

As you noticed, we have logged-in to the remote system's account using passphrase which we created earlier using ssh-keygen command, not using the remote user account's actual password.

If you try to ssh from another client system, you will get this error message. Say for example, I tried to SSH into my Debian 12 server from one of a Ubuntu system using command:

$ ssh sk@192.168.1.20
로그인 후 복사

Sample output:

The authenticity of host '192.168.1.20 (192.168.1.20)' can't be established.
ECDSA key fingerprint is 67:fc:69:b7:d4:4d:fd:6e:38:44:a8:2f:08:ed:f4:21.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.1.20' (ECDSA) to the list of known hosts.
<strong>Permission denied (publickey)</strong>.
로그인 후 복사

As you see in the above output, I can not SSH into my remote SSH server from other systems.

Step 5: Adding New Client System's Keys to SSH Server

This is very important. Like I said already, you can't access the remote system via SSH, except the one you configured (in our case, it's Debian 11 Desktop).

I want to give permissions to more clients to access the remote SSH server. What should I do? Simple. You need to generate the SSH key pair in all your client systems and copy the ssh public key manually to the remote server that you want to access via SSH.

To create SSH key pair on your client systems, run:

$ ssh-keygen
로그인 후 복사
로그인 후 복사

Enter the passphrase twice. After the key pair is generated, copy the public ssh key (not private key) to your remote server manually.

Display the pub key using command:

$ cat ~/.ssh/id_rsa.pub
로그인 후 복사

You should see an output something like below.

ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCt3a9tIeK5rPx9p74/KjEVXa6/OODyRp0QLS/sLp8W6iTxFL+UgALZlupVNgFjvRR5luJ9dLHWwc+d4umavAWz708e6Na9ftEPQtC28rTFsHwmyLKvLkzcGkC5+A0NdbiDZLaK3K3wgq1jzYYKT5k+IaNS6vtrx5LDObcPNPEBDt4vTixQ7GZHrDUUk5586IKeFfwMCWguHveTN7ykmo2EyL2rV7TmYq+eY2ZqqcsoK0fzXMK7iifGXVmuqTkAmZLGZK8a3bPb6VZd7KFum3Ezbu4BXZGp7FVhnOMgau2kYeOH/ItKPzpCAn+dg3NAAziCCxnII9b4nSSGz3mMY4Y7 ostechnix@pvedebian
로그인 후 복사

Copy the entire contents (via USB drive or any medium) and go to your remote server's console. Create a directory called ssh in the home directory as shown below.

$ mkdir -p ~/.ssh
로그인 후 복사

Next, append the your client system's pub key that you generated in the previous step in a file called "~/.ssh/authorized_keys":

$ echo {Your_public_key_contents_here} >> ~/.ssh/authorized_keys
로그인 후 복사

Restart ssh service on the remote system. Now, you'll be able to SSH to your server from the new client.

If manually adding ssh pubkey seems difficult, enable password-based authentication temporarily in the remote system and copy the key using "ssh-copy-id" command from your local system and finally disable the password-based authentication.

Frequently Asked Questions

Here is a list of most commonly asked questions and their answers (FAQ) about SSH Key-based authentication.

Q: What is SSH key-based authentication?

A: SSH key-based authentication is a secure method for logging into remote systems or servers over a network. Instead of using a password, it relies on a pair of cryptographic keys – a public key and a private key – to verify your identity.

Q: How does SSH key-based authentication work?

A: SSH key-based authentication works by generating a unique pair of keys. The public key is placed on the remote server, while the private key remains securely stored on your local machine. When you connect to the server, it checks whether your private key matches the public key stored on the server. If they match, you gain access without needing a password.

Q: What are the advantages of SSH key-based authentication?

A: Here is a list of important features.- Enhanced Security: SSH keys are significantly harder to crack than passwords, making it a more secure authentication method.- Convenience: Once set up, you can log in without entering a password every time.- Automation: SSH keys are commonly used for automated processes, like server-to-server communication or script execution, without user intervention.- Reduced Password Exposure: Since you don't enter passwords, there's no risk of password interception during login.

Q: How do I create SSH keys?

A: You can generate SSH keys using the ssh-keygen command on your local machine. It will create a pair of keys – one public and one private. You'll usually find them in your user's .ssh directory.

Q: Can I use the same SSH key pair on multiple servers?

A: Yes, you can use the same SSH key pair to access multiple servers. However, it's considered more secure to have a unique key pair for each server.

Q: How do I configure SSH key-based authentication on a remote server?

A: You typically append your public key to the ~/.ssh/authorized_keys file on the remote server. This allows the server to recognize your public key when you attempt to connect with your private key.

Q: What happens if I lose my private key?

A: If you lose your private key, you won't be able to use it for authentication. You can generate a new key pair and update your authorized keys on the servers you need to access.

Q: Is SSH key-based authentication compatible with all operating systems and SSH clients?

A: Yes, SSH key-based authentication is widely supported and can be used with various operating systems (Linux, macOS, Windows with tools like PuTTY) and SSH clients.

Q: Can SSH keys be password-protected?

A: Yes, you can add an additional layer of security by password-protecting your private key. This requires entering a password each time you use the private key.

Q: Is SSH key-based authentication suitable for all use cases?

A: While SSH key-based authentication is highly secure and convenient, it may not be suitable for all use cases. For example, it might be less practical for scenarios involving a large number of users or temporary access.


Related Read:

  • How To Setup Multi-Factor Authentication For SSH In Linux
  • Find If A User Is Using Password-based Or Key-based SSH Authentication
  • How To Prevent SSH Brute Force Attacks Using Fail2ban In Linux
  • SSLH – Share A Same Port For HTTPS And SSH
  • ScanSSH – Fast SSH Server And Open Proxy Scanner

Conclusion

SSH Key-based authentication provides an extra layer protection for your Linux servers from brute-force attacks. As you can see, configuring key-based authentication is not that difficult. Using key-based authentication is one of the recommended method to keep your Linux server safe and secure.

위 내용은 Linux에서 SSH 키 기반 인증을 구성하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Linux를 가장 많이 사용하는 것은 무엇입니까? Linux를 가장 많이 사용하는 것은 무엇입니까? Apr 09, 2025 am 12:02 AM

Linux는 서버, 임베디드 시스템 및 데스크탑 환경에서 널리 사용됩니다. 1) 서버 필드에서 Linux는 안정성 및 보안으로 인해 웹 사이트, 데이터베이스 및 응용 프로그램을 호스팅하기에 이상적인 선택이되었습니다. 2) 임베디드 시스템에서 Linux는 높은 사용자 정의 및 효율성으로 인기가 있습니다. 3) 데스크탑 환경에서 Linux는 다양한 사용자의 요구를 충족시키기 위해 다양한 데스크탑 환경을 제공합니다.

Linux 기본 사항을 배우는 방법? Linux 기본 사항을 배우는 방법? Apr 10, 2025 am 09:32 AM

기본 Linux 학습 방법은 다음과 같습니다. 1. 파일 시스템 및 명령 줄 인터페이스 이해, 2. LS, CD, MKDIR, 3. 파일 생성 및 편집과 같은 파일 작업 배우기, 4. 파이프 라인 및 GREP 명령과 같은 고급 사용법, 5. 연습 및 탐색을 통해 지속적으로 기술을 향상시킵니다.

인터넷은 Linux에서 실행됩니까? 인터넷은 Linux에서 실행됩니까? Apr 14, 2025 am 12:03 AM

인터넷은 단일 운영 체제에 의존하지 않지만 Linux는 이에 중요한 역할을합니다. Linux는 서버 및 네트워크 장치에서 널리 사용되며 안정성, 보안 및 확장 성으로 인기가 있습니다.

Linux 운영이란 무엇입니까? Linux 운영이란 무엇입니까? Apr 13, 2025 am 12:20 AM

Linux 운영 체제의 핵심은 명령 줄 인터페이스이며 명령 줄을 통해 다양한 작업을 수행 할 수 있습니다. 1. 파일 및 디렉토리 작업 LS, CD, MKDIR, RM 및 기타 명령을 사용하여 파일 및 디렉토리를 관리합니다. 2. 사용자 및 권한 관리는 UserAdd, Passwd, CHMOD 및 기타 명령을 통해 시스템 보안 및 리소스 할당을 보장합니다. 3. 프로세스 관리는 PS, Kill 및 기타 명령을 사용하여 시스템 프로세스를 모니터링하고 제어합니다. 4. 네트워크 운영에는 Ping, Ifconfig, SSH 및 기타 명령이 포함되어 있으며 네트워크 연결을 구성하고 관리합니다. 5. 시스템 모니터링 및 유지 관리 Top, DF, Du와 같은 명령을 사용하여 시스템의 작동 상태 및 리소스 사용을 이해합니다.

Linux 관리자의 급여는 무엇입니까? Linux 관리자의 급여는 무엇입니까? Apr 17, 2025 am 12:24 AM

Linux 관리자의 평균 연봉은 미국에서 $ 75,000 ~ $ 95,000, 유럽에서는 40,000 유로에서 60,000 유로입니다. 급여를 늘리려면 다음과 같이 할 수 있습니다. 1. 클라우드 컴퓨팅 및 컨테이너 기술과 같은 새로운 기술을 지속적으로 배울 수 있습니다. 2. 프로젝트 경험을 축적하고 포트폴리오를 설정합니다. 3. 전문 네트워크를 설정하고 네트워크를 확장하십시오.

Linux 시스템 관리자의 주요 작업은 무엇입니까? Linux 시스템 관리자의 주요 작업은 무엇입니까? Apr 19, 2025 am 12:23 AM

Linux 시스템 관리자의 주요 작업에는 시스템 모니터링 및 성능 조정, 사용자 관리, 소프트웨어 패키지 관리, 보안 관리 및 백업, 문제 해결 및 해상도, 성능 최적화 및 모범 사례가 포함됩니다. 1. 상단, HTOP 및 기타 도구를 사용하여 시스템 성능을 모니터링하고 조정하십시오. 2. 사용자 ADD 명령 및 기타 명령을 통해 사용자 계정 및 권한을 관리합니다. 3. APT 및 YUM을 사용하여 소프트웨어 패키지를 관리하여 시스템 업데이트 및 보안을 보장합니다. 4. 방화벽을 구성하고 로그를 모니터링하고 데이터 백업을 수행하여 시스템 보안을 보장합니다. 5. 로그 분석 및 공구 사용을 통해 문제를 해결하고 해결합니다. 6. 커널 매개 변수 및 응용 프로그램 구성을 최적화하고 모범 사례를 따라 시스템 성능 및 안정성을 향상시킵니다.

Linux 별칭을 사용하여 사용자 정의 명령 바로 가기로 생산성을 높이십시오 Linux 별칭을 사용하여 사용자 정의 명령 바로 가기로 생산성을 높이십시오 Apr 12, 2025 am 11:43 AM

소개 Linux는 유연성과 효율성으로 인해 개발자, 시스템 관리자 및 전원 사용자가 선호하는 강력한 운영 체제입니다. 그러나 길고 복잡한 명령을 자주 사용하는 것은 지루하고 응급실이 될 수 있습니다.

Linux의 주요 목적은 무엇입니까? Linux의 주요 목적은 무엇입니까? Apr 16, 2025 am 12:19 AM

Linux의 주요 용도에는 다음이 포함됩니다. 1. 서버 운영 체제, 2. 임베디드 시스템, 3. 데스크탑 운영 체제, 4. 개발 및 테스트 환경. Linux는이 분야에서 뛰어나 안정성, 보안 및 효율적인 개발 도구를 제공합니다.

See all articles