Exception: Could not bind to 0.0.0.0:8080 after trying for 30 seconds

Swift服务重启与端口冲突解决方案
本文详细记录了在虚拟机环境下重启Swift服务时遇到的端口冲突问题及解决步骤。通过查找并终止占用8080端口的进程,成功解决了Swift代理服务器无法启动的问题。

 

swift@vincent-virtual-machine /etc/swift $ sudo swift-init main restart
Signal proxy-server  pid: 5688  signal: 15
No proxy-server running
Signal container-server  pid: 5689  signal: 15
Signal container-server  pid: 5690  signal: 15
Signal container-server  pid: 5691  signal: 15
Signal container-server  pid: 5692  signal: 15
Signal account-server  pid: 5693  signal: 15
Signal account-server  pid: 5694  signal: 15
Signal account-server  pid: 5695  signal: 15
Signal account-server  pid: 5696  signal: 15
Signal object-server  pid: 5697  signal: 15
Signal object-server  pid: 5698  signal: 15
Signal object-server  pid: 5699  signal: 15
Signal object-server  pid: 5700  signal: 15
container-server (5689) appears to have stopped
container-server (5690) appears to have stopped
container-server (5691) appears to have stopped
container-server (5692) appears to have stopped
account-server (5696) appears to have stopped
account-server (5694) appears to have stopped
account-server (5695) appears to have stopped
object-server (5698) appears to have stopped
object-server (5700) appears to have stopped
account-server (5693) appears to have stopped
object-server (5697) appears to have stopped
object-server (5699) appears to have stopped
Starting proxy-server...(/etc/swift/proxy-server.conf)
Starting container-server...(/etc/swift/container-server/1.conf)
Starting container-server...(/etc/swift/container-server/2.conf)
Starting container-server...(/etc/swift/container-server/3.conf)
Starting container-server...(/etc/swift/container-server/4.conf)
Starting account-server...(/etc/swift/account-server/1.conf)
Starting account-server...(/etc/swift/account-server/2.conf)
Starting account-server...(/etc/swift/account-server/3.conf)
Starting account-server...(/etc/swift/account-server/4.conf)
Starting object-server...(/etc/swift/object-server/1.conf)
Starting object-server...(/etc/swift/object-server/2.conf)
Starting object-server...(/etc/swift/object-server/3.conf)
Starting object-server...(/etc/swift/object-server/4.conf)
Traceback (most recent call last):
  File "/usr/local/bin/swift-proxy-server", line 10, in <module>
    execfile(__file__)
  File "/home/swift/swift/bin/swift-proxy-server", line 23, in <module>
    sys.exit(run_wsgi(conf_file, 'proxy-server', **options))
  File "/home/swift/swift/swift/common/wsgi.py", line 878, in run_wsgi
    error_msg = strategy.bind_ports()
  File "/home/swift/swift/swift/common/wsgi.py", line 480, in bind_ports
    self.sock = get_socket(self.conf)
  File "/home/swift/swift/swift/common/wsgi.py", line 201, in get_socket
    bind_addr[0], bind_addr[1], bind_timeout))
Exception: Could not bind to 0.0.0.0:8080 after trying for 30 seconds

这种情况很常见,就是端口占用的问题。解决办法:

swift@vincent-virtual-machine /etc/swift $ sudo netstat -ltnp | grep 8080
tcp        0      0 0.0.0.0:8080            0.0.0.0:*               LISTEN      3251/python     
swift@vincent-virtual-machine /etc/swift $ ps -wlp 3251
F S   UID    PID   PPID  C PRI  NI ADDR SZ WCHAN  TTY          TIME CMD
0 S  1001   3251      1  1  80   0 - 22488 poll_s ?        00:01:28 swift-proxy-ser
swift@vincent-virtual-machine /etc/swift $ sudo kill -9 3251
swift@vincent-virtual-machine /etc/swift $ sudo netstat -ltnp | grep 8080
tcp        0      0 0.0.0.0:8080            0.0.0.0:*               LISTEN      3256/python     
swift@vincent-virtual-machine /etc/swift $ ps -wlp 3256
F S   UID    PID   PPID  C PRI  NI ADDR SZ WCHAN  TTY          TIME CMD
1 S  1001   3256      1  0  80   0 - 22950 poll_s ?        00:00:00 swift-proxy-ser
swift@vincent-virtual-machine /etc/swift $ sudo kill -9 3256
swift@vincent-virtual-machine /etc/swift $ sudo netstat -ltnp | grep 8080

 

WARNING: Enabling and disabling experimental features do not take effect until next start of PowerShell. WARNING: Enabling and disabling experimental features do not take effect until next start of PowerShell. [PS7 19:30:16] C:\Users\Administrator\Desktop [master] > # 增强版 Install-Socat 函数(修复下载源失效问题) [PS7 19:30:19] C:\Users\Administrator\Desktop [master] > function Install-Socat { >> param( >> [Parameter(Mandatory = $false)] >> [string]$InstallDrive = "E:", >> >> [Parameter(Mandatory = $false)] >> [string]$InstallDir = "Program Files\Socat" >> ) >> >> # 1. 规范化路径处理 >> $fullPath = [System.IO.Path]::GetFullPath("$InstallDrive\$InstallDir").TrimEnd('\') >> >> # 2. 验证文件系统权限 >> if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { >> Write-Warning "需要管理员权限安装程序" >> return $null >> } >> >> # 3. 检查现有安装 >> $existingPath = (Get-Command socat -ErrorAction SilentlyContinue | >> Select-Object -ExpandProperty Source -First 1) ?? $null >> >> if ($existingPath) { >> Write-Host "已安装于: $existingPath" -ForegroundColor Green >> return $existingPath >> } >> >> # 4. 创建安装目录 >> try { >> if (-not (Test-Path $fullPath)) { >> $null = New-Item -Path $fullPath -ItemType Directory -Force >> } >> } catch { >> Write-Error "创建目录失败: $($_.Exception.Message)" >> return $null >> } >> >> # 5. 文件下载(更新有效的下载源) >> $tempFile = Join-Path $env:TEMP "socat-win64.zip" >> >> # 更新为有效的下载源(GitHub官方镜像) >> $downloadUrls = @( >> "https://github.com/spacemeowx2/socat-windows/releases/download/1.7.4.4/socat_x64.zip", >> "https://github.com/spacemeowx2/socat-windows/releases/download/1.7.4.4/socat_x64.zip", >> "https://github.com/spacemeowx2/socat-windows/releases/download/1.7.4.4/socat_x64.zip" >> ) >> >> $validDownload = $false >> $lastError = $null >> >> # 尝试使用不同方法下载 >> :downloadLoop foreach ($downloadUrl in $downloadUrls) { >> try { >> Write-Host "尝试从 $downloadUrl 下载..." -ForegroundColor Cyan >> >> # 方法1:使用Invoke-WebRequest >> try { >> $ProgressPreference = 'SilentlyContinue' >> Invoke-WebRequest $downloadUrl -OutFile $tempFile -UseBasicParsing -RetryIntervalSec 3 -ErrorAction Stop >> >> # 验证文件大小(最小500KB) >> $fileInfo = Get-Item $tempFile -ErrorAction Stop >> if ($fileInfo.Length -lt 500KB) { >> $lastError = "文件过小 ($([math]::Round($fileInfo.Length/1KB)) KB)" >> Write-Warning "文件校验失败: $lastError" >> continue >> } >> >> $validDownload = $true >> Write-Host "成功下载: $downloadUrl" -ForegroundColor Green >> break downloadLoop >> } catch { >> $lastError = $_.Exception.Message >> Write-Warning "下载失败 (方法1): $lastError" >> } >> >> # 方法2:使用.NET WebClient(备选方法) >> try { >> Write-Host "尝试备选下载方法..." -ForegroundColor Yellow >> $webClient = New-Object System.Net.WebClient >> $webClient.DownloadFile($downloadUrl, $tempFile) >> >> # 验证文件大小 >> $fileInfo = Get-Item $tempFile -ErrorAction Stop >> if ($fileInfo.Length -lt 500KB) { >> $lastError = "文件过小 ($([math]::Round($fileInfo.Length/1KB)) KB)" >> Write-Warning "文件校验失败: $lastError" >> continue >> } >> >> $validDownload = $true >> Write-Host "备选下载方法成功" -ForegroundColor Green >> break downloadLoop >> } catch { >> $lastError = $_.Exception.Message >> Write-Warning "下载失败 (方法2): $lastError" >> } >> } finally { >> $ProgressPreference = 'Continue' >> } >> } >> >> # 如果所有下载源都失败,提供替代安装方案 >> if (-not $validDownload) { >> Write-Error "所有下载源均失败。最后错误: $lastError" >> >> # 替代方案1:使用winget安装(如果可用) >> if (Get-Command winget -ErrorAction SilentlyContinue) { >> Write-Host "尝试使用winget安装socat..." -ForegroundColor Cyan >> try { >> winget install --id spacemeowx2.socat -e >> $wingetPath = (Get-Command socat).Source >> if ($wingetPath) { >> Write-Host "winget安装成功: $wingetPath" -ForegroundColor Green >> return $wingetPath >> } >> } catch { >> Write-Warning "winget安装失败: $($_.Exception.Message)" >> } >> } >> >> # 替代方案2:提供手动安装指南 >> Write-Host @" >> 无法自动下载socat。请手动执行以下操作: >> 1. 从以下链接下载socat: >> https://github.com/spacemeowx2/socat-windows/releases >> 2. 解压到: $fullPath >> 3. 将以下路径添加到系统PATH环境变量: >> $fullPath >> (命令: `$env:Path += `";$fullPath`"`) >> "@ -ForegroundColor Yellow >> >> # 尝试打开下载页面 >> try { >> Start-Process "https://github.com/spacemeowx2/socat-windows/releases" >> } catch { >> Write-Warning "无法打开浏览器" >> } >> >> return $null >> } >> >> # 6. 解压缩 >> try { >> # 使用内置Expand-Archive解压(更可靠) >> Expand-Archive -Path $tempFile -DestinationPath $fullPath -Force >> >> # 查找socat.exe(支持不同目录结构) >> $socatExe = Get-ChildItem -Path $fullPath -Filter "socat.exe" -Recurse | >> Select-Object -First 1 -ExpandProperty FullName >> >> if (-not $socatExe) { >> throw "解压后未找到 socat.exe" >> } >> >> # 如果不在根目录,移动到根目录 >> if ($socatExe -ne (Join-Path $fullPath "socat.exe")) { >> Move-Item -Path $socatExe -Destination $fullPath -Force >> $socatExe = Join-Path $fullPath "socat.exe" >> } >> } catch { >> Write-Error "解压失败: $($_.Exception.Message)" >> return $null >> } >> >> # 7. 环境变量更新 >> $currentPath = [Environment]::GetEnvironmentVariable("Path", "Machine") >> if ($currentPath -notlike "*$fullPath*") { >> $newPath = $currentPath + ";$fullPath" >> [Environment]::SetEnvironmentVariable("Path", $newPath, "Machine") >> } >> >> # 8. 更新当前会话PATH >> $env:Path += ";$fullPath" >> >> # 9. 返回完整路径 >> if (Test-Path $socatExe) { >> Write-Host "socat 安装成功: $socatExe" -ForegroundColor Green >> return $socatExe >> } else { >> Write-Error "安装后文件验证失败" >> return $null >> } >> } [PS7 19:30:23] C:\Users\Administrator\Desktop [master] > [PS7 19:30:23] C:\Users\Administrator\Desktop [master] > # 增强版 New-TcpTunnel 函数(添加超时和重试机制) [PS7 19:30:23] C:\Users\Administrator\Desktop [master] > function New-TcpTunnel { >> param( >> [int]$LocalPort = 8443, >> [string]$RemoteHost = "google.com", >> [int]$RemotePort = 443, >> [string]$SocatPath = $null, >> [int]$TimeoutSeconds = 10 >> ) >> >> # 1. 获取socat路径 >> $socatBinary = if ($SocatPath -and (Test-Path $SocatPath)) { >> $SocatPath >> } else { >> $installedPath = Install-Socat >> if (-not $installedPath) { >> throw "socat安装失败" >> } >> $installedPath >> } >> >> # 2. 创建日志文件 >> $logTime = Get-Date -Format "yyyyMMdd-HHmmss" >> $stdOutFile = Join-Path $env:TEMP "socat-$LocalPort-$logTime-out.log" >> $stdErrFile = Join-Path $env:TEMP "socat-$LocalPort-$logTime-err.log" >> >> # 3. 启动进程 >> try { >> $processArgs = @{ >> FilePath = $socatBinary >> ArgumentList = "TCP-LISTEN:$LocalPort,fork,reuseaddr TCP:$($RemoteHost):$RemotePort" >> NoNewWindow = $true >> RedirectStandardOutput = $stdOutFile >> RedirectStandardError = $stdErrFile >> PassThru = $true >> } >> >> $process = Start-Process @processArgs >> } catch { >> Write-Error "启动socat失败: $($_.Exception.Message)" >> if (Test-Path $stdErrFile) { >> Write-Warning "错误日志内容: $(Get-Content $stdErrFile -Raw)" >> } >> throw >> } >> >> # 4. 验证端口监听(带超时机制) >> $portActive = $false >> $startTime = Get-Date >> while (-not $portActive -and ((Get-Date) - $startTime).TotalSeconds -lt $TimeoutSeconds) { >> Start-Sleep -Seconds 1 >> $portStatus = Get-NetTCPConnection -LocalPort $LocalPort -ErrorAction SilentlyContinue >> $portActive = [bool]$portStatus >> >> # 检查进程是否已退出 >> if ($process.HasExited) { >> if (Test-Path $stdErrFile) { >> $errorContent = Get-Content $stdErrFile -Raw >> Write-Error "进程意外退出: $errorContent" >> } >> throw "socat进程已退出" >> } >> } >> >> if (-not $portActive) { >> Write-Warning "端口 $LocalPort 状态: 未监听" >> if (Test-Path $stdErrFile) { >> Write-Warning "错误日志: $(Get-Content $stdErrFile -Raw)" >> } >> throw "隧道创建失败,端口 $LocalPort 未监听" >> } >> >> # 5. 返回进程信息 >> return [PSCustomObject]@{ >> Process = $process >> Port = $LocalPort >> StdOutLog = $stdOutFile >> StdErrLog = $stdErrFile >> } >> } [PS7 19:30:23] C:\Users\Administrator\Desktop [master] > # 1. 安装socat(使用更新后的源) [PS7 19:30:40] C:\Users\Administrator\Desktop [master] > $socatPath = Install-Socat -InstallDrive "D:" -InstallDir "NetTools" 尝试从 https://github.com/spacemeowx2/socat-windows/releases/download/1.7.4.4/socat_x64.zip 下载... WARNING: 下载失败 (方法1): Response status code does not indicate success: 404 (Not Found). 尝试备选下载方法... WARNING: 下载失败 (方法2): Exception calling "DownloadFile" with "2" argument(s): "The remote server returned an error: (404) Not Found." 尝试从 https://github.com/spacemeowx2/socat-windows/releases/download/1.7.4.4/socat_x64.zip 下载... WARNING: 下载失败 (方法1): Response status code does not indicate success: 404 (Not Found). 尝试备选下载方法... WARNING: 下载失败 (方法2): Exception calling "DownloadFile" with "2" argument(s): "The remote server returned an error: (404) Not Found." 尝试从 https://github.com/spacemeowx2/socat-windows/releases/download/1.7.4.4/socat_x64.zip 下载... WARNING: 下载失败 (方法1): Response status code does not indicate success: 404 (Not Found). 尝试备选下载方法... WARNING: 下载失败 (方法2): Exception calling "DownloadFile" with "2" argument(s): "The remote server returned an error: (404) Not Found." Install-Socat: 所有下载源均失败。最后错误: Exception calling "DownloadFile" with "2" argument(s): "The remote server returned an error: (404) Not Found." 尝试使用winget安装socat... Get-Command: Line | 112 | $wingetPath = (Get-Command socat).Source | ~~~~~~~~~~~~~~~~~ | The term 'socat' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. 无法自动下载socat。请手动执行以下操作: 1. 从以下链接下载socat: https://github.com/spacemeowx2/socat-windows/releases 2. 解压到: D:\NetTools 3. 将以下路径添加到系统PATH环境变量: D:\NetTools (命令: $env:Path += ";D:\NetTools") [PS7 19:31:13] C:\Users\Administrator\Desktop [master] > [PS7 19:31:13] C:\Users\Administrator\Desktop [master] > # 2. 创建到HTTP服务的隧道 [PS7 19:31:13] C:\Users\Administrator\Desktop [master] > $tunnel = New-TcpTunnel -LocalPort 8080 -RemoteHost "example.com" -RemotePort 80 -TimeoutSeconds 15 尝试从 https://github.com/spacemeowx2/socat-windows/releases/download/1.7.4.4/socat_x64.zip 下载... WARNING: 下载失败 (方法1): Response status code does not indicate success: 404 (Not Found). 尝试备选下载方法... WARNING: 下载失败 (方法2): Exception calling "DownloadFile" with "2" argument(s): "The remote server returned an error: (404) Not Found." 尝试从 https://github.com/spacemeowx2/socat-windows/releases/download/1.7.4.4/socat_x64.zip 下载... WARNING: 下载失败 (方法1): Response status code does not indicate success: 404 (Not Found). 尝试备选下载方法... WARNING: 下载失败 (方法2): Exception calling "DownloadFile" with "2" argument(s): "The remote server returned an error: (404) Not Found." 尝试从 https://github.com/spacemeowx2/socat-windows/releases/download/1.7.4.4/socat_x64.zip 下载... WARNING: 下载失败 (方法1): Response status code does not indicate success: 404 (Not Found). 尝试备选下载方法... WARNING: 下载失败 (方法2): Exception calling "DownloadFile" with "2" argument(s): "The remote server returned an error: (404) Not Found." Install-Socat: Line | 14 | $installedPath = Install-Socat | ~~~~~~~~~~~~~ | 所有下载源均失败。最后错误: Exception calling "DownloadFile" with "2" argument(s): "The remote server returned an error: (404) Not Found." 尝试使用winget安装socat... Get-Command: Line | 112 | $wingetPath = (Get-Command socat).Source | ~~~~~~~~~~~~~~~~~ | The term 'socat' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. 无法自动下载socat。请手动执行以下操作: 1. 从以下链接下载socat: https://github.com/spacemeowx2/socat-windows/releases 2. 解压到: E:\Program Files\Socat 3. 将以下路径添加到系统PATH环境变量: E:\Program Files\Socat (命令: $env:Path += ";E:\Program Files\Socat") New-TcpTunnel: 启动socat失败: Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'FilePath'. Specified method is not supported. Start-Process: Line | 37 | $process = Start-Process @processArgs | ~~~~~~~~~~~~ | Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'FilePath'. Specified method is not supported. [PS7 19:31:39] C:\Users\Administrator\Desktop [master] > [PS7 19:31:39] C:\Users\Administrator\Desktop [master] > # 3. 测试隧道 [PS7 19:31:39] C:\Users\Administrator\Desktop [master] > curl -v "http://localhost:$($tunnel.Port)" * Host localhost:80 was resolved. * IPv6: ::1 * IPv4: 127.0.0.1 * Trying [::1]:80... * Trying 127.0.0.1:80... * connect to ::1 port 80 from :: port 54290 failed: Connection refused * connect to 127.0.0.1 port 80 from 0.0.0.0 port 54296 failed: Connection refused * Failed to connect to localhost port 80 after 2215 ms: Could not connect to server * closing connection #0 [PS7 19:31:41] C:\Users\Administrator\Desktop [master] > [PS7 19:31:41] C:\Users\Administrator\Desktop [master] > # 4. 监控日志(实时查看) [PS7 19:31:41] C:\Users\Administrator\Desktop [master] > Get-Content $tunnel.StdErrLog -Wait -Tail 10 Get-Content: Cannot bind argument to parameter 'Path' because it is null. [PS7 19:31:41] C:\Users\Administrator\Desktop [master] > [PS7 19:31:42] C:\Users\Administrator\Desktop [master] > # 5. 使用内置网页测试 [PS7 19:31:42] C:\Users\Administrator\Desktop [master] > Start-Process "http://localhost:$($tunnel.Port)" [PS7 19:31:42] C:\Users\Administrator\Desktop [master] >
最新发布
09-07
WARNING: Enabling and disabling experimental features do not take effect until next start of PowerShell. WARNING: Enabling and disabling experimental features do not take effect until next start of PowerShell. [PS7 19:07:06] C:\Users\Administrator\Desktop [master] > # 增强版 Install-Socat 函数(修复下载和解压问题) [PS7 19:07:12] C:\Users\Administrator\Desktop [master] > function Install-Socat { >> param( >> [Parameter(Mandatory = $false)] >> [string]$InstallDrive = "E:", >> >> [Parameter(Mandatory = $false)] >> [string]$InstallDir = "Program Files\Socat" >> ) >> >> # 1. 规范化路径处理 >> $fullPath = [System.IO.Path]::GetFullPath("$InstallDrive\$InstallDir").TrimEnd('\') >> >> # 2. 验证文件系统权限 >> if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { >> Write-Warning "需要管理员权限安装程序" >> return $null >> } >> >> # 3. 检查现有安装(修复多结果问题) >> $existingPath = (Get-Command socat -ErrorAction SilentlyContinue | >> Select-Object -ExpandProperty Source -First 1) ?? $null >> >> if ($existingPath) { >> Write-Host "已安装于: $existingPath" -ForegroundColor Green >> return $existingPath >> } >> >> # 4. 创建安装目录(带错误处理) >> try { >> if (-not (Test-Path $fullPath)) { >> $null = New-Item -Path $fullPath -ItemType Directory -Force >> } >> } catch { >> Write-Error "创建目录失败: $($_.Exception.Message)" >> return $null >> } >> >> # 5. 文件下载(修复文件名和下载源) >> $tempFile = Join-Path $env:TEMP "socat-win64.zip" >> $downloadUrl = "https://downloads.sourceforge.net/project/unix-utils/socat/1.7.4.4/socat-1.7.4.4-win64.zip" >> >> # 清除旧下载 >> if (Test-Path $tempFile) { >> Remove-Item $tempFile -Force >> } >> >> try { >> # 禁用进度条提高稳定性 >> $ProgressPreference = 'SilentlyContinue' >> Invoke-WebRequest $downloadUrl -OutFile $tempFile -UseBasicParsing -RetryIntervalSec 5 >> } catch { >> Write-Error "下载失败: $($_.Exception.Message)" >> return $null >> } finally { >> $ProgressPreference = 'Continue' >> } >> >> # 6. 解压缩(修复路径处理) >> try { >> # 确保目标目录存在 >> if (-not (Test-Path $fullPath)) { >> $null = New-Item -Path $fullPath -ItemType Directory -Force >> } >> >> # 使用.NET方法解压更可靠 >> Add-Type -AssemblyName System.IO.Compression.FileSystem >> [System.IO.Compression.ZipFile]::ExtractToDirectory($tempFile, $fullPath) >> >> $socatExe = Join-Path $fullPath "socat.exe" >> >> if (-not (Test-Path $socatExe -PathType Leaf)) { >> throw "解压后未找到 socat.exe" >> } >> } catch { >> Write-Error "解压失败: $($_.Exception.Message)" >> return $null >> } >> >> # 7. 环境变量更新(避免重复添加) >> $currentPath = [Environment]::GetEnvironmentVariable("Path", "Machine") >> if ($currentPath -notlike "*$fullPath*") { >> $newPath = $currentPath + ";$fullPath" >> [Environment]::SetEnvironmentVariable("Path", $newPath, "Machine") >> } >> >> # 8. 更新当前会话PATH >> $env:Path += ";$fullPath" >> >> # 9. 返回完整路径(确保字符串类型) >> if (Test-Path $socatExe) { >> return $socatExe.ToString() >> } else { >> Write-Error "安装后文件验证失败" >> return $null >> } >> } [PS7 19:07:13] C:\Users\Administrator\Desktop [master] > [PS7 19:07:13] C:\Users\Administrator\Desktop [master] > # 增强版 New-TcpTunnel 函数(修复类型和路径问题) [PS7 19:07:13] C:\Users\Administrator\Desktop [master] > function New-TcpTunnel { >> param( >> [int]$LocalPort = 8443, >> [string]$RemoteHost = "google.com", >> [int]$RemotePort = 443, >> [string]$SocatPath = $null >> ) >> >> # 1. 获取socat路径(强制转换为字符串) >> $socatBinary = if ($SocatPath -and (Test-Path $SocatPath)) { >> $SocatPath.ToString() >> } else { >> $installedPath = Install-Socat >> if (-not $installedPath) { >> throw "socat安装失败" >> } >> $installedPath.ToString() >> } >> >> # 2. 创建日志文件(确保唯一性) >> $logTime = Get-Date -Format "yyyyMMdd-HHmmss" >> $stdOutFile = Join-Path $env:TEMP "socat-$LocalPort-$logTime-out.log" >> $stdErrFile = Join-Path $env:TEMP "socat-$LocalPort-$logTime-err.log" >> >> # 3. 启动进程(修复路径空格问题) >> $quotedPath = if ($socatBinary -match '\s') { "`"$socatBinary`"" } else { $socatBinary } >> >> try { >> $processArgs = @{ >> FilePath = $socatBinary >> ArgumentList = "TCP-LISTEN:$LocalPort,fork,reuseaddr TCP:$($RemoteHost):$RemotePort" >> NoNewWindow = $true >> RedirectStandardOutput = $stdOutFile >> RedirectStandardError = $stdErrFile >> PassThru = $true >> } >> >> $process = Start-Process @processArgs >> } catch { >> Write-Error "启动socat失败: $($_.Exception.Message)" >> # 显示错误日志 >> if (Test-Path $stdErrFile) { >> Write-Warning "错误日志内容: $(Get-Content $stdErrFile -Raw)" >> } >> throw >> } >> >> # 4. 验证端口监听(增加重试机制) >> $portActive = $false >> 1..5 | ForEach-Object { >> Start-Sleep -Seconds 1 >> if (-not $portActive) { >> $portStatus = Get-NetTCPConnection -LocalPort $LocalPort -ErrorAction SilentlyContinue >> $portActive = [bool]$portStatus >> } >> } >> >> if (-not $portActive) { >> Write-Warning "端口 $LocalPort 状态: 未监听" >> if (Test-Path $stdErrFile) { >> Write-Warning "错误日志: $(Get-Content $stdErrFile -Raw)" >> } >> throw "隧道创建失败,端口 $LocalPort 未监听" >> } >> >> # 5. 返回进程信息(包含日志路径) >> return [PSCustomObject]@{ >> Process = $process >> Port = $LocalPort >> StdOutLog = $stdOutFile >> StdErrLog = $stdErrFile >> } >> } [PS7 19:07:13] C:\Users\Administrator\Desktop [master] > # 1. 安装socat(测试下载和解压) [PS7 19:07:49] C:\Users\Administrator\Desktop [master] > $socatPath = Install-Socat -InstallDrive "E:" -InstallDir "CustomTools\NetUtils" Install-Socat: 解压失败: Exception calling "ExtractToDirectory" with "2" argument(s): "End of Central Directory record could not be found." [PS7 19:07:52] C:\Users\Administrator\Desktop [master] > Test-Path $socatPath Test-Path: Value cannot be null. (Parameter 'The provided Path argument was null or an empty collection.') [PS7 19:07:52] C:\Users\Administrator\Desktop [master] > [PS7 19:07:52] C:\Users\Administrator\Desktop [master] > # 2. 创建隧道(带详细日志) [PS7 19:07:52] C:\Users\Administrator\Desktop [master] > $tunnel = New-TcpTunnel -LocalPort 9080 -RemoteHost "example.com" -RemotePort 80 Install-Socat: Line | 13 | $installedPath = Install-Socat | ~~~~~~~~~~~~~ | 解压失败: Exception calling "ExtractToDirectory" with "2" argument(s): "End of Central Directory record could not be found." Exception: Line | 15 | throw "socat安装失败" | ~~~~~~~~~~~~~~~~~ | socat安装失败 [PS7 19:07:55] C:\Users\Administrator\Desktop [master] > [PS7 19:07:55] C:\Users\Administrator\Desktop [master] > # 3. 监控日志(实时查看) [PS7 19:07:55] C:\Users\Administrator\Desktop [master] > Get-Content $tunnel.StdErrLog -Wait -Tail 10 Get-Content: Cannot bind argument to parameter 'Path' because it is null. [PS7 19:07:55] C:\Users\Administrator\Desktop [master] > [PS7 19:07:55] C:\Users\Administrator\Desktop [master] > # 4. 测试隧道 [PS7 19:07:55] C:\Users\Administrator\Desktop [master] > curl -v "http://localhost:$($tunnel.Port)" * Host localhost:80 was resolved. * IPv6: ::1 * IPv4: 127.0.0.1 * Trying [::1]:80... * Trying 127.0.0.1:80... * connect to ::1 port 80 from :: port 53990 failed: Connection refused * connect to 127.0.0.1 port 80 from 0.0.0.0 port 53991 failed: Connection refused * Failed to connect to localhost port 80 after 2380 ms: Could not connect to server * closing connection #0 [PS7 19:07:58] C:\Users\Administrator\Desktop [master] > function Test-TcpTunnel { >> param( >> [Parameter(Mandatory, ValueFromPipeline)] >> [object]$Tunnel >> ) >> $connection = Get-NetTCPConnection -LocalPort $Tunnel.Port -ErrorAction SilentlyContinue >> $processActive = $Tunnel.Process.HasExited -eq $false >> >> return [PSCustomObject]@{ >> Port = $Tunnel.Port >> IsListening = [bool]$connection >> ProcessActive = $processActive >> ProcessId = $Tunnel.Process.Id >> } >> } [PS7 19:08:04] C:\Users\Administrator\Desktop [master] > [PS7 19:08:04] C:\Users\Administrator\Desktop [master] > # 使用示例 [PS7 19:08:04] C:\Users\Administrator\Desktop [master] > $tunnel | Test-TcpTunnel Test-TcpTunnel: Cannot bind argument to parameter 'Tunnel' because it is null. Get-NetTCPConnection: Line | 6 | … $connection = Get-NetTCPConnection -LocalPort $Tunnel.Port -ErrorA … | ~~~~~~~~~~~~ | Cannot validate argument on parameter 'LocalPort'. The argument is null. Provide a valid value for the argument, and then try running the command again. Port IsListening ProcessActive ProcessId ---- ----------- ------------- --------- False False [PS7 19:08:04] C:\Users\Administrator\Desktop [master] >
09-07
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值