SSH 常用命令指南

This article is extracted from the chat log with AI. Please identify it with caution.

1. 生成 SSH 密钥对#

生成 RSA 密钥对 (传统)#

ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
  • -t rsa: 指定密钥类型为 RSA
  • -b 4096: 指定密钥位数为 4096 位
  • -C "comment": 添加注释(通常是邮箱)

生成 ED25519 密钥对 (推荐,更安全高效)#

ssh-keygen -t ed25519 -C "your_email@example.com"

指定保存路径和密码#

ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519_custom -N "passphrase"
  • -f: 指定密钥文件保存路径
  • -N: 指定密码(空密码为"",不推荐)

2. 使用密钥连接远程服务器#

指定密钥文件连接#

ssh -i /path/to/private_key username@hostname
  • -i: 指定私钥文件路径

指定端口和密钥#

ssh -i ~/.ssh/id_ed25519 -p 2222 user@server.com
  • -p: 指定连接端口

3. SSH 配置文件#

配置文件示例 (~/.ssh/config)#

Host myserver
    HostName server.com
    User username
    IdentityFile ~/.ssh/id_ed25519_custom
    Port 2222
    ServerAliveInterval 60
    
Host github
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_ed25519_github

使用配置后连接:

ssh myserver

4. 密钥管理#

启动 SSH 代理#

eval "$(ssh-agent -s)"

添加密钥到 ssh-agent#

ssh-add ~/.ssh/id_ed25519
# 添加带密码的密钥
ssh-add ~/.ssh/id_ed25519_custom
# 添加后1小时后自动移除
ssh-add -t 1h ~/.ssh/id_ed25519_custom

列出已加载的密钥#

ssh-add -l

复制公钥到远程服务器#

ssh-copy-id -i ~/.ssh/id_ed25519.pub user@server.com
# 指定端口
ssh-copy-id -p 2222 -i ~/.ssh/id_ed25519.pub user@server.com

5. 其他实用命令#

设置连接保持活跃#

ssh -o ServerAliveInterval=60 user@server.com

本地端口转发#

ssh -L 8080:localhost:80 user@server.com

将远程服务器的80端口映射到本地8080端口

通过跳板机连接#

ssh -J jumpuser@jumphost user@targetserver

详细模式连接 (排错用)#

ssh -v user@server.com
# 更详细的输出
ssh -vvv user@server.com

限制加密算法 (兼容旧系统)#

ssh -o HostKeyAlgorithms=+ssh-rsa -o PubkeyAcceptedKeyTypes=+ssh-rsa user@oldserver
本文共 576 字,创建于 Dec 30, 2025

相关标签: Linux, Shell, ByAI