跳至正文
网络 — SSH 常用命令指南

SSH 常用命令指南

1. 生成 SSH 密钥对

生成 RSA 密钥对 (传统)

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

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

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

指定保存路径和密码

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

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

指定密钥文件连接

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

指定端口和密钥

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

3. SSH 配置文件

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

text
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

使用配置后连接:

bash
ssh myserver

4. 密钥管理

启动 SSH 代理

bash
eval "$(ssh-agent -s)"

添加密钥到 ssh-agent

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

列出已加载的密钥

bash
ssh-add -l

复制公钥到远程服务器

bash
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. 其他实用命令

设置连接保持活跃

bash
ssh -o ServerAliveInterval=60 user@server.com

本地端口转发

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

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

通过跳板机连接

bash
ssh -J jumpuser@jumphost user@targetserver

详细模式连接 (排错用)

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

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

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

相关标签:Linux, Shell, ByAI

博客助手

正在打开博客助手…