端口转发

1
2
3
4
5
6
7
8
9
10
11
# 添加端口转发规则
netsh interface portproxy add v4tov4 listenport=$port listenaddress=$addr connectport=$port connectaddress=$remoteport

# 删除端口转发规则
netsh interface portproxy delete v4tov4 listenport=$port listenaddress=$addr

# 清空当前所有的配置规则
netsh interface portproxy reset

eg:
netsh interface portproxy add v4tov4 listenport=主机转发端口 listenaddress=0.0.0.0 connectport=监听端口 connectaddress=监听ip

查看端口转发规则

1
2
3
4
5
6
7
netsh interface portproxy show all

侦听 ipv4: 连接到 ipv4:
地址 端口 地址 端口
--------------- ---------- --------------- ----------
0.0.0.0 40081 192.168.3.180 8080
0.0.0.0 40022 192.168.3.180 10022

脚本样例(proxy-wsl.ps1,powershell下执行)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
$remoteport = bash.exe -c "ifconfig eth0 | grep 'inet '"
$found = $remoteport -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}';
if( $found ){
$remoteport = $matches[0];
} else{
echo "The Script Exited, the ip address of WSL 2 cannot be found";
exit;
}
#[Ports]
#All the ports you want to forward separated by coma
$ports=@(10000,6379,3306,3307,3308,8082,8099);
#[Static ip]
#You can change the addr to your ip config to listen to a specific address
$addr='0.0.0.0';
$ports_a = $ports -join ",";
#Remove Firewall Exception Rules
#iex "Remove-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' ";

#adding Exception Rules for inbound and outbound Rules
#iex "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Outbound -LocalPort $ports_a -Action Allow -Protocol TCP";
#iex "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Inbound -LocalPort $ports_a -Action Allow -Protocol TCP";
for( $i = 0; $i -lt $ports.length; $i++ ){
$port = $ports[$i];
iex "netsh interface portproxy delete v4tov4 listenport=$port listenaddress=$addr";
iex "netsh interface portproxy add v4tov4 listenport=$port listenaddress=$addr connectport=$port connectaddress=$remoteport";
}
netsh interface portproxy show all

rdp保持(有些自动化操作的应用需要保持服务器后台连接)

将此代码保存为.bat文件,并运行即可

1
2
3
for /f "skip=1 tokens=3" %%s in ('query user %USERNAME%') do (
%windir%\System32\tscon.exe %%s /dest:console
)

查找端口占用

1
2
3
netstat -ano|findstr "80"
tasklist|findstr "4"
netsh http show servicestate

windows下 杀死所有nginx进程

1
taskkill /f /t /im nginx.exe

强制杀死某个pid

1
taskkill /pid  [pid] /F