Blog / Others/ How to Use the ssh-copy-id Command

How to Use the ssh-copy-id Command

ssh-copy-id命令使用方法

Introduction to ssh-copy-id

The ssh-copy-id command is a utility script that copies your local SSH public key to the authorized_keys file on a remote host. This enables passwordless SSH authentication, eliminating the need to enter a password for each login.

Key Features

  • Installs the local user's SSH public key into the remote user's ~/.ssh/authorized_keys file.
  • Automatically sets appropriate permissions on the remote user's home directory, ~/.ssh directory, and ~/.ssh/authorized_keys file (e.g., removing group-write permissions) to meet SSH server strict mode requirements.

Basic Usage

The basic command syntax is:

ssh-copy-id [-i [identity_file]] [user@]machine

Parameter Explanation

  • -i [identity_file]: Specifies the public key file to use. By default, ~/.ssh/id_rsa.pub is used. If this option is provided, the specified file is used and keys from ssh-agent are ignored.
  • [user@]machine: Specifies the remote host's username and address (e.g., [email protected]).

How It Works

ssh-copy-id is essentially a script that connects to the remote server via SSH (requiring a password on first connection) and performs the following:

  1. Checks for available local public keys. It first tries the output of ssh-add -L (keys managed by ssh-agent). If ssh-agent returns nothing or the -i option is used, it uses the specified or default identity file (e.g., id_rsa.pub).
  2. After obtaining one or more public key fingerprints, it appends the key content to the remote server's ~/.ssh/authorized_keys file via the SSH connection.
  3. Adjusts permissions on the remote server's directories and files as needed to ensure SSH functions correctly.

Usage Examples

1. Copy the default public key (~/.ssh/id_rsa.pub) to a remote host:

ssh-copy-id [email protected]

2. Specify a particular public key file:

ssh-copy-id -i ~/.ssh/my_key.pub [email protected]

Important Notes

  • On first run, password authentication must be enabled on the remote SSH server (as a password is required to connect). After successful key setup, it's recommended to disable password authentication in the SSH server configuration for enhanced security.
  • The command automatically handles permission issues, which is convenient for users unfamiliar with SSH directory permission requirements.
  • To view all available options and detailed help, use: ssh-copy-id -h.

Post a Comment

Your email will not be published. Required fields are marked with *.