소스 검색

迁移到linux-cmd

zhch158_admin 2 달 전
부모
커밋
276d4bb903
10개의 변경된 파일0개의 추가작업 그리고 1677개의 파일을 삭제
  1. 0 233
      zhch/Cloudflare.py
  2. 0 304
      zhch/cloudflare_dns_fix.py
  3. 0 13
      zhch/curl_github.sh
  4. 0 41
      zhch/curl_github_ssh_port.sh
  5. 0 91
      zhch/localtunnel.py
  6. 0 51
      zhch/ngrok_proxy.py
  7. 0 287
      zhch/secure_tunnel.py
  8. 0 74
      zhch/setup_remote_copilot.sh
  9. 0 337
      zhch/setup_remote_copilot_v2.sh
  10. 0 246
      zhch/ssh端口转发.md

+ 0 - 233
zhch/Cloudflare.py

@@ -1,233 +0,0 @@
-"""
-使用 Cloudflare Tunnel 替代 ngrok - 改进版
-"""
-import subprocess
-import time
-import os
-import signal
-import sys
-import re
-from pathlib import Path
-
-def setup_environment():
-    """设置环境变量"""
-    proxy_url = "http://172.16.40.16:7280"
-    env = os.environ.copy()
-    env.update({
-        'HTTP_PROXY': proxy_url,
-        'HTTPS_PROXY': proxy_url,
-        'http_proxy': proxy_url,
-        'https_proxy': proxy_url,
-        # 设置 DNS
-        'GODEBUG': 'netdns=go+1',
-    })
-    return env
-
-def download_cloudflared():
-    """下载 cloudflared"""
-    print("🔄 Downloading cloudflared...")
-    
-    # 确保目录存在
-    bin_dir = Path.home() / "zhch" / "bin"
-    bin_dir.mkdir(exist_ok=True)
-    
-    cloudflared_path = bin_dir / "cloudflared"
-    
-    # 如果已存在,跳过下载
-    if cloudflared_path.exists():
-        print("✅ Cloudflared already exists")
-        return str(cloudflared_path)
-    
-    # 下载命令
-    download_url = "https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64"
-    download_cmd = ['curl', '-L', '-o', str(cloudflared_path), download_url]
-    # 1. 下载 cloudflared
-    download_cmd = ['wget', '-O', str(cloudflared_path), download_url]
-
-    try:
-        env = setup_environment()
-        result = subprocess.run(
-            download_cmd, 
-            check=True, 
-            env=env,
-            capture_output=True,
-            text=True,
-            timeout=300  # 5分钟超时
-        )
-        
-        # 设置执行权限
-        subprocess.run(['chmod', '+x', str(cloudflared_path)], check=True)
-        print("✅ Cloudflared downloaded successfully")
-        return str(cloudflared_path)
-        
-    except subprocess.TimeoutExpired:
-        print("❌ Download timeout - network may be slow")
-        return None
-    except subprocess.CalledProcessError as e:
-        print(f"❌ Download failed: {e}")
-        print(f"STDOUT: {e.stdout}")
-        print(f"STDERR: {e.stderr}")
-        return None
-
-def setup_cloudflare_tunnel(port=8101, timeout=60):
-    """设置 Cloudflare Tunnel"""
-    
-    print(f"🔄 Setting up Cloudflare Tunnel for port {port}...")
-    
-    # 下载 cloudflared
-    cloudflared_path = download_cloudflared()
-    if not cloudflared_path:
-        return None
-    
-    # 准备命令
-    tunnel_cmd = [
-        cloudflared_path, 'tunnel',
-        '--url', f'http://localhost:{port}',
-        '--no-autoupdate',
-        '--logfile', f'{Path.home()}/zhch/logs/cloudflared.log',
-        '--loglevel', 'info'
-    ]
-    
-    print(f"🚀 Starting tunnel: {' '.join(tunnel_cmd)}")
-    
-    try:
-        env = setup_environment()
-        process = subprocess.Popen(
-            tunnel_cmd,
-            stdout=subprocess.PIPE,
-            stderr=subprocess.STDOUT,  # 合并输出
-            text=True,
-            env=env,
-            bufsize=1,  # 行缓冲
-            universal_newlines=True
-        )
-        
-        print("⏳ Waiting for tunnel to start...")
-        
-        # 等待隧道启动并获取 URL
-        start_time = time.time()
-        url_found = False
-        
-        while time.time() - start_time < timeout:
-            if process.poll() is not None:
-                # 进程已终止
-                stdout, _ = process.communicate()
-                print(f"❌ Process terminated early:")
-                print(stdout)
-                return None
-            
-            try:
-                # 非阻塞读取
-                line = process.stdout.readline()
-                if line:
-                    print(f"LOG: {line.strip()}")
-                    
-                    # 查找 trycloudflare.com URL
-                    if 'trycloudflare.com' in line:
-                        # 使用正则表达式提取 URL
-                        url_match = re.search(r'https://[a-zA-Z0-9-]+\.trycloudflare\.com', line)
-                        if url_match:
-                            url = url_match.group(0)
-                            print(f"✅ Tunnel URL found: {url}")
-                            return url, process
-                    
-                    # 检查错误信息
-                    if 'failed to request quick Tunnel' in line:
-                        print("❌ Failed to create tunnel - network connectivity issue")
-                        process.terminate()
-                        return None
-                
-            except Exception as e:
-                print(f"Error reading output: {e}")
-                break
-            
-            time.sleep(0.5)
-        
-        print(f"⏰ Timeout after {timeout} seconds")
-        process.terminate()
-        return None
-        
-    except Exception as e:
-        print(f"❌ Failed to start tunnel: {e}")
-        return None
-
-def test_local_service(port=8101):
-    """测试本地服务是否运行"""
-    import socket
-    try:
-        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-        sock.settimeout(5)
-        result = sock.connect_ex(('localhost', port))
-        sock.close()
-        
-        if result == 0:
-            print(f"✅ Local service is running on port {port}")
-            return True
-        else:
-            print(f"❌ No service found on port {port}")
-            return False
-    except Exception as e:
-        print(f"❌ Error testing local service: {e}")
-        return False
-
-def main():
-    port = 8101
-    
-    print("🌐 Cloudflare Tunnel Setup")
-    print("=" * 50)
-    
-    # 检查本地服务
-    if not test_local_service(port):
-        print(f"⚠️ Warning: No service detected on port {port}")
-        response = input("Continue anyway? (y/N): ")
-        if response.lower() != 'y':
-            return
-    
-    # 设置隧道
-    result = setup_cloudflare_tunnel(port, timeout=120)
-    
-    if result:
-        url, process = result
-        print(f"\n🎉 Success!")
-        print(f"🌐 Your service is now accessible at: {url}")
-        print(f"🔗 Test URL: {url}/docs (if it's a FastAPI service)")
-        print("\nPress Ctrl+C to stop the tunnel")
-        
-        def signal_handler(sig, frame):
-            print("\n🛑 Stopping tunnel...")
-            process.terminate()
-            try:
-                process.wait(timeout=5)
-            except subprocess.TimeoutExpired:
-                process.kill()
-            print("✅ Tunnel stopped")
-            sys.exit(0)
-        
-        signal.signal(signal.SIGINT, signal_handler)
-        
-        try:
-            # 保持运行并显示日志
-            while process.poll() is None:
-                try:
-                    line = process.stdout.readline()
-                    if line:
-                        print(f"TUNNEL: {line.strip()}")
-                except KeyboardInterrupt:
-                    break
-                except Exception as e:
-                    print(f"Error: {e}")
-                    break
-        except Exception as e:
-            print(f"Error: {e}")
-        finally:
-            process.terminate()
-    else:
-        print("\n❌ Failed to setup tunnel")
-        print("\n🔧 Troubleshooting tips:")
-        print("1. Check if your proxy allows connections to api.trycloudflare.com")
-        print("2. Try using a different tunnel service (localtunnel, bore.pub)")
-        print("3. Contact your network administrator about tunnel access")
-        print("4. Use VS Code port forwarding if available")
-
-if __name__ == "__main__":
-    main()

+ 0 - 304
zhch/cloudflare_dns_fix.py

@@ -1,304 +0,0 @@
-"""
-通过修复 DNS 解析问题来使用 Cloudflare Tunnel
-"""
-import subprocess
-import time
-import os
-import signal
-import sys
-import re
-import socket
-from pathlib import Path
-
-def setup_dns_resolution():
-    """设置 DNS 解析"""
-    print("🔧 Setting up DNS resolution...")
-    
-    # 临时 DNS 解析方案
-    hosts_entries = {
-        'api.trycloudflare.com': '104.18.22.223',  # Cloudflare IP
-        'trycloudflare.com': '104.18.22.223'
-    }
-    
-    # 写入临时 hosts 文件
-    temp_hosts = Path.home() / 'zhch' / 'temp_hosts'
-    with open(temp_hosts, 'w') as f:
-        for domain, ip in hosts_entries.items():
-            f.write(f"{ip} {domain}\n")
-    
-    print(f"✅ Created temporary hosts file: {temp_hosts}")
-    return str(temp_hosts)
-
-def test_dns_resolution():
-    """测试 DNS 解析"""
-    test_domains = [
-        'api.trycloudflare.com',
-        'google.com',
-        'cloudflare.com'
-    ]
-    
-    print("🧪 Testing DNS resolution...")
-    for domain in test_domains:
-        try:
-            ip = socket.gethostbyname(domain)
-            print(f"✅ {domain} -> {ip}")
-        except socket.gaierror as e:
-            print(f"❌ {domain} -> Failed: {e}")
-
-def setup_environment_with_dns():
-    """设置包含 DNS 配置的环境变量"""
-    proxy_url = "http://172.16.40.16:7280"
-    env = os.environ.copy()
-    
-    # 基本代理配置
-    env.update({
-        'HTTP_PROXY': proxy_url,
-        'HTTPS_PROXY': proxy_url,
-        'http_proxy': proxy_url,
-        'https_proxy': proxy_url,
-    })
-    
-    # DNS 配置
-    env.update({
-        'GODEBUG': 'netdns=go+1',
-        'GOPROXY': 'direct',
-        'GOSUMDB': 'off',
-    })
-    
-    # 使用公共 DNS
-    env['NAMESERVER'] = '8.8.8.8'
-    
-    return env
-
-def download_cloudflared_direct():
-    """直接下载 cloudflared(绕过 DNS 问题)"""
-    print("🔄 Downloading cloudflared directly...")
-    
-    bin_dir = Path.home() / "zhch" / "bin"
-    bin_dir.mkdir(exist_ok=True, parents=True)
-    cloudflared_path = bin_dir / "cloudflared"
-    
-    if cloudflared_path.exists():
-        print("✅ Cloudflared already exists")
-        return str(cloudflared_path)
-    
-    # 使用直接 IP 地址下载(绕过 DNS)
-    github_ip = "140.82.113.3"  # GitHub IP
-    download_cmd = [
-        'curl', '-L', '-k',  # -k 忽略 SSL 证书验证
-        '-H', f'Host: github.com',
-        f'http://{github_ip}/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64',
-        '-o', str(cloudflared_path)
-    ]
-    
-    try:
-        env = setup_environment_with_dns()
-        result = subprocess.run(
-            download_cmd,
-            check=True,
-            env=env,
-            capture_output=True,
-            text=True,
-            timeout=300
-        )
-        
-        subprocess.run(['chmod', '+x', str(cloudflared_path)], check=True)
-        print("✅ Cloudflared downloaded successfully")
-        return str(cloudflared_path)
-        
-    except Exception as e:
-        print(f"❌ Download failed: {e}")
-        
-        # 备选方案:使用 wget
-        try:
-            wget_cmd = [
-                'wget', '--no-check-certificate',
-                '--header', f'Host: github.com',
-                f'http://{github_ip}/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64',
-                '-O', str(cloudflared_path)
-            ]
-            
-            subprocess.run(wget_cmd, check=True, env=env, timeout=300)
-            subprocess.run(['chmod', '+x', str(cloudflared_path)], check=True)
-            print("✅ Cloudflared downloaded with wget")
-            return str(cloudflared_path)
-            
-        except Exception as e2:
-            print(f"❌ Wget also failed: {e2}")
-            return None
-
-def setup_cloudflare_tunnel_with_dns_fix(port=8101, timeout=120):
-    """使用 DNS 修复的 Cloudflare Tunnel 设置"""
-    
-    print(f"🔄 Setting up Cloudflare Tunnel for port {port} with DNS fix...")
-    
-    # 测试 DNS
-    test_dns_resolution()
-    
-    # 下载 cloudflared
-    cloudflared_path = download_cloudflared_direct()
-    if not cloudflared_path:
-        print("❌ Could not download cloudflared")
-        return None
-    
-    # 创建日志目录
-    log_dir = Path.home() / 'zhch' / 'logs'
-    log_dir.mkdir(exist_ok=True, parents=True)
-    
-    # 准备命令
-    tunnel_cmd = [
-        cloudflared_path, 'tunnel',
-        '--url', f'http://localhost:{port}',
-        '--no-autoupdate',
-        '--logfile', str(log_dir / 'cloudflared.log'),
-        '--loglevel', 'debug'  # 更详细的日志
-    ]
-    
-    print(f"🚀 Starting tunnel: {' '.join(tunnel_cmd)}")
-    
-    try:
-        env = setup_environment_with_dns()
-        
-        # 显示环境配置
-        print("🔧 Environment configuration:")
-        for key in ['HTTP_PROXY', 'HTTPS_PROXY', 'GODEBUG', 'NAMESERVER']:
-            print(f"   {key}: {env.get(key, 'Not set')}")
-        
-        process = subprocess.Popen(
-            tunnel_cmd,
-            stdout=subprocess.PIPE,
-            stderr=subprocess.STDOUT,
-            text=True,
-            env=env,
-            bufsize=1,
-            universal_newlines=True
-        )
-        
-        print("⏳ Waiting for tunnel to start...")
-        start_time = time.time()
-        
-        while time.time() - start_time < timeout:
-            if process.poll() is not None:
-                stdout, _ = process.communicate()
-                print(f"❌ Process terminated early:")
-                print(stdout)
-                return None
-            
-            try:
-                line = process.stdout.readline()
-                if line:
-                    line = line.strip()
-                    print(f"LOG: {line}")
-                    
-                    # 查找成功的隧道 URL
-                    if 'trycloudflare.com' in line:
-                        url_match = re.search(r'https://[a-zA-Z0-9-]+\.trycloudflare\.com', line)
-                        if url_match:
-                            url = url_match.group(0)
-                            print(f"✅ Tunnel URL found: {url}")
-                            return url, process
-                    
-                    # 检查特定错误
-                    if 'dial tcp: lookup api.trycloudflare.com' in line:
-                        print("❌ DNS lookup failed for api.trycloudflare.com")
-                        print("🔧 Trying DNS workaround...")
-                        break
-                    
-                    if 'failed to request quick Tunnel' in line:
-                        print("❌ Failed to create tunnel")
-                        break
-                
-            except Exception as e:
-                print(f"Error reading output: {e}")
-                break
-            
-            time.sleep(0.5)
-        
-        print(f"⏰ Timeout after {timeout} seconds")
-        process.terminate()
-        return None
-        
-    except Exception as e:
-        print(f"❌ Failed to start tunnel: {e}")
-        return None
-
-def main():
-    port = 8101
-    
-    print("🌐 Cloudflare Tunnel Setup with DNS Fix")
-    print("=" * 60)
-    
-    # 检查网络连接
-    print("🔍 Network diagnostics:")
-    
-    # 检查代理连接
-    try:
-        result = subprocess.run(['curl', '-s', '--connect-timeout', '5', 
-                               'http://httpbin.org/ip'], 
-                              capture_output=True, text=True)
-        if result.returncode == 0:
-            print("✅ Proxy connection working")
-        else:
-            print("❌ Proxy connection failed")
-    except:
-        print("❌ Could not test proxy")
-    
-    # 检查本地服务
-    import socket
-    try:
-        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-        sock.settimeout(2)
-        result = sock.connect_ex(('localhost', port))
-        sock.close()
-        
-        if result == 0:
-            print(f"✅ Local service running on port {port}")
-        else:
-            print(f"⚠️ No service on port {port}")
-    except Exception as e:
-        print(f"❌ Error checking local service: {e}")
-    
-    print()
-    
-    # 设置隧道
-    result = setup_cloudflare_tunnel_with_dns_fix(port, timeout=180)
-    
-    if result:
-        url, process = result
-        print(f"\n🎉 Success!")
-        print(f"🌐 Your service is accessible at: {url}")
-        print(f"🔗 Test it: {url}/docs")
-        print("\nPress Ctrl+C to stop")
-        
-        def signal_handler(sig, frame):
-            print("\n🛑 Stopping tunnel...")
-            process.terminate()
-            try:
-                process.wait(timeout=5)
-            except subprocess.TimeoutExpired:
-                process.kill()
-            print("✅ Tunnel stopped")
-            sys.exit(0)
-        
-        signal.signal(signal.SIGINT, signal_handler)
-        
-        try:
-            while process.poll() is None:
-                try:
-                    line = process.stdout.readline()
-                    if line:
-                        print(f"TUNNEL: {line.strip()}")
-                except KeyboardInterrupt:
-                    break
-        finally:
-            process.terminate()
-    else:
-        print("\n❌ All attempts failed")
-        print("\n🔧 Alternative solutions:")
-        print("1. Ask network admin to whitelist *.trycloudflare.com")
-        print("2. Use VS Code built-in port forwarding")
-        print("3. Set up SSH tunnel to external server")
-        print("4. Use internal reverse proxy")
-
-if __name__ == "__main__":
-    main()

+ 0 - 13
zhch/curl_github.sh

@@ -1,13 +0,0 @@
-# 测试基础连接
-curl -I https://api.github.com
-
-# 测试用户信息(验证 token 是否有效)
-curl -H "Authorization: Bearer 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" https://api.github.com/user
-
-# 获取 GitHub token
-gh auth token
-
-# 测试 Copilot API
-curl -H "Authorization: Bearer $(gh auth token)" \
-     -H "Content-Type: application/json" \
-     https://api.github.com/user/copilot/billing

+ 0 - 41
zhch/curl_github_ssh_port.sh

@@ -1,41 +0,0 @@
-#!/bin/bash
-# filepath: /Users/zhch158/workspace/repository.git/dots.ocr/zhch/test_copilot_connection.sh
-
-PROXY_PORT=7280
-
-echo "Testing GitHub Copilot connectivity..."
-
-# 测试基本的 GitHub API 访问
-echo "1. Testing GitHub API..."
-if curl -s --proxy http://localhost:$PROXY_PORT --connect-timeout 10 https://api.github.com/user > /dev/null; then
-    echo "✓ GitHub API accessible"
-else
-    echo "✗ GitHub API not accessible"
-fi
-
-# 测试 Copilot 特定的端点
-echo "2. Testing Copilot proxy service..."
-if curl -s --proxy http://localhost:$PROXY_PORT --connect-timeout 10 https://copilot-proxy.githubusercontent.com > /dev/null; then
-    echo "✓ Copilot proxy service accessible"
-else
-    echo "✗ Copilot proxy service not accessible"
-fi
-
-# 测试用户内容服务
-echo "3. Testing GitHub user content..."
-if curl -s --proxy http://localhost:$PROXY_PORT --connect-timeout 10 https://raw.githubusercontent.com > /dev/null; then
-    echo "✓ GitHub user content accessible"
-else
-    echo "✗ GitHub user content not accessible"
-fi
-
-echo "4. Testing with authentication (if token available)..."
-if [ ! -z "$GITHUB_TOKEN" ]; then
-    if curl -s --proxy http://localhost:$PROXY_PORT -H "Authorization: token $GITHUB_TOKEN" https://api.github.com/user > /dev/null; then
-        echo "✓ GitHub authenticated API accessible"
-    else
-        echo "✗ GitHub authenticated API not accessible"
-    fi
-else
-    echo "ℹ GITHUB_TOKEN not set, skipping authenticated test"
-fi

+ 0 - 91
zhch/localtunnel.py

@@ -1,91 +0,0 @@
-"""
-使用 localtunnel 替代 ngrok
-"""
-import subprocess
-import time
-import re
-
-def setup_localtunnel(port=8101, subdomain=None):
-    """设置 localtunnel"""
-    
-    print("🔄 Setting up localtunnel...")
-    
-    # 1. 安装 localtunnel (需要 Node.js)
-    try:
-        # 检查 npm 是否可用
-        subprocess.run(['npm', '--version'], check=True, capture_output=True)
-        print("✅ npm is available")
-    except subprocess.CalledProcessError:
-        print("❌ npm not found. Please install Node.js first:")
-        print("  curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -")
-        print("  sudo apt-get install -y nodejs")
-        return None
-    
-    # 2. 安装 localtunnel
-    try:
-        env = {
-            'https_proxy': 'http://172.16.40.16:7280',
-            'http_proxy': 'http://172.16.40.16:7280'
-        }
-        subprocess.run(['npm', 'install', '-g', 'localtunnel'], check=True, env=env)
-        print("✅ localtunnel installed")
-    except subprocess.CalledProcessError as e:
-        print(f"❌ Installation failed: {e}")
-        return None
-    
-    # 3. 启动隧道
-    cmd = ['lt', '--port', str(port)]
-    if subdomain:
-        cmd.extend(['--subdomain', subdomain])
-    
-    try:
-        print(f"🚀 Starting tunnel for port {port}...")
-        process = subprocess.Popen(
-            cmd,
-            stdout=subprocess.PIPE,
-            stderr=subprocess.PIPE,
-            text=True,
-            env={
-                'https_proxy': 'http://172.16.40.16:7280',
-                'http_proxy': 'http://172.16.40.16:7280'
-            }
-        )
-        
-        # 等待并获取 URL
-        for _ in range(20):
-            output = process.stdout.readline()
-            if output:
-                print(f"Output: {output.strip()}")
-                # 查找 URL
-                url_match = re.search(r'https://.*?\.loca\.lt', output)
-                if url_match:
-                    url = url_match.group(0)
-                    print(f"✅ Tunnel URL: {url}")
-                    return url, process
-            
-            if process.poll() is not None:
-                stderr = process.stderr.read()
-                print(f"❌ Process failed: {stderr}")
-                return None
-            
-            time.sleep(1)
-        
-        print("⏰ Timeout waiting for tunnel URL")
-        process.terminate()
-        return None
-        
-    except Exception as e:
-        print(f"❌ Failed to start tunnel: {e}")
-        return None
-
-if __name__ == "__main__":
-    result = setup_localtunnel(8101)
-    if result:
-        url, process = result
-        print(f"🌐 Your service is now accessible at: {url}")
-        print("Press Ctrl+C to stop the tunnel")
-        try:
-            process.wait()
-        except KeyboardInterrupt:
-            print("\n🛑 Stopping tunnel...")
-            process.terminate()

+ 0 - 51
zhch/ngrok_proxy.py

@@ -1,51 +0,0 @@
-# 配置代理环境的 ngrok 启动
-import os
-from pyngrok import ngrok, conf
-
-# 配置 ngrok 以使用代理
-ngrok_config = conf.PyngrokConfig(
-    ngrok_path="/usr/local/bin/ngrok",  # 根据实际路径调整
-    config_path="~/.config/ngrok/ngrok.yml"
-)
-
-# 设置代理环境变量(如果配置文件中没有设置)
-os.environ['HTTP_PROXY'] = 'http://172.16.40.16:7280'
-os.environ['HTTPS_PROXY'] = 'http://172.16.40.16:7280'
-
-try:
-    # 连接 ngrok
-    public_url = ngrok.connect(8101, "http", pyngrok_config=ngrok_config, bind_tls=True)
-    print("Public URL:", public_url)
-    print("Web Interface:", public_url.replace("https://", "http://"))
-except Exception as e:
-    print(f"Ngrok connection failed: {e}")
-    print("Trying alternative configuration...")
-    
-    # 备选方案:使用命令行方式
-    import subprocess
-    try:
-        # 使用系统命令启动 ngrok
-        result = subprocess.run([
-            'ngrok', 'http', '8101', 
-            '--config', '~/.config/ngrok/ngrok.yml',
-            '--log', 'stdout'
-        ], capture_output=True, text=True, timeout=30)
-        
-        if result.returncode == 0:
-            print("Ngrok started via command line")
-            # 获取 ngrok API 信息
-            import requests
-            try:
-                resp = requests.get('http://localhost:4040/api/tunnels')
-                tunnels = resp.json()['tunnels']
-                for tunnel in tunnels:
-                    if tunnel['config']['addr'] == 'http://localhost:8101':
-                        print(f"Public URL: {tunnel['public_url']}")
-                        break
-            except:
-                print("Please check ngrok web interface at http://localhost:4040")
-        else:
-            print(f"Command failed: {result.stderr}")
-    except subprocess.TimeoutExpired:
-        print("Ngrok is starting in background...")
-        print("Check http://localhost:4040 for tunnel URLs")

+ 0 - 287
zhch/secure_tunnel.py

@@ -1,287 +0,0 @@
-#!/usr/bin/env python3
-"""
-安全的端口转发 - 只允许特定进程访问
-"""
-import subprocess
-import psutil
-import time
-import os
-import signal
-import sys
-import socket
-import threading
-import json
-from pathlib import Path
-from http.server import HTTPServer, BaseHTTPRequestHandler
-import requests
-
-class SecureProxyHandler(BaseHTTPRequestHandler):
-    """安全代理处理器 - 只允许特定进程访问"""
-    
-    def __init__(self, allowed_pids, target_host, target_port, *args, **kwargs):
-        self.allowed_pids = allowed_pids
-        self.target_host = target_host
-        self.target_port = target_port
-        super().__init__(*args, **kwargs)
-    
-    def is_request_allowed(self):
-        """检查请求是否来自允许的进程"""
-        try:
-            # 获取客户端连接信息
-            client_ip = self.client_address[0]
-            
-            # 如果不是本地连接,直接拒绝
-            if client_ip not in ['127.0.0.1', '::1']:
-                return False, f"Non-local connection from {client_ip}"
-            
-            # 检查当前运行的进程
-            current_pids = set()
-            for proc in psutil.process_iter(['pid', 'name', 'cmdline']):
-                try:
-                    proc_info = proc.info
-                    proc_name = proc_info['name']
-                    cmdline = ' '.join(proc_info['cmdline'] or [])
-                    
-                    # 检查是否是允许的进程
-                    for allowed_process in ['Code', 'github-copilot', 'vllm', 'python']:
-                        if (allowed_process.lower() in proc_name.lower() or 
-                            allowed_process.lower() in cmdline.lower()):
-                            current_pids.add(proc.info['pid'])
-                            
-                except (psutil.NoSuchProcess, psutil.AccessDenied):
-                    continue
-            
-            # 检查是否有允许的进程在运行
-            if not current_pids:
-                return False, "No allowed processes running"
-            
-            return True, "Request allowed"
-            
-        except Exception as e:
-            return False, f"Error checking request: {e}"
-    
-    def proxy_request(self, method='GET', data=None):
-        """代理请求到目标服务器"""
-        allowed, reason = self.is_request_allowed()
-        
-        if not allowed:
-            self.send_error(403, f"Access denied: {reason}")
-            return
-        
-        try:
-            # 构建目标 URL
-            target_url = f"http://{self.target_host}:{self.target_port}{self.path}"
-            
-            # 准备请求头
-            headers = {}
-            for header, value in self.headers.items():
-                if header.lower() not in ['host', 'connection']:
-                    headers[header] = value
-            
-            # 发送请求
-            if method == 'GET':
-                response = requests.get(target_url, headers=headers, timeout=30)
-            elif method == 'POST':
-                response = requests.post(target_url, headers=headers, data=data, timeout=30)
-            else:
-                self.send_error(405, "Method not allowed")
-                return
-            
-            # 返回响应
-            self.send_response(response.status_code)
-            for header, value in response.headers.items():
-                if header.lower() not in ['connection', 'transfer-encoding']:
-                    self.send_header(header, value)
-            self.end_headers()
-            
-            self.wfile.write(response.content)
-            
-            # 记录访问日志
-            self.log_message(f"Proxied {method} {self.path} -> {response.status_code}")
-            
-        except requests.RequestException as e:
-            self.send_error(502, f"Proxy error: {e}")
-        except Exception as e:
-            self.send_error(500, f"Internal error: {e}")
-    
-    def do_GET(self):
-        self.proxy_request('GET')
-    
-    def do_POST(self):
-        content_length = int(self.headers.get('Content-Length', 0))
-        post_data = self.rfile.read(content_length)
-        self.proxy_request('POST', post_data)
-    
-    def log_message(self, format, *args):
-        """自定义日志格式"""
-        timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
-        sys.stderr.write(f"[{timestamp}] {format % args}\n")
-
-class SecureTunnel:
-    def __init__(self):
-        self.config_file = Path.home() / '.secure_tunnel_config.json'
-        self.proxy_server = None
-        self.tunnel_process = None
-        self.proxy_thread = None
-        
-    def load_config(self):
-        """加载配置"""
-        default_config = {
-            "remote_host": "10.192.72.11",
-            "remote_user": "ubuntu",
-            # "ssh_key": str(Path.home() / ".ssh/id_dotsocr_tunnel"),
-            "local_forward_port": 8082,
-            "remote_service_port": 8101,
-            "secure_proxy_port": 7281,  # 安全代理端口
-            "target_proxy_host": "127.0.0.1",
-            "target_proxy_port": 7890,
-            "allowed_processes": ["Code", "github-copilot", "vllm"],
-            "check_interval": 30
-        }
-        
-        if self.config_file.exists():
-            with open(self.config_file, 'r') as f:
-                config = json.load(f)
-                for key, value in default_config.items():
-                    if key not in config:
-                        config[key] = value
-                return config
-        else:
-            with open(self.config_file, 'w') as f:
-                json.dump(default_config, f, indent=2)
-            return default_config
-    
-    def start_secure_proxy(self, config):
-        """启动安全代理服务器"""
-        def create_handler(*args, **kwargs):
-            return SecureProxyHandler(
-                config['allowed_processes'],
-                config['target_proxy_host'],
-                config['target_proxy_port'],
-                *args, **kwargs
-            )
-        
-        try:
-            self.proxy_server = HTTPServer(('127.0.0.1', config['secure_proxy_port']), create_handler)
-            print(f"🔒 Secure proxy started on port {config['secure_proxy_port']}")
-            
-            def run_server():
-                self.proxy_server.serve_forever()
-            
-            self.proxy_thread = threading.Thread(target=run_server, daemon=True)
-            self.proxy_thread.start()
-            return True
-            
-        except Exception as e:
-            print(f"❌ Failed to start secure proxy: {e}")
-            return False
-    
-    def start_tunnel(self, config):
-        """启动 SSH 隧道(使用安全代理端口)"""
-        if self.tunnel_process and self.tunnel_process.poll() is None:
-            return True
-        
-        ssh_cmd = [
-            'ssh',
-            # '-i', config['ssh_key'],
-            '-o', 'ExitOnForwardFailure=yes',
-            '-o', 'ServerAliveInterval=30',
-            '-o', 'ServerAliveCountMax=3',
-            '-L', f"{config['local_forward_port']}:localhost:{config['remote_service_port']}",
-            '-R', f"7281:localhost:{config['secure_proxy_port']}",  # 转发到安全代理
-            '-N',
-            f"{config['remote_user']}@{config['remote_host']}"
-        ]
-        
-        try:
-            print(f"🚀 Starting secure SSH tunnel...")
-            self.tunnel_process = subprocess.Popen(
-                ssh_cmd,
-                stdout=subprocess.PIPE,
-                stderr=subprocess.PIPE,
-                preexec_fn=os.setsid
-            )
-            
-            time.sleep(3)
-            if self.tunnel_process.poll() is None:
-                print("✅ Secure SSH tunnel started")
-                return True
-            else:
-                stdout, stderr = self.tunnel_process.communicate()
-                print(f"❌ SSH tunnel failed: {stderr.decode()}")
-                return False
-                
-        except Exception as e:
-            print(f"❌ Error starting tunnel: {e}")
-            return False
-    
-    def stop_all(self):
-        """停止所有服务"""
-        # 停止代理服务器
-        if self.proxy_server:
-            self.proxy_server.shutdown()
-            self.proxy_server.server_close()
-            print("🔒 Secure proxy stopped")
-        
-        # 停止 SSH 隧道
-        if self.tunnel_process:
-            try:
-                os.killpg(os.getpgid(self.tunnel_process.pid), signal.SIGTERM)
-                self.tunnel_process.wait(timeout=5)
-                print("🚀 SSH tunnel stopped")
-            except:
-                try:
-                    os.killpg(os.getpgid(self.tunnel_process.pid), signal.SIGKILL)
-                except:
-                    pass
-    
-    def run(self):
-        """运行安全隧道"""
-        config = self.load_config()
-        
-        print("🛡️ Starting Secure DotsOCR Tunnel")
-        print("=" * 50)
-        print(f"🔒 Secure proxy port: {config['secure_proxy_port']}")
-        print(f"🎯 Target proxy: {config['target_proxy_host']}:{config['target_proxy_port']}")
-        print(f"✅ Allowed processes: {', '.join(config['allowed_processes'])}")
-        print("=" * 50)
-        
-        # 设置信号处理
-        def signal_handler(signum, frame):
-            print("\n🛑 Shutting down secure tunnel...")
-            self.stop_all()
-            sys.exit(0)
-        
-        signal.signal(signal.SIGTERM, signal_handler)
-        signal.signal(signal.SIGINT, signal_handler)
-        
-        try:
-            # 启动安全代理
-            if not self.start_secure_proxy(config):
-                return 1
-            
-            # 启动 SSH 隧道
-            if not self.start_tunnel(config):
-                return 1
-            
-            print("\n🎉 Secure tunnel is running!")
-            print("📊 Access logs will show below:")
-            print("-" * 50)
-            
-            # 保持运行
-            while True:
-                time.sleep(1)
-                
-        except KeyboardInterrupt:
-            print("\n🛑 Interrupted by user")
-        finally:
-            self.stop_all()
-        
-        return 0
-
-def main():
-    tunnel = SecureTunnel()
-    return tunnel.run()
-
-if __name__ == "__main__":
-    sys.exit(main())

+ 0 - 74
zhch/setup_remote_copilot.sh

@@ -1,74 +0,0 @@
-#!/bin/bash
-
-# 本地网络代理端口(如果有的话)
-LOCAL_PROXY_PORT=7890
-REMOTE_FORWARD_PORT=7281
-REMOTE_HOST="10.192.72.11"
-REMOTE_USER="ubuntu"
-
-echo "Setting up GitHub Copilot connectivity for remote development..."
-
-# 1. 检查本地代理是否可用
-if curl -s --proxy http://localhost:$LOCAL_PROXY_PORT --connect-timeout 5 http://www.google.com > /dev/null; then
-    echo "✓ Local proxy detected on port $LOCAL_PROXY_PORT"
-    PROXY_TARGET="localhost:$LOCAL_PROXY_PORT"
-else
-    echo "ℹ No local proxy detected, using direct connection"
-    PROXY_TARGET="0.0.0.0:80"
-fi
-
-# 2. 建立 SSH 连接with端口转发, 启动 SSH 连接with双向端口转发
-echo "🔗 Establishing SSH connection with port forwarding..."
-echo "   Local :8082 -> Remote :8101 (vLLM service)"
-echo "   Remote:$REMOTE_FORWARD_PORT -> Local :$LOCAL_PROXY_PORT (GitHub Copilot)"
-
-ssh -o "ExitOnForwardFailure=yes" \
-    -o "ServerAliveInterval=60" \
-    -o "ServerAliveCountMax=3" \
-    -L 8111:localhost:8101 \
-    -R $REMOTE_FORWARD_PORT:$PROXY_TARGET \
-    $REMOTE_USER@$REMOTE_HOST \
-    "
-    # 在远程服务器上执行的命令
-    echo 'Configuring remote environment...'
-    
-    # 设置代理环境变量
-    export http_proxy=http://localhost:$REMOTE_FORWARD_PORT
-    export https_proxy=http://localhost:$REMOTE_FORWARD_PORT
-    export HTTP_PROXY=http://localhost:$REMOTE_FORWARD_PORT
-    export HTTPS_PROXY=http://localhost:$REMOTE_FORWARD_PORT
-    
-    # 更新 VSCode 服务器配置
-#     mkdir -p ~/.vscode-server/data/Machine
-#     cat > ~/.vscode-server/data/Machine/settings.json << EOF
-# {
-#     \"http.proxy\": \"http://localhost:$REMOTE_FORWARD_PORT\",
-#     \"http.proxySupport\": \"on\",
-#     \"http.proxyAuthorization\": null,
-#     \"github.copilot.enable\": {
-#         \"*\": true,
-#         \"yaml\": true,
-#         \"plaintext\": true,
-#         \"markdown\": true
-#     },
-#     \"github.copilot.advanced\": {
-#         \"debug.overrideEngine\": \"codex\",
-#         \"debug.useNodeFetcher\": true
-#     }
-# }
-# EOF
-    
-    # 测试网络连接
-    echo 'Testing internet connectivity...'
-    if curl -s --proxy http://localhost:$REMOTE_FORWARD_PORT --connect-timeout 10 https://api.github.com > /dev/null; then
-        echo '✓ GitHub API accessible'
-    else
-        echo '✗ GitHub API not accessible'
-    fi
-    
-    echo 'Setup complete! You can now use GitHub Copilot in VSCode.'
-    echo 'Keep this SSH session alive for Copilot to work.'
-    
-    # 保持会话活跃
-    exec bash
-    "

+ 0 - 337
zhch/setup_remote_copilot_v2.sh

@@ -1,337 +0,0 @@
-#!/bin/bash
-
-# GitHub Copilot 远程开发连接设置脚本
-# 作者: zhch158
-# 版本: 2.2
-
-# ==================== 配置参数 ====================
-LOCAL_PROXY_PORT=7890
-REMOTE_FORWARD_PORT=7281
-REMOTE_HOST="10.192.72.11"
-REMOTE_USER="ubuntu"
-VLLM_PORT=8101
-LOCAL_VLLM_PORT=8111
-
-# ==================== 颜色定义 ====================
-RED='\033[0;31m'
-GREEN='\033[0;32m'
-YELLOW='\033[1;33m'
-BLUE='\033[0;34m'
-PURPLE='\033[0;35m'
-CYAN='\033[0;36m'
-NC='\033[0m' # No Color
-
-# ==================== 工具函数 ====================
-log_info() {
-    echo -e "${BLUE}ℹ${NC} $1"
-}
-
-log_success() {
-    echo -e "${GREEN}✅${NC} $1"
-}
-
-log_warning() {
-    echo -e "${YELLOW}⚠${NC} $1"
-}
-
-log_error() {
-    echo -e "${RED}❌${NC} $1"
-}
-
-log_step() {
-    echo -e "${PURPLE}🔧${NC} $1"
-}
-
-# ==================== 检查函数 ====================
-check_dependencies() {
-    log_step "检查依赖工具..."
-    
-    local missing_tools=()
-    
-    # 检查必需工具
-    for tool in ssh curl netstat; do
-        if ! command -v $tool >/dev/null 2>&1; then
-            missing_tools+=($tool)
-        fi
-    done
-    
-    if [ ${#missing_tools[@]} -ne 0 ]; then
-        log_error "缺少必需工具: ${missing_tools[*]}"
-        log_info "请安装缺少的工具后重试"
-        exit 1
-    fi
-    
-    log_success "所有依赖工具已安装"
-}
-
-check_local_proxy() {
-    log_step "检查本地代理服务..."
-    
-    # 检查端口是否监听
-    if netstat -tln 2>/dev/null | grep -q ":$LOCAL_PROXY_PORT "; then
-        log_info "发现本地端口 $LOCAL_PROXY_PORT 正在监听"
-    else
-        log_warning "本地端口 $LOCAL_PROXY_PORT 未在监听"
-    fi
-    
-    # 测试代理连接
-    if curl -s --proxy http://localhost:$LOCAL_PROXY_PORT --connect-timeout 5 http://www.google.com > /dev/null 2>&1; then
-        log_success "本地代理 (端口 $LOCAL_PROXY_PORT) 工作正常"
-        return 0
-    else
-        log_warning "本地代理不可用,将使用直接连接"
-        return 1
-    fi
-}
-
-check_remote_connectivity() {
-    log_step "检查远程主机连接..."
-    
-    if ssh -o ConnectTimeout=10 -o BatchMode=yes $REMOTE_USER@$REMOTE_HOST "echo 'SSH连接成功'" 2>/dev/null; then
-        log_success "远程主机 $REMOTE_HOST 连接正常"
-        return 0
-    else
-        log_error "无法连接到远程主机 $REMOTE_HOST"
-        log_info "请检查网络连接和SSH配置"
-        return 1
-    fi
-}
-
-# ==================== 主要功能 ====================
-setup_ssh_tunnel() {
-    local proxy_target
-    
-    if check_local_proxy; then
-        proxy_target="localhost:$LOCAL_PROXY_PORT"
-    else
-        # 如果没有本地代理,使用一个无效的目标让连接失败
-        log_warning "没有可用的本地代理,GitHub Copilot可能无法正常工作"
-        proxy_target="127.0.0.1:1"  # 故意使用一个无效端口
-    fi
-    
-    log_step "建立SSH隧道连接..."
-    echo -e "${CYAN}📡 端口转发配置:${NC}"
-    echo "   本地 :$LOCAL_VLLM_PORT -> 远程 :$VLLM_PORT (vLLM 服务)"
-    echo "   远程 :$REMOTE_FORWARD_PORT -> 本地 :$LOCAL_PROXY_PORT (代理服务)"
-    echo ""
-    
-    # SSH 连接参数优化,减少警告
-    ssh \
-        -o "ExitOnForwardFailure=yes" \
-        -o "ServerAliveInterval=60" \
-        -o "ServerAliveCountMax=3" \
-        -o "TCPKeepAlive=yes" \
-        -o "Compression=yes" \
-        -o "StrictHostKeyChecking=no" \
-        -o "UserKnownHostsFile=/dev/null" \
-        -o "LogLevel=ERROR" \
-        -L $LOCAL_VLLM_PORT:localhost:$VLLM_PORT \
-        -R $REMOTE_FORWARD_PORT:$proxy_target \
-        $REMOTE_USER@$REMOTE_HOST \
-        "$(cat << 'REMOTE_SCRIPT'
-#!/bin/bash
-
-# 远程执行脚本
-REMOTE_FORWARD_PORT=7281
-SHELL_DIR=$HOME/zhch/shell
-mkdir -p $SHELL_DIR
-
-# 颜色定义
-RED='\033[0;31m'
-GREEN='\033[0;32m'
-YELLOW='\033[1;33m'
-BLUE='\033[0;34m'
-PURPLE='\033[0;35m'
-CYAN='\033[0;36m'
-NC='\033[0m'
-
-log_info() { echo -e "${BLUE}ℹ${NC} $1"; }
-log_success() { echo -e "${GREEN}✅${NC} $1"; }
-log_warning() { echo -e "${YELLOW}⚠${NC} $1"; }
-log_error() { echo -e "${RED}❌${NC} $1"; }
-log_step() { echo -e "${PURPLE}🔧${NC} $1"; }
-
-echo -e "${CYAN}🚀 在远程主机上配置 GitHub Copilot 环境${NC}"
-echo "=================================================="
-
-# 备份原有代理设置
-log_step "备份原有代理设置..."
-env | grep -i proxy > $SHELL_DIR/copilot_proxy_backup 2>/dev/null || true
-
-# 显示当前环境
-log_info "当前代理环境:"
-env | grep -i proxy | sed 's/^/   /' || echo "   (无代理设置)"
-
-# 清除现有代理设置
-log_step "清除现有代理设置..."
-unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY
-unset ftp_proxy FTP_PROXY no_proxy NO_PROXY
-
-# 设置新的代理环境变量
-log_step "设置隧道代理环境变量..."
-export http_proxy=http://localhost:$REMOTE_FORWARD_PORT
-export https_proxy=http://localhost:$REMOTE_FORWARD_PORT
-export HTTP_PROXY=http://localhost:$REMOTE_FORWARD_PORT
-export HTTPS_PROXY=http://localhost:$REMOTE_FORWARD_PORT
-export no_proxy=localhost,127.0.0.1,10.192.72.11,172.16.0.0/12
-export NO_PROXY=localhost,127.0.0.1,10.192.72.11,172.16.0.0/12
-
-log_success "代理环境变量已设置"
-echo "   http_proxy=http://localhost:$REMOTE_FORWARD_PORT"
-echo "   https_proxy=http://localhost:$REMOTE_FORWARD_PORT"
-
-# 检查端口监听状态
-log_step "检查端口转发状态..."
-sleep 2  # 等待端口转发建立
-
-if netstat -tln 2>/dev/null | grep -q "127.0.0.1:$REMOTE_FORWARD_PORT " || ss -tln 2>/dev/null | grep -q ":$REMOTE_FORWARD_PORT "; then
-    log_success "端口 $REMOTE_FORWARD_PORT 正在监听"
-else
-    log_warning "端口 $REMOTE_FORWARD_PORT 未检测到监听状态"
-fi
-
-# 测试网络连接
-log_step "测试网络连接..."
-
-echo "🧪 连接测试结果:"
-
-# 测试隧道代理
-if curl -s --proxy http://localhost:$REMOTE_FORWARD_PORT --connect-timeout 10 http://httpbin.org/ip > /dev/null 2>&1; then
-    log_success "隧道代理连接正常"
-else
-    log_warning "隧道代理连接失败"
-fi
-
-# 测试 GitHub API
-if curl -s --connect-timeout 10 https://api.github.com/user > /dev/null 2>&1; then
-    log_success "GitHub API 可访问"
-else
-    log_error "GitHub API 不可访问"
-fi
-
-# 测试 GitHub Copilot 服务
-if curl -s --connect-timeout 10 https://copilot-proxy.githubusercontent.com/ > /dev/null 2>&1; then
-    log_success "GitHub Copilot 服务可访问"
-else
-    log_warning "GitHub Copilot 服务访问可能有问题"
-fi
-
-# 显示环境信息
-echo ""
-echo -e "${CYAN}📊 环境信息摘要${NC}"
-echo "=================================================="
-echo "🔗 SSH 隧道: 已建立"
-echo "🌐 代理端口: localhost:$REMOTE_FORWARD_PORT"
-echo "📝 备份文件: $SHELL_DIR/copilot_proxy_backup"
-echo "💻 主机名: $(hostname)"
-echo "👤 用户: $(whoami)"
-echo "📅 时间: $(date)"
-
-# 创建快速测试脚本
-cat > $SHELL_DIR/test_copilot_connection.sh << 'TEST_EOF'
-#!/bin/bash
-echo "🧪 GitHub Copilot 连接测试"
-echo "=========================="
-
-# 测试代理连接
-if curl -s --connect-timeout 5 https://api.github.com > /dev/null; then
-    echo "✅ GitHub API: 可访问"
-else
-    echo "❌ GitHub API: 不可访问"
-fi
-
-if curl -s --connect-timeout 5 https://copilot-proxy.githubusercontent.com/ > /dev/null; then
-    echo "✅ Copilot Service: 可访问"
-else
-    echo "❌ Copilot Service: 不可访问"
-fi
-
-echo ""
-echo "📊 当前代理设置:"
-env | grep -i proxy | sort
-TEST_EOF
-
-chmod +x $SHELL_DIR/test_copilot_connection.sh
-
-# 创建代理恢复脚本
-cat > $SHELL_DIR/restore_proxy.sh << 'RESTORE_EOF'
-#!/bin/bash
-echo "🔄 恢复原有代理设置..."
-
-if [ -f $SHELL_DIR/copilot_proxy_backup ]; then
-    source $SHELL_DIR/copilot_proxy_backup
-    echo "✅ 代理设置已恢复"
-    echo "📊 当前代理设置:"
-    env | grep -i proxy | sort
-else
-    echo "❌ 未找到备份文件"
-fi
-RESTORE_EOF
-
-chmod +x $SHELL_DIR/restore_proxy.sh
-
-echo ""
-echo -e "${GREEN}🎉 GitHub Copilot 环境配置完成!${NC}"
-echo "=================================================="
-echo "📝 使用说明:"
-echo "   • 保持此 SSH 会话活跃以维持 Copilot 功能"
-echo "   • 在 VS Code 中正常使用 GitHub Copilot"
-echo "   • 运行 $SHELL_DIR/test_copilot_connection.sh 测试连接"
-echo "   • 运行 $SHELL_DIR/restore_proxy.sh 恢复原有代理设置"
-echo ""
-echo "🔧 调试命令:"
-echo "   netstat -tln | grep 127.0.0.1:$REMOTE_FORWARD_PORT  # 检查端口"
-echo "   curl -v https://api.github.com             # 测试 GitHub API"
-echo "   env | grep -i proxy                        # 查看代理设置"
-echo ""
-
-# 设置退出时恢复代理的陷阱
-trap 'echo "🔄 会话结束,恢复代理设置..."; source $SHELL_DIR/copilot_proxy_backup 2>/dev/null || true; echo "✅ 代理设置已恢复"' EXIT
-
-log_info "保持 SSH 会话活跃中... (按 Ctrl+C 退出)"
-
-# 保持会话活跃并定期显示状态
-while true; do
-    sleep 60
-    echo "📡 $(date '+%H:%M:%S'): SSH 隧道活跃,Copilot 代理运行中"
-    
-    # 检查代理连接状态
-    if netstat -an 2>/dev/null | grep -q "127.0.0.1:$REMOTE_FORWARD_PORT.*ESTABLISHED"; then
-        echo "🔥 检测到活跃的代理连接"
-    fi
-done
-
-'REMOTE_SCRIPT'
-)"
-}
-
-# ==================== 清理函数 ====================
-cleanup() {
-    log_info "正在清理..."
-    # 这里可以添加清理逻辑
-}
-
-# ==================== 主程序 ====================
-main() {
-    echo -e "${CYAN}🚀 GitHub Copilot 远程开发连接设置${NC}"
-    echo "=================================================="
-    echo "📅 $(date)"
-    echo "🖥️  本机: $(hostname)"
-    echo "🌐 远程: $REMOTE_HOST"
-    echo ""
-    
-    # 设置退出陷阱
-    trap cleanup EXIT
-    
-    # 执行检查
-    check_dependencies
-    check_remote_connectivity || exit 1
-    
-    # 设置隧道
-    setup_ssh_tunnel
-}
-
-# ==================== 脚本入口 ====================
-if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
-    main "$@"
-fi

+ 0 - 246
zhch/ssh端口转发.md

@@ -1,246 +0,0 @@
-# 0. 程序,配置
-```bash
-# 在本机(192.168.247.197)上启动
-./setup_remote_copilot.sh
-```
-### 远端主机(10.192.72.11)的vscode中配置--远程[SSH:10.192.72.11]
-```json
-{
-    "http.proxyStrictSSL": false,
-    "http.systemCertificates": false,
-    "Lingma.HttpProxySettings": "manual",
-    "Lingma.HttpProxyConfigurationURL": "http://172.16.40.16:7280",
-    "http.proxy": "http://localhost:7281",
-    "http.proxySupport": "on",
-    "github.copilot.enable": {
-        "*": true,
-        "yaml": true,
-        "plaintext": true,
-        "markdown": true
-    },
-    "github.copilot.advanced": {
-        "debug.overrideEngine": "codex",
-        "debug.useNodeFetcher": true
-    },
-    "http.proxyAuthorization": null
-}
-```
-
-# 1. 正向端口转发
-### 在mac本机(192.168.247.197)上运行
-```
-ssh -L 8082:localhost:8101 10.192.72.11 
-```
-就可以在本机(192.168.247.197)通过访问 `http://localhost:8082` 来访问远程服务了。
-
-# 2. 双向端口转发
-```
-ssh -o "ExitOnForwardFailure=yes"  -o "ServerAliveInterval=60" -o "ServerAliveCountMax=3" -L 8082:localhost:8101 -R 7281:localhost:7890 ubuntu@10.192.72.11
-
-ssh  -o ExitOnForwardFailure=yes -o ServerAliveInterval=30 -o ServerAliveCountMax=3 -L 8082:localhost:8101 -R 7281:localhost:7890 -N ubuntu@10.192.72.11
-```
-这个 SSH 命令用于建立隧道连接,让您可以从本地访问远程服务器上的服务,同时为远程服务器提供代理访问。这正好可以解决您 ngrok 连接问题。
-
-让我详细解释这个命令的各个参数:
-
-## SSH 隧道命令解析
-
- 连接选项 (`-o`)
-- **`ExitOnForwardFailure=yes`**: 如果端口转发失败,立即退出 SSH 连接
-- **`ServerAliveInterval=60`**: 每 60 秒发送一次保活信号
-- **`ServerAliveCountMax=3`**: 最多发送 3 次保活信号无响应后断开连接
-
-### 端口转发
-- **`-L 8082:localhost:8101`**: 本地端口转发
-  - 将本地的 8082 端口转发到远程服务器的 8101 端口
-  - 访问 `localhost:8082` 相当于访问远程服务器的 `localhost:8101`
-
-- **`-R 7281:localhost:7890`**: 远程端口转发
-  - 将远程服务器的 7281 端口转发到本地的 7890 端口
-  - 远程服务器访问 `localhost:7281` 相当于访问您本地的 `localhost:7890`
-- **`-R 参数的完整格式`**
-```
--R [bind_address:]port:host:hostport
-```
-  - bind_address: 远程主机上的监听地址(可选), 不指定时默认是localhost
-  - port: 远程主机上的监听端口
-  - host: 本机的目标地址
-  - hostport: 本机的目标端口
-
-
-```
-ssh -i /Users/zhch158/.ssh/id_dotsocr_tunnel -o ExitOnForwardFailure=yes -o ServerAliveInterval=30 -o ServerAliveCountMax=3 -L 8082:localhost:8101 -R 7281:localhost:7281 -N ubuntu@10.192.72.11
-```
-这个 SSH 命令是您安全隧道方案的核心,让我详细解释每个参数的作用:
-
-## 🔐 SSH 安全隧道命令解析
-
-```bash
-ssh -i /Users/zhch158/.ssh/id_dotsocr_tunnel \
-    -o ExitOnForwardFailure=yes \
-    -o ServerAliveInterval=30 \
-    -o ServerAliveCountMax=3 \
-    -L 8082:localhost:8101 \
-    -R 7281:localhost:7281 \
-    -N ubuntu@10.192.72.11
-```
-
-### 📋 参数详解
-
-#### 🔑 身份认证
-- **`-i /Users/zhch158/.ssh/id_dotsocr_tunnel`**
-  - 使用专用的 SSH 私钥文件
-  - 这是您为 DotsOCR 隧道专门生成的密钥,确保独占访问
-  - 可以不指定,使用默认的 `~/.ssh/id_rsa` 或其他默认密钥
-
-#### ⚙️ 连接选项 (`-o`)
-- **`ExitOnForwardFailure=yes`**
-  - 如果任何端口转发失败,立即终止 SSH 连接
-  - 确保隧道完整性,避免部分失效的连接
-
-- **`ServerAliveInterval=30`**
-  - 每 30 秒发送一次保活信号到服务器
-  - 防止长时间无活动导致连接被防火墙断开
-
-- **`ServerAliveCountMax=3`**
-  - 最多发送 3 次保活信号无响应后断开
-  - 总计 90 秒无响应后自动断开(30秒 × 3次)
-
-#### 🌐 端口转发配置
-
-##### 正向转发 (`-L`)
-```
--L 8082:localhost:8101
-```
-- **作用**: 本地端口转发
-- **含义**: 
-  - 本机的 `localhost:8082` → 远程服务器的 `localhost:8101`
-  - 在您的 Mac 上访问 `http://localhost:8082` 就相当于访问远程服务器的 vLLM 服务
-
-##### 反向转发 (`-R`)
-```
--R 7281:localhost:7281
-```
-- **作用**: 远程端口转发(关键的安全改进)
-- **含义**:
-  - 远程服务器的 `localhost:7281` → 您本机的 `localhost:7281`
-  - 注意:这里转发到 7281 端口,而不是直接的 7890
-
-#### 🚫 执行选项
-- **`-N`**
-  - 不执行远程命令,只建立端口转发
-  - 纯隧道模式,不会打开远程 shell
-
-- **`ubuntu@10.192.72.11`**
-  - 连接到远程服务器的用户和地址
-
-## 🛡️ 安全架构图解
-
-```
-您的 Mac (192.168.247.197)          远程服务器 (10.192.72.11)
-┌─────────────────────────┐         ┌─────────────────────────┐
-│                         │         │                         │
-│  🌐 浏览器              │         │  🤖 vLLM 服务           │
-│  localhost:8082 ◄───────┼─────────┼──► localhost:8101       │
-│                         │   SSH   │                         │
-│  🔒 安全代理服务器      │  隧道   │  其他用户进程           │
-│  localhost:7281 ◄───────┼─────────┼──► localhost:7281       │
-│         │               │         │         │               │
-│         ▼               │         │         ▼               │
-│  🎯 本地代理            │         │    ❌ 被拒绝           │
-│  localhost:7890         │         │   (安全检查失败)        │
-│  (Clash/V2Ray等)        │         │                         │
-└─────────────────────────┘         └─────────────────────────┘
-```
-
-## SSH非交互式执行的环境隔离
-  - 通过 SSH 执行远程脚本时,默认使用最小化的环境
-  - 不会加载用户的 shell 配置文件(如 .bashrc, .profile)
-  - 系统级的代理环境变量可能不会被继承
-
-
-## 🔧 与您的 secure_tunnel.py 的配合
-
-### 1. 配置文件对应关系
-
-```python
-# secure_tunnel.py 中的配置
-{
-    "local_forward_port": 8082,      # 对应 -L 8082:localhost:8101
-    "remote_service_port": 8101,     # 远程 vLLM 服务端口
-    "secure_proxy_port": 7281,       # 对应 -R 7281:localhost:7281
-    "target_proxy_host": "127.0.0.1",
-    "target_proxy_port": 7890        # 最终的代理目标
-}
-```
-
-### 2. 安全流程
-
-1. **远程服务器上的进程**访问 `localhost:7281`
-2. **SSH 隧道**将请求转发到您本机的 `localhost:7281`
-3. **安全代理服务器**(secure_tunnel.py)在 7281 端口监听
-4. **进程检查**:验证请求是否来自允许的进程(VS Code、Copilot)
-5. **条件转发**:只有合法请求才转发到 `localhost:7890`(您的真实代理)
-
-## 🚀 使用场景示例
-
-### 场景 1: 您使用 VS Code + Copilot
-```bash
-# 远程服务器上的 vLLM 进程请求代理
-curl http://localhost:7281/some-api
-
-# 流程:
-# 1. 请求到达远程服务器的 7281 端口
-# 2. SSH 隧道转发到您本机的 7281 端口
-# 3. 安全代理检测到 VS Code 进程运行 ✅
-# 4. 转发请求到本机的 7890 端口(真实代理)
-# 5. 返回响应
-```
-
-### 场景 2: 其他用户尝试访问
-```bash
-# 其他用户在远程服务器执行
-curl http://localhost:7281/some-api
-
-# 流程:
-# 1. 请求到达远程服务器的 7281 端口
-# 2. SSH 隧道转发到您本机的 7281 端口
-# 3. 安全代理检测:没有 VS Code 进程 ❌
-# 4. 返回 HTTP 403 Forbidden
-# 5. 记录访问日志
-```
-
-## 🎯 总结
-
-这个命令实现了一个**双向安全隧道**:
-
-1. **正向隧道**:让您在本机访问远程的 vLLM 服务
-2. **反向隧道**:为远程服务器提供受控的代理访问
-3. **安全控制**:通过中间代理层实现访问权限控制
-4. **进程绑定**:只有特定进程才能使用代理服务
-
-
-🔍 验证监听状态
-连接到远程主机后,可以检查端口监听状态:
-```bash
-# 检查监听端口
-netstat -tlnp | grep 7281
-# 或
-ss -tlnp | grep 7281
-
-# 应该看到类似输出:
-# tcp 0 0 127.0.0.1:7281 0.0.0.0:* LISTEN  # localhost 监听
-# tcp 0 0 0.0.0.0:7281   0.0.0.0:* LISTEN  # 所有接口监听
-# tcp 0 0 10.192.72.11:7281 0.0.0.0:* LISTEN  # 特定IP监听
-```
-
-## 杀死主机上指定用户ubuntu的所有vscode进程
-```bash
-sudo pkill -u ubuntu -f vscode
-```
-
-🛡️ 安全建议
-默认使用 localhost:最安全,只有本机用户可访问
-避免使用 0.0.0.0:除非确实需要外部访问
-使用特定 IP:如果需要内网访问,指定具体的内网 IP
-监控访问日志:定期检查谁在使用代理服务