📜  ssh key - Shell-Bash (1)

📅  最后修改于: 2023-12-03 15:05:21.438000             🧑  作者: Mango

SSH Key - Shell/Bash

Introduction

As a programmer, you may already have used SSH (Secure Shell) to log in to remote servers, transfer files, or execute commands remotely. SSH is a secure protocol and is widely used in the industry. However, every time you log in to a remote server, you need to enter your password, which can be tiresome and time-consuming. Moreover, it can be a security risk if someone steals your password. To avoid these problems, you can use SSH keys, which are more secure and convenient than passwords. In this guide, we will explain what SSH keys are, how to generate them, and how to use them.

What is an SSH Key?

An SSH key is an authentication method that uses public-key cryptography to verify your identity. With SSH keys, you don't need to enter your password every time you log in to a remote server. Instead, you generate a pair of keys: a public key and a private key. The public key is shared with the remote server, while the private key is kept on your local machine. When you try to log in to the remote server, it will ask for your private key, which is encrypted with a passphrase. If the passphrase is correct, the server will use the public key to verify your identity and grant you access.

Generating SSH Keys

To generate SSH keys, you can use the ssh-keygen command, which is included in most Linux and macOS systems:

$ ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

This command generates a new SSH key, using the RSA algorithm with a key size of 4096 bits, and adds your email address as a comment. You can accept the default file name and location, or choose a custom one. By default, the private key is stored in the ~/.ssh/id_rsa file, while the public key is stored in the ~/.ssh/id_rsa.pub file.

Copying SSH Keys

Once you have generated your SSH keys, you need to copy the public key to the remote server. You can do this with the ssh-copy-id command:

$ ssh-copy-id user@remote_server

This command copies your public key to the remote server's authorized_keys file, which is used to authenticate your SSH connections. You will be prompted to enter your password for the remote server, for the last time.

Using SSH Keys

To use SSH keys, you need to specify the private key when you log in to the remote server. You can do this with the -i option:

$ ssh -i ~/.ssh/id_rsa user@remote_server

This command logs you in to the remote server, using your SSH key as the authentication method. If you have encrypted your private key with a passphrase, you will be prompted to enter it.

Conclusion

SSH keys are an essential tool for any programmer who needs to log in to remote servers frequently. They are secure, convenient, and easy to use. By following the steps in this guide, you can generate your own SSH keys, copy them to remote servers, and use them to log in securely.