您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# Linux系统中如何用SSH
## 一、SSH基础概念
### 1.1 什么是SSH
SSH(Secure Shell)是一种加密的网络传输协议,用于在不安全的网络中提供安全的远程登录和其他网络服务。它通过加密技术防止信息泄露和中间人攻击,替代了早期的Telnet、rlogin等明文传输协议。
### 1.2 SSH工作原理
SSH采用客户端-服务器架构,工作流程包含:
1. 协议版本协商
2. 密钥交换(Diffie-Hellman算法)
3. 认证阶段(密码/密钥认证)
4. 会话加密通信
### 1.3 主要组件
- ssh:客户端程序
- sshd:服务端守护进程
- ssh-keygen:密钥生成工具
- ssh-copy-id:密钥分发工具
- scp/sftp:安全文件传输工具
## 二、SSH服务配置
### 2.1 安装SSH服务
大多数Linux发行版默认安装OpenSSH:
```bash
# Debian/Ubuntu
sudo apt update && sudo apt install openssh-server
# RHEL/CentOS
sudo yum install openssh-server
# Arch Linux
sudo pacman -S openssh
# 启动服务
sudo systemctl start sshd
# 设置开机自启
sudo systemctl enable sshd
# 检查状态
systemctl status sshd
主配置文件位于/etc/ssh/sshd_config
,重要参数:
Port 22 # 监听端口
PermitRootLogin no # 禁止root直接登录
PasswordAuthentication no # 禁用密码认证
AllowUsers alice bob # 白名单用户
MaxAuthTries 3 # 最大尝试次数
ClientAliveInterval 300 # 连接保持时间
修改后需重启服务:
sudo systemctl restart sshd
ssh username@hostname -p port
示例:
ssh alice@192.168.1.100 -p 2222
参数 | 说明 |
---|---|
-v | 显示调试信息 |
-X | 启用X11转发 |
-L | 本地端口转发 |
-R | 远程端口转发 |
-N | 不执行远程命令 |
首次连接时会提示验证主机密钥:
The authenticity of host 'hostname (192.168.1.100)' can't be established.
ECDSA key fingerprint is SHA256:xxxxxxxx.
Are you sure you want to continue (yes/no/[fingerprint])?
确认后会保存到~/.ssh/known_hosts
中
ssh-keygen -t ed25519 -C "your_email@example.com"
或使用RSA算法:
ssh-keygen -t rsa -b 4096
生成的文件:
- ~/.ssh/id_algorithm
:私钥
- ~/.ssh/id_algorithm.pub
:公钥
方法一:使用ssh-copy-id
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@host
方法二:手动追加到~/.ssh/authorized_keys
cat ~/.ssh/id_ed25519.pub | ssh user@host "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519
编辑~/.ssh/config
实现快捷连接:
Host myserver
HostName 192.168.1.100
User alice
Port 2222
IdentityFile ~/.ssh/myserver_key
ServerAliveInterval 60
之后只需执行:
ssh myserver
ssh -L 8080:internal:80 gateway.example.com
ssh -R 9000:localhost:3000 remote.example.com
sudo apt install libpam-google-authenticator
ChallengeResponseAuthentication yes
AuthenticationMethods publickey,keyboard-interactive
auth required pam_google_authenticator.so
# 仅允许特定IP访问
sudo ufw allow from 192.168.1.0/24 to any port 2222
sudo ufw enable
lastlog
grep 'sshd' /var/log/auth.log
sudo apt install lynis
sudo lynis audit system
ping hostname
telnet hostname 22
ssh -vvv user@hostname
ssh-keygen -R hostname
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
man ssh
, man sshd_config
本文涵盖了SSH从基础到进阶的核心知识点,实际使用时请根据具体环境调整配置。安全无小事,建议在生产环境部署前充分测试所有变更。 “`
注:本文实际约1600字,可根据需要增减内容。Markdown格式允许您轻松调整结构和添加代码示例。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。