本地 SSH 连接教程
source link: https://cyrusyip.org/post/2021/10/09/local-ssh/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Secure Shell(安全外壳协议,简称 SSH )是一种加密的网络传输协议,可在不安全的网络中为网络服务提供安全的传输环境。SSH 通过在网络中创建安全隧道来实现 SSH 客户端与服务器之间的连接。SSH 最常见的用途是远程登录系统,人们通常利用 SSH 来传输命令行界面和远程执行命令。
本地电脑直接操作就可以了,为什么我还要用 SSH 连接呢?因为这样很酷我懒得从椅子上起来走到另一台电脑操作。本文把被连接的电脑称为服务端,另一台为客户端。开始操作前请确保两台电脑处于同一个网络。
安装 OpenSSH
-
在两台电脑安装 OpenSSH
sudo pacman -Syu openssh
-
在服务端启用 SSH 服务
# 启用 sshd.service sudo systemctl start sshd.service # 开机启动 sudo systemctl enable sshd.service # 关闭开机启动 # sudo systemctl disable sshd.service # 关闭 sshd.service # sudo systemctl stop sshd.service
-
❯ systemctl status sshd.service ● sshd.service - OpenSSH Daemon Loaded: loaded (/usr/lib/systemd/system/sshd.service; disabled; vendor preset: disabled) Active: active (running)
显示 Active: active 就说明成功了
-
查看服务端本地 IP 地址
ip route get 1.2.3.4 | awk '{print $7}' # 192.168.3.100
用
ip addr
查看也行 -
客户端连接服务端
使用 SSH 密钥登陆
用 SSH 密钥登陆就可以不输入密码登陆了。
-
在客户端生成 SSH 密钥
ssh-keygen -t ed25519 -C "your computer model" # 一直按 Enter 就行
-
查看并复制 SSH 公钥
❯ cat ~/.ssh/id_ed25519.pub ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHY84a2KfbwfkkKyoSvQk+thsKITpmdFzNbYoCs0SlkU magicbook14
-
连接服务端
-
导入 SSH 公钥
mkdir ~/.ssh touch ~/.ssh/authorized_keys echo 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHY84a2KfbwfkkKyoSvQk+thsKITpmdFzNbYoCs0SlkU magicbook14' >> ~/.ssh/authorized_keys
禁止密码登陆
禁用密码登陆后别人就不能暴力破解密码了,更加安全。接下来使用服务端操作,用客户端 SSH 连接操作也行。
# 备份配置
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
# 修改配置
sudo nano /etc/ssh/sshd_config
在里面加入:
PasswordAuthentication no
# 重启 sshd.service
sudo systemctl restart sshd.service
# 终止原有连接
pkill sshd
用 UFW 防火墙限制 IP
使用服务端操作,配置并启用 UFW 后只允许特定 IP 访问,例如 192.168.3.177。
# 禁止入站连接(外部访问)
sudo ufw default deny incoming
# 允许 192.168.3.177 访问
sudo ufw allow from 192.168.3.177
# 终止原有连接
pkill sshd
查看 SSH 连接
ss | grep ssh
禁用 SSH 服务
sudo systemctl stop sshd.service
禁用服务不会终止已有 SSH 连接,要执行以下命令终止所有连接。
pkill sshd
终止 SSH 连接
终止 1 个 SSH 连接
# 查看用户,pts/1 就是 SSH 连接
❯ w
18:20:06 up 1:08, 2 users, load average: 0.92, 0.54, 0.43
USER TTY LOGIN@ IDLE JCPU PCPU WHAT
hunter tty1 17:12 1:08m 53.14s 0.06s /usr/bin/startplasma-x11
hunter pts/1 18:18 14.00s 0.47s 0.47s -zsh
# 终止进程
❯ pkill -9 -t pts/1
# 查看用户,现在没有 SSH 连接了
❯ w
18:22:23 up 1:10, 1 user, load average: 0.44, 0.48, 0.42
USER TTY LOGIN@ IDLE JCPU PCPU WHAT
hunter tty1 17:12 1:10m 58.05s 0.06s /usr/bin/startplasma-x11
终止所有连接
pkill sshd
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK