快速切换 wsl 默认用户
wsl 只能同时有一个默认用户。
这个东西很鸡肋,比如 vscode 就只能登录默认用户,所以想要以其他用户身份在 vscode 里连接 wsl 写程序,只能修改默认用户。
手动修改比较麻烦,具体是修改 /etc/wsl.conf 里的 [user] 里的 default 字段为默认用户名,之后通过 windows 的 wsl -t 命令来重启 wsl 。
所以我做了个小脚本可以快速切换用户。
@echo off
REM Licensed under WTFPL
set distro=Ubuntu
set list_file="%~dp0userlist.txt"
set conf_file="%~dp0wsl.conf"
set status_file="%~dp0usernow.txt"
setlocal enabledelayedexpansion
set c=wsl -d %distro% -u root --
goto start
:new
%c% echo ^> /etc/wsl.conf
exit /b 0
:out
%c% echo %1 ^>^> /etc/wsl.conf
exit /b 0
:show_users
echo 请输入你要登录的用户
echo 的前面的编号。
echo.
set /a id=1
for /F usebackq %%i in (%list_file%) do (
echo !id!. %%i
set /a id+=1
)
exit /b 0
:get_user
if "%1" neq "" (
set user=%1
for /F usebackq %%i in (%list_file%) do (
if !user! == %%i (exit /b 0)
)
exit 3
)
call :show_users
set /p userid=
set /a id=1
set user=
for /F usebackq %%i in (%list_file%) do (
if !id! == %userid% (
set user=%%i
)
set /a id+=1
)
if '%user%' == '' (
echo.
echo 傻叉,你编号输错了。
echo 给我重输!
call :get_user
)
exit /b 0
:check_status
if not exist %status_file% exit /b 0
for /F usebackq %%i in (%status_file%) do (
set user_now=%%i
)
if "!user!" == "!user_now!" set cached=1
exit /b 0
:copy_conf
for /F usebackq %%i in (%conf_file%) do (
call :out "%%i"
)
exit /b 0
:end
echo %user%>%status_file%
if "%1" neq "" exit /b 0
echo.
echo 成功,当前是 %user%
pause
exit /b 0
:start
call :get_user %1
call :check_status
if "%cached%" == "" (
call :new
call :copy_conf
call :out [user]
call :out "default=%user%"
wsl -t %distro%
ping -n 2 127.0.0.1>nul
)
call :end %1
使用这个小脚本要求同目录下有一个 userlist.txt 和 wsl.conf 文件。
-
uesrlist.txt的内容是每行一个用户名,也就是需要切换的用户。 -
wsl.conf的内容是不包含[user]字段的剩余的/etc/wsl.conf配置文件,到时候会把[user]字段追加到这个文件里。
一个示例如下:[boot] systemd=true
复制代码到 .bat 文件中,双击即可使用。
也有命令行用法,后跟一个参数表示要切换到的用户(参数不要带引号);如果在 userlist.txt 文件中没找到这个用户的话就什么也不干并返回值 3 。
使用体验还是不错的,我已经试着做到最好了。
博客园原文链接:https://www.cnblogs.com/QiFande/p/18534319,转载请注明。
如果你对本篇文章感兴趣,不如来看看肉丁土豆表的其他文章,说不定也有你喜欢的。
浙公网安备 33010602011771号