Gateway-keepaliveForPowershell/proxy-test.ps1

80 lines
2.6 KiB
PowerShell

. $(-Join($(Get-Location).Path, '\logger.ps1'))
. $(-Join($(Get-Location).Path, '\config.ps1'))
function Test-SocksProxy {
param (
[string]$ProxyHost,
[int]$ProxyPort,
[string]$TestHost = "google.com",
[int]$TestPort = 443
)
$result = $false
try {
# check if proxy is working
$result = $(Test-Connection $ProxyHost -Count 1).Status
if(!($result -eq "Success")){
Write-Log -Message "proxy host $ProxyHost is $result"
return $false
}
# create TCP client
$tcpClient = New-Object System.Net.Sockets.TcpClient
$tcpClient.SendTimeout = 1000
$tcpClient.ReceiveTimeout = 1000
$tcpClient.Connect($ProxyHost, $ProxyPort)
# 代理成功连接,开始验证目标地址是否可达
$stream = $tcpClient.GetStream()
# 构建 SOCKS5 握手包 (Initial request)
$handshake = [byte[]](0x05, 0x01, 0x00) # Version 5, 1 method, No auth
$stream.Write($handshake, 0, $handshake.Length)
# 接收服务器响应
$response = New-Object byte[] 2
$stream.Read($response, 0, $response.Length)
if ($response[1] -ne 0x00) {
throw "SOCKS handshake failed. Proxy does not support no-authentication."
}
# 将 TestHost 转换为字节数组
$hostBytes = [System.Text.Encoding]::ASCII.GetBytes($TestHost)
# 构建 SOCKS5 连接请求
$connectRequest = @(
0x05, 0x01, 0x00, 0x03, # Version 5, Connect, Reserved, Domain
[byte]$hostBytes.Length # Domain length
) + $hostBytes + @(
[byte]($TestPort -shr 8), # Port (high byte)
[byte]($TestPort -band 0xFF) # Port (low byte)
)
$stream.Write($connectRequest, 0, $connectRequest.Length)
# 接收连接响应
$connectResponse = New-Object byte[] 10
$stream.Read($connectResponse, 0, $connectResponse.Length)
if ($connectResponse[1] -eq 0x00) {
Write-Log -Message "Proxy is valid and can connect to ${TestHost}:$TestPort."
$result = $true
} else {
throw "SOCKS connection to ${TestHost}:$TestPort failed. Response code: $($connectResponse[1])"
$result = $false
}
} catch {
Write-Log -Message "Proxy test failed: $_"
$result = $false
} finally {
# 关闭连接
if ($stream) { $stream.Dispose() }
if ($tcpClient) { $tcpClient.Close() }
}
return $result
}
# Test-SocksProxy -ProxyHost "192.168.6.2" -ProxyPort 1081