SSH 使用
常用命令
ssh-keygen -t ed25519 # 创建 SSH 密钥
ssh user@host # 登录远程主机
ssh-copy-id user@host # 上传密钥
scp src user@host:tgt # 传输文件
说明
scp 只能识别以正斜杠分隔的路径,即便是在 Windows 上也是如此。因此 Shell 路径 /Users/username/.ssh/authorized_keys 相当于 DOS 上的:C:\Users\username\.ssh\authorized_keys
SSH 配置
基本配置
SSH 的配置文件为 ~/.ssh/config
# 全局设置
Host *
# 保活
ServerAliveInterval 120
Host example
HostName example.com
User username
IdentityFile ~/.ssh/id_rsa
Port 2222
# 通过代理连接 github.com:443
Host github.com
HostName ssh.github.com
User git
Port 443
IdentityFile ~/.ssh/id_rsa
ProxyCommand connect -H 127.0.0.1:6152 %h %p
# 登录后自动连接 tmux
Host myserver
User ubuntu
HostName 192.168.1.2
RemoteCommand tmux new -As default
RequestTTY yes
此时登录时可以使用 ssh example 代替 ssh -p 2222 username@example.com
参见:
权限设置
.ssh/:700id_rsa:600id_rsa.pub:644authorized_keys:600known_hosts:644config:600
跳板机
通过跳板机连接到目标服务器:
flowchart LR
A[本地客户端] --> B[跳板机(bastion)]
B --> C[目标服务器(target)]
# 跳板机配置
Host bastion
HostName bastion-host
User bastion-user
IdentityFile ~/.ssh/id_rsa # 本地私钥文件路径
# 目标服务器配置
Host target
HostName target-host
User target-user
ProxyJump bastion
IdentityFile ~/.ssh/id_rsa # 本地私钥文件路径
远程命令
可以设置 SSH 登录后在远程主机上自动执行的命令:
Host myserver
Hostname myserver.local
RequestTTY force
RemoteCommand zsh
参考:Choosing the shell that SSH uses? | Server Fault
Troubleshooting
REMOTE HOST IDENTIFICATION HAS CHANGED
在使用 SSH 连接远程主机时遇到如下警告:
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that a host key has just been changed.
The fingerprint for the ED25519 key sent by the remote host is
SHA256:aFBqZqRp+ZlAldN8EXRkYOE7P2HdQwuI3yh++kW6dbQ.
Please contact your system administrator.
Add correct host key in /Users/username/.ssh/known_hosts to get rid of this message.
Offending ECDSA key in /Users/username/.ssh/known_hosts:6
Password authentication is disabled to avoid man-in-the-middle attacks.
Keyboard-interactive authentication is disabled to avoid man-in-the-middle attacks.
UpdateHostkeys is disabled because the host key is not trusted.
Error: forwarding disabled due to host key check failure
Connection closed by UNKNOWN port 65535
fatal: Could not read from remote repository.
这是一种安全警告,提示你远程主机的 SSH 密钥与本地存储的不匹配,这有可能是中间人攻击造成的。但是对于一般人来说,遇到中间人攻击的可能性不大,这更有可能是连接 SSH 时使用了代理,而每次使用的代理服务器不一样,所以 SSH 客户端看到了不同的代理服务器密钥,从而导致密钥验证失败。
在确保没有安全风险后,可以通过如下设置来绕过密钥验证机制:
Host myserver
StrictHostKeyChecking no
UserKnownHostsFile=/dev/null
如果你使用 Windows,则使用下面的配置:
Host myserver
StrictHostKeyChecking no
UserKnownHostsFile nul
附:SSH 连接的验证机制
当你第一次连接到某个 SSH 服务器时,服务器会发送它的公钥给客户端。客户端会将这个公钥存储在 ~/.ssh/known_hosts 文件中。之后每次连接时,客户端都会比对服务器发来的公钥与存储的公钥是否一致。

浙公网安备 33010602011771号