1. SSH基本概念和常用命令
SSH命令的基本格式:
(图片来源网络,侵删)
bash
ssh [选项] [用户@]主机名 [命令]常用选项:
-p 指定端口-i 指定身份文件(私钥)-L 本地端口转发-R 远程端口转发-D 动态端口转发(SOCKS代理)-N 不执行远程命令,常用于端口转发-f 后台运行-v 详细模式(可多个v,如-vvv)示例:
bash
ssh user@example.comssh -p 2222 user@example.comssh -i ~/.ssh/id_rsa user@example.com2. SSH配置文件SSH配置文件分为客户端配置文件(~/.ssh/config)和服务器端配置文件(/etc/ssh/sshd_config)。
客户端配置文件~/.ssh/config 可以配置多个主机,避免每次输入冗长的参数。
示例配置:
text
Host myserver HostName example.com User user Port 2222 IdentityFile ~/.ssh/id_rsa_myserverHost * ServerAliveInterval 60 ServerAliveCountMax 3配置说明:
Host:别名,可以使用通配符HostName:实际的主机名或IPUser:用户名Port:端口IdentityFile:私钥文件路径ServerAliveInterval:客户端每隔多少秒发送一次保活包ServerAliveCountMax:保活包最多发送次数,超过则断开连接服务器端配置文件服务器端配置文件通常位于 /etc/ssh/sshd_config。修改后需要重启SSH服务。
重要配置项:
Port:监听的端口,默认为22PermitRootLogin:是否允许root登录,建议设为noPasswordAuthentication:是否允许密码登录,建议密钥登录,设为noPubkeyAuthentication:是否允许公钥登录AllowUsers:允许登录的用户列表PermitEmptyPasswords:是否允许空密码,必须设为no示例配置:
text
Port 22PermitRootLogin noPasswordAuthentication noPubkeyAuthentication yesAllowUsers user1 user2PermitEmptyPasswords no重启SSH服务(根据系统不同):
bash
# Ubuntu/Debiansudo systemctl restart ssh# CentOS/RHELsudo systemctl restart sshd3. SSH密钥管理生成密钥对bash
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"-t 指定密钥类型(如rsa, ed25519)-b 指定密钥长度-C 注释,通常为邮箱将公钥复制到服务器bash
ssh-copy-id -i ~/.ssh/id_rsa.pub user@example.com或者手动将公钥内容添加到服务器的 ~/.ssh/authorized_keys 文件中。
SSH代理(agent)SSH代理可以避免每次连接都输入私钥密码。
启动代理并添加私钥:
bash
eval "$(ssh-agent -s)"ssh-add ~/.ssh/id_rsa可以配置 ~/.ssh/config 自动使用代理:
text
Host * AddKeysToAgent yes4. SSH连接优化和故障排除优化连接速度在 ~/.ssh/config 中:
text
Host * Compression yes IPQoS throughput保持连接长时间不断开客户端配置:
text
Host * ServerAliveInterval 60 ServerAliveCountMax 3服务器端配置(/etc/ssh/sshd_config):
text
ClientAliveInterval 60ClientAliveCountMax 3调试连接问题使用详细模式:
bash
ssh -vvv user@example.com5. 高级配置端口转发本地端口转发(将远程服务器的端口映射到本地):
bash
ssh -L 8080:localhost:80 user@example.com远程端口转发(将本地端口映射到远程服务器):
bash
ssh -R 8080:localhost:80 user@example.com动态端口转发(创建SOCKS代理):
bash
ssh -D 1080 user@example.com跳板机(通过一台服务器连接另一台服务器)在 ~/.ssh/config 中配置:
text
Host bastion HostName bastion.example.com User user IdentityFile ~/.ssh/id_rsa_bastionHost internal HostName internal.example.com User user IdentityFile ~/.ssh/id_rsa_internal ProxyJump bastion多路复用(复用同一个连接)在 ~/.ssh/config 中:
text
Host * ControlMaster auto ControlPath ~/.ssh/ssh_mux_%h_%p_%r ControlPersist 600这样,第一次连接会创建一个主连接,之后的连接会复用这个连接,加快速度。
总结以上是SSH连接管理与配置的全面介绍。根据实际需求,你可以组合使用这些配置,以提高安全性和效率。
注意:在生产环境中修改SSH配置时,务必保持一个活动的会话,以避免配置错误导致无法登录。
转载请注明来自海坡下载,本文标题:《ssh优化(SSH 连接管理与完全配置)》
京公网安备11000000000001号
京ICP备11000001号
还没有评论,来说两句吧...