When executing an SSH command (such as connecting to a remote server or running commands via SSH), you can specify a particular private SSH key using the -i
option, followed by the path to the private key file. This is helpful if you have multiple SSH keys and need to specify which one to use for a specific connection.
Syntax:
ssh -i /path/to/private-key user@host
/path/to/private-key
: The full path to the private SSH key file you want to use.user
: The username you are logging in with.host
: The hostname or IP address of the remote server.
Example:
Suppose you have a private SSH key stored at ~/.ssh/my_private_key
and you want to use it to connect to a server with the username username
at example.com
.
ssh -i ~/.ssh/my_private_key [email protected]
Additional Considerations:
- Permissions of the Private Key: Make sure the private key has appropriate permissions (e.g.,
600
), which means only the owner can read and write the file:chmod 600 ~/.ssh/my_private_key
- Using SSH with Other Tools (e.g., Git): If you’re using Git or other tools that rely on SSH, you can specify the private key by setting the
SSH_AUTH_SOCK
environment variable or configuring the SSH client to use a specific key in the~/.ssh/config
file.
Example for Git:
If you use Git and want to specify an SSH key for a specific repository, you can set the
GIT_SSH_COMMAND
environment variable:GIT_SSH_COMMAND="ssh -i ~/.ssh/my_private_key" git clone [email protected]:username/repository.git
- Using SSH Config File: You can configure SSH to automatically use a specific key for a given host by adding an entry to your SSH config file (
~/.ssh/config
):Host example.com User username IdentityFile ~/.ssh/my_private_key
With this configuration, you can simply run:
ssh example.com
And it will automatically use the specified key for that host.