1. 设置SSH
安装wsl2 Ubuntu,后无法启动SSH
1.1 出现的错误包括:
a. start-stop-daemon: unable to set gid to 0 (Operation not permitted)
b. * Starting OpenBSD Secure Shell server sshd sshd: no hostkeys available – exiting.
c. * Starting OpenBSD Secure Shell server sshd [ Fail ]
1.2 解决方案
第一步:修改/etc/ssh/sshd_config文件
Port 22 将前面的#去掉,开启22端口
LinstenAddress 0.0.0.0 将前面的#去掉,监听所有的ip
PasswordAuthentication yes 可以使用账号密码进行登录
PermitRootLogin yes 允许root登录
第二步:新增密钥文件
下述命令会在/etc/ssh下新增6个密钥文件,如果该目录下存在此6个文件,直接第三步
cd /etc/ssh
sudo ssh-keygen -t rsa -b 2048 -f /etc/ssh/ssh_host_rsa_key
sudo ssh-keygen -t ecdsa -b 256 -f /etc/ssh/ssh_host_ecdsa_key
sudo ssh-keygen -t ed25519 -b 256 -f /etc/ssh/ssh_host_ed25519_key
第三步:重启ssh
sudo service ssh restart
通过root账户,使用ssh连接Ubuntu,被拒绝
root密码正确也要重置密码,重置密码时,可以是原密码
通过
sudo passwd root
重置密码
2. 固定IP,自动启动SSH
该脚本能够固定ip,同时能够上网,能够启动ssh。
将脚本放入启动文件夹,使得Windows系统开机会自动设置wsl固定ip,开启ssh。
wsl.bat 文件,内容如下,运行该脚本后 UbuntuIp: 172.18.54.10
@ECHO OFF
%1 mshta vbscript:CreateObject("Shell.Application").ShellExecute("cmd.exe","/c ""%~s0"" ::","","runas",1)(window.close)&&exit
setlocal enabledelayedexpansion
wsl --shutdown ubuntu
wsl -u root service ssh start
if !errorlevel! equ 0 (
wsl -u root ip addr | findstr "172.18.54.10" > nul
if !errorlevel! equ 0 (
echo wsl ip has set: 172.18.54.10
) else (
wsl -u root ip addr add 172.18.54.10/16 broadcast 172.18.54.0 dev eth0 label eth0:1
echo set wsl ip success: 172.18.54.10
)
ipconfig | findstr "172.18.54.1" > nul
if !errorlevel! equ 0 (
echo windows ip has set: 172.18.54.1
) else (
netsh interface ip add address "vEthernet (WSL)" 172.18.54.1 255.255.0.0
echo set windows ip success: 172.18.54.1
)
)
ping 172.18.54.10
pause
3. 参考资料
- 允许root ssh登录https://blog.csdn.net/qq_44633541/article/details/122683337
- windows10安装WSL(Ubantu18.04)后无法实现ssh远程链接的解决办法https://blog.csdn.net/weixin_42160053/article/details/119451862
- 给wsl2的ubuntu分配固定IP: https://zhuanlan.zhihu.com/p/515068209