WSL安装ubuntu问题汇总

755 阅读2分钟

1. Microsoft Store下载Ubuntu异常问题

参考网上资料,修改本地hosts,增加以下映射可解决:
```124.108.22.138 licensing.mp.microsoft.com #UHE_```

2. 修改ubunt安装位置

1. 在powershell中查看安装的子系统:```wsl -l -v```

image.png

2. 关闭ubuntu:```wsl --shutdown```
3. 导出安装的ubuntu:```wsl --export Ubuntu-20.04 E:\ubuntu\ubuntu20.04.tar```
4. 注销之前的子系统:```wsl --unregister Ubuntu-20.04```
5. 导入系统到指定位置:```wsl --import Ubuntu-20.04 E:\ubuntu\ubuntu2004 E:\ubuntu\ubuntu20.04.tar```
(导入成功则会在E:\ubuntu\ubuntu2004目录中看到ext4.vhdx文件)
6. 配置默认登录用户:```ubuntu2004.exe config --default-user xxxxx```

3. 使用ssh工具连接ubuntu问题

将/etc/ssh/sshd_config中PasswordAuthentication对应的值由no修改为yes后执行命令重启ssh
命令:`sudo service ssh restart`
(重启后可以连接,但是如果重启的ubuntu发现需要再次重启ssh才可连接,需要确认原因)

4. 设置WSL系统的资源

在资源管理器中输入%UserProfile%,进入目录后创建配置文件.wslconfig,并添加以下配置:
```
[wsl2]
processors=4
memory=4GB
swap=4GB
```
保存后,使用wsl重新启动ubuntu即可生效

5. 每次重启ubuntu后IP地址变更

思路:通过在ubuntu启动时执行脚本将ip写入到宿主机hosts文件实现在宿主机通过域名来访问变化的ip。
1. 修改hosts文件的属性->安全,修改当前用户的权限为完全控制。
2. 编辑脚本domain.sh
```
#!/usr/bin/bash
# 为 win 设置 wsl host
# win hosts 文件路径
win_hosts_path="/mnt/c/Windows/System32/drivers/etc/hosts"
# 为 wsl2 设置的域名
wsl_domain="yourdomain"
# 获取 wsl2 的 ip
wsl_ip=$(ifconfig eth0 | grep -w inet | awk '{print $2}')
# 判断是否已存在 wsl2 的域名,如果存在则修改,否则追加
if grep -wq "$wsl_domain" $win_hosts_path
then
    # 此处因为权限问题没有直接用 sed 修改 hosts 文件
    win_hosts=$(sed -s "s/.* $wsl_domain/$wsl_ip $wsl_domain/g" $win_hosts_path)
    echo "$win_hosts" > $win_hosts_path
else
    echo "$wsl_ip $wsl_domain" >> $win_hosts_path
fi

# 为 wsl 设置 win host
wsl_hosts_path="/etc/hosts"
win_domain="win"
win_ip=$(cat /etc/resolv.conf | grep "nameserver" | awk '{print $2}')
if grep -wq "$win_domain" $wsl_hosts_path
then
    wsl_hosts=$(sed -s "s/.* $win_domain/$win_ip $win_domain/g" $wsl_hosts_path)
    echo $wsl_hosts > $wsl_hosts_path
else
    echo "$win_ip $win_domain" >> $wsl_hosts_path
fi
```
3. 将该文件上传到ubuntu中(注意编码格式)
4. 将domain.sh复制到/opt/domain目录下,并修改其权限 
```chmod +x domain.sh```
5. 执行./domain.sh,查看windows系统的hosts文件中是否增加了域名和ubuntu中ip的映射关系
6. 设置domain.sh开机自启动:拷贝domain.sh到/etc/profile.d/目录下即可