WSL2开启SSH. 按照网上的教程1折腾了一下,据说自带的OpenSSH有问题,需要先卸后装 先配置一下源,看下/etc/os-release: PRETTY_NAME=”Ubuntu 22.04.3 LTS” NAME=”Ubuntu” VERSION_ID=”22.04″ VERSION=”22.04.3 LTS (Jammy Jellyfish)” 配置相应版本的源
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
cat /etc/apt/sources.list # 默认注释了源码仓库,如有需要可自行取消注释 deb https://mirrors.aliyun.com/ubuntu/ jammy main restricted universe multiverse deb-src https://mirrors.aliyun.com/ubuntu/ jammy main restricted universe multiverse deb https://mirrors.aliyun.com/ubuntu/ jammy-security main restricted universe multiverse deb-src https://mirrors.aliyun.com/ubuntu/ jammy-security main restricted universe multiverse deb https://mirrors.aliyun.com/ubuntu/ jammy-updates main restricted universe multiverse deb-src https://mirrors.aliyun.com/ubuntu/ jammy-updates main restricted universe multiverse deb https://mirrors.aliyun.com/ubuntu/ jammy-backports main restricted universe multiverse deb-src https://mirrors.aliyun.com/ubuntu/ jammy-backports main restricted universe multiverse ## Not recommended # deb https://mirrors.aliyun.com/ubuntu/ jammy-proposed main restricted universe multiverse # deb-src https://mirrors.aliyun.com/ubuntu/ jammy-proposed main restricted universe multiverse |
先卸后装openssh
|
sudo apt remove openssh-server sudo apt install openssh-server |
然后修改配置文件 ,这里还是用的密码登录,密钥的差不多处理
|
Port 2222 #设置ssh的端口号, 由于22在windows中有别的用处, 尽量不修改系统的端口号 PermitRootLogin yes # 可以root远程登录 PasswordAuthentication yes # 允许密码验证登录 AllowUsers dancingline # 远程登录时的用户名 |
然后重启服务
|
sudo service ssh --full-restart |
新装的ssh可能不是默认开机自启的,顺便设置了
|
sudo systemctl enable ssh |
同样的,Windows上自带的OpenSSH(如果装了的话)也有问题,就是连不上,需要重新装一个或者用Xshell之类的软件来连接,或者参考2把环境变量里的ssh换成一个正常的(比如git bash自带的那个)。 然后应该可以在Windows上用powershell连接了
|
ssh -P2222 dancingline@localhost # 注意Windows上的ssh命令跟linux略有不同,端口号要用-P参数指定 |
Windows端口转发 上一步只能保证本机连接到WSL,为了能在局域网甚至外网上进行连接,需要进行一些设置,主要分为两步:首先在Windows防火墙设置端口,给刚才设定的SSH端口2222添加入站规则,这部分参考3 ;然后是端口转发,这里有一个比较严重的问题,WSL2每次重启都会换IP,在网上4找了个powershell脚本,摘录如下(运行需要管理员权限)
|
# 找到WSL2的IP $ip = bash.exe -c "ifconfig eth0 | grep 'inet '" $found = $ip -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'; if( $found ) { $ip = $matches[0]; echo "Found IP $ip" # 端口转发,listenport和listenaddress表示监听的端口和IP,connectport和connectaddress表示转发到的端口和IP iex "netsh interface portproxy add v4tov4 listenport=2222 listenaddress=* connectport=2222 connectaddress=$ip"; # 展示已有的 iex "netsh interface portproxy show all;" } else { echo "The ip address of WSL2 cannot be found!"; } # 如果不想用了,下面可以删除端口转发 # netsh interface portproxy delete v4tov4 listenport=2222 protocol=tcp |
可以把这个脚本命名forward_wsl2_port.ps1, 放进Windows计划任务开机自动执行。,具体操作是: 右键点win开始按钮,选择computer management, 选择Computer Management(Local) –> System Tools –> Task Scheduler –> Task Scheduler Library, 在Task Scheduler Library上右键,选择 Read more…