详细步骤:创建和管理 Azure 中的 Linux VM 用于身份验证的 SSH 密钥Detailed steps: Create and manage SSH keys for authentication to a Linux VM in Azure

使用安全外壳 (SSH) 密钥对,可在 Azure 上创建默认使用 SSH 密钥进行身份验证的 Linux 虚拟机,从而无需密码即可登录。With a secure shell (SSH) key pair, you can create a Linux virtual machine on Azure that defaults to using SSH keys for authentication, eliminating the need for passwords to sign in. 使用 Azure 门户、Azure CLI、资源管理器模板或其他工具创建的 VM 可在部署中包含 SSH 公钥,为 SSH 连接设置 SSH 密钥身份验证。VMs created with the Azure portal, Azure CLI, Resource Manager templates, or other tools can include your SSH public key as part of the deployment, which sets up SSH key authentication for SSH connections.

本文提供创建和管理用于 SSH 客户端连接的 SSH RSA 公钥/私钥文件对的详细背景和步骤。This article provides detailed background and steps to create and manage an SSH RSA public-private key file pair for SSH client connections. 如果想要快捷命令,请参阅如何创建适用于 Azure 中 Linux VM 的 SSH 公钥/私钥对If you want quick commands, see How to create an SSH public-private key pair for Linux VMs in Azure.

有关在 Windows 计算机上生成和使用 SSH 密钥的其他方式,请参阅如何在 Azure 上将 SSH 密钥与 Windows 配合使用For additional ways to generate and use SSH keys on a Windows computer, see How to use SSH keys with Windows on Azure.

SSH 和密钥的概述Overview of SSH and keys

SSH 是一种加密的连接协议,利用该协议可以通过未受保护的连接进行安全登录。SSH is an encrypted connection protocol that allows secure sign-ins over unsecured connections. SSH 是在 Azure 中托管的 Linux VM 的默认连接协议。SSH is the default connection protocol for Linux VMs hosted in Azure. 虽然 SSH 本身提供加密连接,但是将密码用于 SSH 连接仍使 VM 易受到强力破解攻击或猜测密码。Although SSH itself provides an encrypted connection, using passwords with SSH connections still leaves the VM vulnerable to brute-force attacks or guessing of passwords. 使用 SSH 连接到 VM 的更安全且首选的方法是使用公钥-私钥对,也称为 SSH 密钥。A more secure and preferred method of connecting to a VM using SSH is by using a public-private key pair, also known as SSH keys.

  • 公钥放置在 Linux VM 上或者要对其使用公钥加密的任何其他服务中。The public key is placed on your Linux VM, or any other service that you wish to use with public-key cryptography.

  • 你连接到 Linux VM 时,SSH 客户端使用你本地系统上的私钥来验证你的身份。The private key on you local system is used by an SSH client to verify your identity when you connect to your Linux VM. 请保护好私钥,Protect this private key. 不要透露给其他人。Do not share it.

根据组织的安全策略,可重复使用单个公钥-私钥对来访问多个 Azure VM 和服务。Depending on your organization's security policies, you can reuse a single public-private key pair to access multiple Azure VMs and services. 无需对要访问的每个 VM 或服务使用单独的密钥对。You do not need a separate pair of keys for each VM or service you wish to access.

公钥可与任何人共享;但只有你(或本地安全基础结构)才应拥有私钥。Your public key can be shared with anyone, but only you (or your local security infrastructure) should possess your private key.

私钥密码Private key passphrase

SSH 私钥应使用非常安全的密码来保护它。The SSH private key should have a very secure passphrase to safeguard it. 此密码只用于访问 SSH 私钥文件,不是用户帐户密码 。This passphrase is just to access the private SSH key file and is not the user account password. 向 SSH 密钥添加密码时,会使用 128 位 AES 加密私钥,因此在不能通过密码解密的情况下,私钥是没有用的。When you add a passphrase to your SSH key, it encrypts the private key using 128-bit AES, so that the private key is useless without the passphrase to decrypt it. 如果攻击者窃取了私钥,并且该私钥没有密码,那么他们就能使用私钥登录到有相应公钥的任何服务器。If an attacker stole your private key and that key did not have a passphrase, they would be able to use that private key to sign in to any servers that have the corresponding public key. 如果私钥受密码保护,攻击者就无法使用,从而为 Azure 基础结构提供一个额外的安全层。If a private key is protected by a passphrase, it cannot be used by that attacker, providing an additional layer of security for your infrastructure on Azure.

受支持的 SSH 密钥格式Supported SSH key formats

Azure 目前支持最小长度为 2048 位的 SSH 协议 2 (SSH-2) RSA 公钥-私钥对。Azure currently supports SSH protocol 2 (SSH-2) RSA public-private key pairs with a minimum length of 2048 bits. 不支持其他密钥格式(如 ED25519 和 ECDSA)。Other key formats such as ED25519 and ECDSA are not supported.

SSH 密钥的使用和优势SSH keys use and benefits

通过指定公钥创建 Azure VM 时,Azure 将公钥(以 .pub 格式)复制到 VM 上的 ~/.ssh/authorized_keys 文件夹。When you create an Azure VM by specifying the public key, Azure copies the public key (in the .pub format) to the ~/.ssh/authorized_keys folder on the VM. ~/.ssh/authorized_keys 中的 SSH 密钥用于在 SSH 连接时质询客户端以匹配相应的私钥。SSH keys in ~/.ssh/authorized_keys are used to challenge the client to match the corresponding private key on an SSH connection. 在使用 SSH 密钥进行身份验证的 Azure Linux VM 中,Azure 会将 SSHD 服务器配置为不允许密码登录,仅允许 SSH 密钥登录。In an Azure Linux VM that uses SSH keys for authentication, Azure configures the SSHD server to not allow password sign-in, only SSH keys. 因此,使用 SSH 密钥创建 Azure Linux VM 可确保 VM 部署的安全,不必进行通常在部署完后需要进行的配置步骤(即在 sshd_config 文件中禁用密码)。Therefore, by creating an Azure Linux VM with SSH keys, you can help secure the VM deployment and save yourself the typical post-deployment configuration step of disabling passwords in the sshd_config file.

如果不希望使用 SSH 密钥,可以将 Linux VM 设置为使用密码身份验证。If you do not wish to use SSH keys, you can set up your Linux VM to use password authentication. 如果 VM 未向 Internet 公开,使用密码可能已足够。If your VM is not exposed to the Internet, using passwords may be sufficient. 但是,仍需要管理每台 Linux VM 的密码和维护正常密码策略和做法(如最小密码长度)并定期进行更新。However, you still need to manage your passwords for each Linux VM and maintain healthy password policies and practices, such as minimum password length and regular updates. 使用 SSH 密钥可降低跨多台 VM 管理单个凭据的复杂性。Using SSH keys reduces the complexity of managing individual credentials across multiple VMs.

使用 ssh-keygen 生成密钥Generate keys with ssh-keygen

若要创建密钥,首选命令是 ssh-keygen,它随 Azure 本地 Shell、macOS 或 Linux 主机中的 OpenSSH 实用程序、用于 Linux 的 Windows 子系统以及其他工具提供。To create the keys, a preferred command is ssh-keygen, which is available with OpenSSH utilities in the Azure local Shell, a macOS or Linux host, the Windows Subsystem for Linux, and other tools. ssh-keygen 会询问一系列问题,然后编写私钥和匹配的公钥。ssh-keygen asks a series of questions and then writes a private key and a matching public key.

SSH 密钥默认保留在 ~/.ssh 目录中。SSH keys are by default kept in the ~/.ssh directory. 如果没有 ~/.ssh 目录,ssh-keygen 命令会使用正确的权限创建一个。If you do not have a ~/.ssh directory, the ssh-keygen command creates it for you with the correct permissions.

基本示例Basic example

以下 ssh-keygen 命令默认在 ~/.ssh 目录中生成 2048 位 SSH RSA 公钥和私钥文件。The following ssh-keygen command generates 2048-bit SSH RSA public and private key files by default in the ~/.ssh directory. 如果当前位置存在 SSH 密钥对,这些文件将被覆盖。If an SSH key pair exists in the current location, those files are overwritten.

ssh-keygen -t rsa -b 2048

详细示例Detailed example

以下示例显示可用于创建 SSH RSA 密钥对的其他命令选项。The following example shows additional command options to create an SSH RSA key pair. 如果当前位置存在 SSH 密钥对,这些文件将被覆盖。If an SSH key pair exists in the current location, those files are overwritten.

ssh-keygen \
    -t rsa \
    -b 4096 \
    -C "azureuser@myserver" \
    -f ~/.ssh/mykeys/myprivatekey \
    -N mypassphrase

命令解释Command explained

ssh-keygen = 用于创建密钥的程序ssh-keygen = the program used to create the keys

-t rsa = 要创建的密钥类型,本例中为 RSA 格式-t rsa = type of key to create, in this case in the RSA format

-b 4096 = 密钥的位数,本例中为 4096-b 4096 = the number of bits in the key, in this case 4096

-C "azureuser@myserver" = 追加到公钥文件末尾以便于识别的注释。-C "azureuser@myserver" = a comment appended to the end of the public key file to easily identify it. 通常以电子邮件地址用作注释,但也可以使用任何最适合你基础结构的事物。Normally an email address is used as the comment, but use whatever works best for your infrastructure.

-f ~/.ssh/mykeys/myprivatekey = 私钥文件的文件名(如果选择不使用默认名称)。-f ~/.ssh/mykeys/myprivatekey = the filename of the private key file, if you choose not to use the default name. 追加了 .pub 的相应公钥文件在相同目录中生成。A corresponding public key file appended with .pub is generated in the same directory. 该目录必须存在。The directory must exist.

-N mypassphrase = 用于访问私钥文件的其他密码。-N mypassphrase = an additional passphrase used to access the private key file.

ssh-keygen 的示例Example of ssh-keygen

ssh-keygen -t rsa -b 2048 -C "azureuser@myserver"
Generating public/private rsa key pair.
Enter file in which to save the key (/home/azureuser/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/azureuser/.ssh/id_rsa.
Your public key has been saved in /home/azureuser/.ssh/id_rsa.pub.
The key fingerprint is:
14:a3:cb:3e:78:ad:25:cc:55:e9:0c:08:e5:d1:a9:08 azureuser@myserver
The keys randomart image is:
+--[ RSA 2048]----+
|        o o. .   |
|      E. = .o    |
|      ..o...     |
|     . o....     |
|      o S =      |
|     . + O       |
|      + = =      |
|       o +       |
|        .        |

保存的密钥文件Saved key files

Enter file in which to save the key (/home/azureuser/.ssh/id_rsa): ~/.ssh/id_rsa

本文中的密钥对名称。The key pair name for this article. 系统默认提供名为 id_rsa 的密钥对,有些工具可能要求私钥文件名为 id_rsa,因此最好使用此密钥对。Having a key pair named id_rsa is the default; some tools might expect the id_rsa private key file name, so having one is a good idea. 目录 ~/.ssh/ 是 SSH 密钥对和 SSH 配置文件的默认位置。The directory ~/.ssh/ is the default location for SSH key pairs and the SSH config file. 如果未使用完全路径指定,则 ssh-keygen 会在当前的工作目录(而非默认的 ~/.ssh)中创建密钥。If not specified with a full path, ssh-keygen creates the keys in the current working directory, not the default ~/.ssh.

~/.ssh 目录列表List of the ~/.ssh directory

ls -al ~/.ssh
-rw------- 1 azureuser staff  1675 Aug 25 18:04 id_rsa
-rw-r--r-- 1 azureuser staff   410 Aug 25 18:04 id_rsa.pub

密钥密码Key passphrase

Enter passphrase (empty for no passphrase):

强烈建议为私钥添加密码 。It is strongly recommended to add a passphrase to your private key. 如果不使用密码来保护密钥文件,任何人只要拥有该文件,就可以用它登录到拥有相应公钥的任何服务器。Without a passphrase to protect the key file, anyone with the file can use it to sign in to any server that has the corresponding public key. 添加密码可提升防护能力以防有人能够访问私钥文件,可让用户有时间更改密钥。Adding a passphrase offers more protection in case someone is able to gain access to your private key file, giving you time to change the keys.

部署期间自动生成密钥Generate keys automatically during deployment

如果使用 Azure CLI 创建 VM,则可以选择通过运行具有 --generate-ssh-keys 选项的 az vm create 命令生成 SSH 公钥和私钥文件。If you use the Azure CLI to create your VM, you can optionally generate SSH public and private key files by running the az vm create command with the --generate-ssh-keys option. 密钥存储在 ~/.ssh 目录中。The keys are stored in the ~/.ssh directory. 请注意,如果该位置已存在密钥,此命令选项不会覆盖这些密钥。Note that this command option does not overwrite keys if they already exist in that location.

部署 VM 时提供 SSH 公钥Provide SSH public key when deploying a VM

若要创建使用 SSH 密钥进行身份验证的 Linux VM,请在使用 Azure 门户、CLI、资源管理器模板或其他方法创建 VM 时提供 SSH 公钥。To create a Linux VM that uses SSH keys for authentication, provide your SSH public key when creating the VM using the Azure portal, CLI, Resource Manager templates, or other methods. 使用门户时,请输入公钥本身。When using the portal, you enter the public key itself. 如果借助现有公钥使用 Azure CLI 创建 VM,请通过运行具有 --ssh-key-value 选项的 az vm create 命令来指定此公钥的值或位置。If you use the Azure CLI to create your VM with an existing public key, specify the value or location of this public key by running the az vm create command with the --ssh-key-value option.

如果不熟悉 SSH 公钥的格式,则可通过运行 cat 来查看公钥(如下所示),注意需将 ~/.ssh/id_rsa.pub 替换成自己的公钥文件位置:If you're not familiar with the format of an SSH public key, you can see your public key by running cat as follows, replacing ~/.ssh/id_rsa.pub with your own public key file location:

cat ~/.ssh/id_rsa.pub

输出如下所示(此处为密文形式):Output is similar to the following (here redacted):

ssh-rsa XXXXXXXXXXc2EAAAADAXABAAABAXC5Am7+fGZ+5zXBGgXS6GUvmsXCLGc7tX7/rViXk3+eShZzaXnt75gUmT1I2f75zFn2hlAIDGKWf4g12KWcZxy81TniUOTjUsVlwPymXUXxESL/UfJKfbdstBhTOdy5EG9rYWA0K43SJmwPhH28BpoLfXXXXXG+/ilsXXXXXKgRLiJ2W19MzXHp8z3Lxw7r9wx3HaVlP4XiFv9U4hGcp8RMI1MP1nNesFlOBpG4pV2bJRBTXNXeY4l6F8WZ3C4kuf8XxOo08mXaTpvZ3T1841altmNTZCcPkXuMrBjYSJbA8npoXAXNwiivyoe3X2KMXXXXXdXXXXXXXXXXCXXXXX/ azureuser@myserver

如果将公钥文件的内容复制粘贴到 Azure 门户或资源管理器模板,请确保不会复制额外的空格或添加额外的换行符。If you copy and paste the contents of the public key file into the Azure portal or a Resource Manager template, make sure you don't copy any additional whitespace or introduce additional line breaks. 例如,如果使用 macOS,则可将公钥文件(默认为 ~/.ssh/id_rsa.pub)通过管道传送到 pbcopy,以便复制内容(也可通过其他 Linux 程序执行此类操作,例如 xclip)。For example, if you use macOS, you can pipe the public key file (by default, ~/.ssh/id_rsa.pub) to pbcopy to copy the contents (there are other Linux programs that do the same thing, such as xclip).

如果更愿意使用多行格式的公钥,则可基于之前创建的公钥在 pem 容器中生成 RFC4716 格式的密钥。If you prefer to use a public key that is in a multiline format, you can generate an RFC4716 formatted key in a pem container from the public key you previously created.

从现有的 SSH 公钥创建 RFC4716 格式的密钥:To create a RFC4716 formatted key from an existing SSH public key:

ssh-keygen \
-f ~/.ssh/id_rsa.pub \
-e \
-m RFC4716 > ~/.ssh/id_ssh2.pem

使用 SSH 客户端将 SSH 连接到 VMSSH to your VM with an SSH client

凭借部署在 Azure VM 上的公钥和本地系统上的私钥,使用 VM 的 IP 地址或 DNS 名称通过 SSH 连接到 VM。With the public key deployed on your Azure VM, and the private key on your local system, SSH to your VM using the IP address or DNS name of your VM. 将以下命令中的 azureusermyvm.chinanorth.cloudapp.chinacloudapi.cn 替换为管理员用户名和完全限定的域名(或 IP 地址):Replace azureuser and myvm.chinanorth.cloudapp.chinacloudapi.cn in the following command with the administrator user name and the fully qualified domain name (or IP address):

ssh azureuser@myvm.chinanorth.cloudapp.chinacloudapi.cn

如果在创建密钥对时提供的是通行短语,则在登录过程中遇到提示时,请输入该通行短语。If you provided a passphrase when you created your key pair, enter the passphrase when prompted during the sign-in process. (服务器添加到 ~/.ssh/known_hosts 文件夹。系统不会要求再次进行连接,除非更改了 Azure VM 上的公钥,或者从 ~/.ssh/known_hosts 中删除了服务器名称。)(The server is added to your ~/.ssh/known_hosts folder, and you won't be asked to connect again until the public key on your Azure VM changes or the server name is removed from ~/.ssh/known_hosts.)

如果 VM 使用的是实时访问策略,则需要先请求访问权限,然后才能连接到 VM。If the VM is using the just-in-time access policy, you need to request access before you can connect to the VM. 有关实时策略的详细信息,请参阅使用实时策略管理虚拟机访问For more information about the just-in-time policy, see Manage virtual machine access using the just in time policy.

使用 ssh-agent 来存储私钥密码Use ssh-agent to store your private key passphrase

为了避免在每次 SSH 登录时键入私钥文件密码,可以使用 ssh-agent 来缓存私钥文件密码。To avoid typing your private key file passphrase with every SSH sign-in, you can use ssh-agent to cache your private key file passphrase. 如果使用 Mac,macOS Keychain 在用户调用 ssh-agent 时会安全存储私钥密码。If you are using a Mac, the macOS Keychain securely stores the private key passphrase when you invoke ssh-agent.

验证并使用 ssh-agentssh-add 将密钥文件的情况通知给 SSH 系统,这样就无需交互使用密码。Verify and use ssh-agent and ssh-add to inform the SSH system about the key files so that you do not need to use the passphrase interactively.

eval "$(ssh-agent -s)"

现在,使用命令 ssh-add 将私钥添加到 ssh-agentNow add the private key to ssh-agent using the command ssh-add.

ssh-add ~/.ssh/id_rsa

私钥密码现在存储在 ssh-agent 中。The private key passphrase is now stored in ssh-agent.

使用 ssh-copy-id 将密钥复制到现有 VMUse ssh-copy-id to copy the key to an existing VM

如果已创建 VM,则可使用如下所示的命令将新的 SSH 公钥安装到 Linux VM:If you have already created a VM, you can install the new SSH public key to your Linux VM with a command similar to the following:

ssh-copy-id -i ~/.ssh/id_rsa.pub azureuser@myserver

创建并配置 SSH 配置文件Create and configure an SSH config file

可创建并配置 SSH 配置文件 (~/.ssh/config),以便加速登录和优化 SSH 客户端行为。You can create and configure an SSH config file (~/.ssh/config) to speed up log-ins and to optimize your SSH client behavior.

以下示例显示一个简单配置,通过此配置,你可以使用默认的 SSH 私钥以用户身份快速登录到特定 VM。The following example shows a simple configuration that you can use to quickly sign in as a user to a specific VM using the default SSH private key.

创建文件Create the file

touch ~/.ssh/config

编辑文件以添加新的 SSH 配置Edit the file to add the new SSH configuration

vim ~/.ssh/config

示例配置Example configuration

添加适用于主机 VM 的配置设置。Add configuration settings appropriate for your host VM.

# Azure Keys
Host myvm
  User azureuser
# ./Azure Keys

可为其他主机添加配置,让每台主机使用其自己的专用密钥对。You can add configurations for additional hosts to enable each to use its own dedicated key pair. 查看 SSH 配置文件获取更多高级配置选项。See SSH config file for more advanced configuration options.

获得 SSH 密钥对并配置 SSH 配置文件后,便可以快速安全地登录到 Linux VM 了。Now that you have an SSH key pair and a configured SSH config file, you are able to sign in to your Linux VM quickly and securely. 运行以下命令时,SSH 从 SSH 配置文件的 Host myvm 块中找到所有设置并加载它们。When you run the following command, SSH locates and loads any settings from the Host myvm block in the SSH config file.

ssh myvm

首次使用 SSH 密钥登录到服务器时,命令会提示用户输入该密钥文件的密码。The first time you sign in to a server using an SSH key, the command prompts you for the passphrase for that key file.

后续步骤Next steps

下一步是使用新 SSH 公钥创建 Azure Linux VM。Next up is to create Azure Linux VMs using the new SSH public key. 使用 SSH 公钥作为登录名创建的 Azure VM 受到的保护优于使用默认登录方法(即密码)创建的 VM。Azure VMs that are created with an SSH public key as the sign-in are better secured than VMs created with the default sign-in method, passwords.