Last active
April 12, 2023 09:17
-
-
Save suzumura-ss/f990cbfb730c13e0a62a3e3894d80a0c to your computer and use it in GitHub Desktop.
Windows Host to WSL proxy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
const { execSync } = require('child_process'); | |
const CMD = process.argv[2]; | |
const PORT = process.argv[3]; | |
const IP = execSync('ifconfig eth0').toString().split(/[\r\n]+/) | |
.filter(line => line.match(/inet /))[0].split(/ +/) | |
.filter(token => token)[1]; | |
function usage () { | |
console.log(` | |
${process.argv[1]} <add|del|show> [port] | |
add port: add portproxy. | |
del port: delete portproxy. | |
show: show portproxy. | |
`); | |
process.exit(1); | |
} | |
function runAsUAC (cmd) { | |
execSync(`powershell.exe -noprofile -noninteractive -command "Start-Process powershell.exe -Verb RunAs -ArgumentList '${cmd}'"`); | |
} | |
function forwardingPorts () { | |
return execSync('netsh.exe interface portproxy show v4tov4').toString() | |
.split(/[\r\n]+/) | |
.map(line => line.split(/ +/).filter(token => token)[1]) | |
.filter(port => parseInt(port)); | |
} | |
switch (CMD) { | |
case 'try': | |
if (!PORT) usage(); | |
if (!forwardingPorts().includes(PORT)) { | |
runAsUAC(`netsh.exe interface portproxy add v4tov4 listenport=${PORT} listenaddress=0.0.0.0 connectport=${PORT} connectaddress=${IP}`); | |
} | |
break; | |
case 'add': | |
if (!PORT) usage(); | |
runAsUAC(`netsh.exe interface portproxy add v4tov4 listenport=${PORT} listenaddress=0.0.0.0 connectport=${PORT} connectaddress=${IP}`); | |
break; | |
case 'del': | |
if (!PORT) usage(); | |
runAsUAC(`netsh.exe interface portproxy delete v4tov4 listenport=${PORT} listenaddress=0.0.0.0`); | |
break; | |
case 'show': | |
console.log(execSync('netsh.exe interface portproxy show v4tov4').toString()); | |
break; | |
default: | |
usage(); | |
break; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment