gerardog/gsudo: gsudo
- a sudo for Windows https://github.com/gerardog/gsudo
gsudo is a sudo
equivalent for Windows, with a similar user-experience as the original Unix/Linux sudo. Allows to run commands with elevated permissions, or to elevate the current shell, in the current console window or a new one.
-
Download gsudo in Windows and install. For example, I did portable installation in
%USERPROFILE%\gsudo\
-
Add this script to ~/.bashrc and
Define your dns name in_wsl_ssh_ip_name
variable.
Add location from gsudo and WindowsPowerShell toPATH
environment variable in the script.
#!/bin/bash
# adjust this paths to your environment
export PATH=/mnt/c/Users/your-USERNAME/gsudo/x64/:$PATH
export PATH=/mnt/c/Windows/System32/WindowsPowerShell/v1.0/:$PATH
change_wsl_ssh_ip(){
# define your dns name
_wsl_ssh_ip_name="ubuntu2004.wsl"
# set windows hosts file path
_wslhosts=/mnt/c/Windows/System32/drivers/etc/hosts
_winhosts='C:\Windows\System32\drivers\etc\hosts'
# get wsl real ip and ignore wsl-vpnkit
_wsl_ssh_ip_addr=$(ip -4 addr show "eth0" | grep -oP '(?<=inet\s)\d+(\.\d+){3}' | head -1)
echo "wsl ssh ip addr:[$_wsl_ssh_ip_addr]"
# get current ip from windows hosts
_win_ssh_ip_addr=$(grep -oP "\d+(\.\d+){3}(?=\s*$_wsl_ssh_ip_name)" $_wslhosts)
echo "win ssh ip addr:[$_win_ssh_ip_addr]"
# check if ip exists or diff, then modify
if [[ "$_win_ssh_ip_addr" == "" ]]
then
echo "ssh ip is missing, adding to windows hosts"
gsudo powershell.exe -Command "echo '' '$_wsl_ssh_ip_addr $_wsl_ssh_ip_name' | out-file -encoding ASCII $_winhosts -append"
else
if [[ "$_win_ssh_ip_addr" != "$_wsl_ssh_ip_addr" ]]
then
echo "ssh ip diff, modifying windows hosts"
gsudo powershell.exe -Command "(gc $_winhosts) -replace '$_win_ssh_ip_addr', '$_wsl_ssh_ip_addr' | out-file -encoding ASCII $_winhosts"
else
echo "ssh ip ok"
fi
fi
# resulting windows hosts
echo "now $_wsl_ssh_ip_name 's ip is:"
grep "$_wsl_ssh_ip_name" $_wslhosts
}
# run the function
change_wsl_ssh_ip
- Now shutdown and restart your wsl to check whether the bash script works.
C:\>wsl --shutdown
- Finally check the stdout that the content of the Windows hosts file has changed.
...
123.45.67.89 ubuntu2004.wsl
...