1. 方法1(此方法可能不行)
1、卸载重装一遍ssh服务(自带的不好用)
sudo apt-get remove openssh-server
sudo apt-get install openssh-server
2、编辑sshd_config文件
sudo vim /etc/ssh/sshd_config
在此位置添加如下内容:
PermitRootLogin yes #如果需要用 root 直接登录系统则此处改为 yes
PasswordAuthentication yes #表示使用帐号密码方式登录
为了安全可以把默认端口Port 22改为其它值。
3、启动ssh服务
sudo service ssh start
4、查看WSL IP地址
ip addr show
#或
ifconfig
5、Putty/Xshell中输入WSL IP和端口号(默认:22)连接。本例中既可以用WSL IP 192.168.1.3连接,也可以用本机回路IP 127.0.0.1连接。推荐使用本机回路IP连接,因为不会变,而WSL IP可能随着Win10系统重启而改变。如果使用127.0.0.1无法连接,参看方法2。
6、配置ssh服务随Win10自启动
上边虽然让Xshell连接上了WSL,但是每次Win10重启后,ssh服务不会自动运行,需要打开WSL(例如:Ubuntu-20.04 LTS)终端启动ssh服务,然后再打开Xshell连接,十分麻烦。可以配置让ssh随Win启动而启动。参看:WSL2服务自启动 / WSL ssh 开机自启
2. 方法2(此方法一定可行)
参考网址:
1、先按照方法1操作完1~3步
2、给WSL Ubuntu和Win10添加固定ip
1) 临时生效:
在Windows 10中,以管理员权限运行cmd或Windows Powershell,然后执行以下两个命令:
#在Ubuntu中添加IP地址192.168.50.16,名为eth0:1
wsl -d Ubuntu-20.04 -u root ip addr add 192.168.50.16/24 broadcast 192.168.50.255 dev eth0 label eth0:1
#在Win10中添加IP地址192.168.50.88
netsh interface ip add address "vEthernet (WSL)" 192.168.50.88 255.255.255.0
然后,可用192.168.50.16访问Ubuntu,192.168.50.88访问Win10。
2) 开机自动设置:
①方法1:
a、「开始 > 运行 > 输入:shell:startup」
b、在此启动目录下建立一个wsl_ip.bat脚本,添加如下内容:
@echo off
:: 获取管理员权限
setlocal
set uac=~uac_permission_tmp_%random%
md "%SystemRoot%\system32\%uac%" 2>nul
if %errorlevel%==0 ( rd "%SystemRoot%\system32\%uac%" >nul 2>nul ) else (
echo set uac = CreateObject^("Shell.Application"^)>"%temp%\%uac%.vbs"
echo uac.ShellExecute "%~s0","","","runas",1 >>"%temp%\%uac%.vbs"
echo WScript.Quit >>"%temp%\%uac%.vbs"
"%temp%\%uac%.vbs" /f
del /f /q "%temp%\%uac%.vbs" & exit )
endlocal
:: 给WSL Ubuntu和Win10添加固定ip
wsl -d Ubuntu-20.04 -u root ip addr add 192.168.50.16/24 broadcast 192.168.50.255 dev eth0 label eth0:1
netsh interface ip add address "vEthernet (WSL)" 192.168.50.88 255.255.255.0
因为netsh interface ip add address "vEthernet (WSL)" 192.168.50.88 255.255.255.0这条命令必须以管理员身份运行,所以此脚本的上边一段代码是首先获取管理员运行权限,然后才开始执行设置ip相关的命令;
c、因为此脚本放在启动目录下,所以Win10启动的时候会自动运行此脚本设置ip,就可以用Xshell通过192.168.50.16访问WSL Ubuntu了;
d、此方法缺点:每次开机运行此脚本时都会弹出一个黑窗然后自动关闭,不是很优雅。
②方法2:
通过BatToExeConverter.exe把上述脚本转换成wsl_ip.exe,然后放入启动目录下,开机之后就不会弹出黑窗了,比较完美。
操作步骤:
5、配置ssh开机自启参看方法1的步骤6。
附件:33-S-BatToExeConverter.zip
>> 附件获取地址见右侧博客公告