|
1 | | -# Python V2Ray/Xray Core Wrapper |
| 1 | +# python-v2ray |
2 | 2 |
|
3 | | -A powerful, high-level Python library to control and manage Xray-core instances, featuring a high-performance connection tester written in Go. |
| 3 | +[](https://pypi.org/project/python-v2ray/) |
| 4 | +[](https://www.gnu.org/licenses/gpl-3.0) |
| 5 | +[](https://pypi.org/project/python-v2ray/) |
4 | 6 |
|
5 | | -## Features |
| 7 | +A powerful, high-level Python wrapper for managing and testing V2Ray/Xray-core and Hysteria clients. |
6 | 8 |
|
7 | | -* Start and stop the Xray-core process programmatically. |
8 | | -* Build and parse configurations using Python objects. |
9 | | -* Communicate with the Xray API via gRPC for stats and management. |
10 | | -* Ultra-fast concurrent connection testing engine powered by Go. |
| 9 | +This library abstracts the complexities of binary management, multi-format config parsing, and concurrent connection testing, providing a clean and streamlined API for developers. |
11 | 10 |
|
12 | | -## Quick Start |
| 11 | +--- |
13 | 12 |
|
14 | | -1. Run the setup script to create a virtual environment: |
| 13 | +## ✨ Features |
15 | 14 |
|
16 | | - `setup.bat` (on Windows) |
| 15 | +- **Automated Binary Management**: Automatically downloads and manages the necessary `Xray-core`, `Hysteria`, and test engine binaries for your platform (Windows, macOS, Linux). |
| 16 | +- **Unified Config Parser**: Seamlessly parses various subscription link formats (`vless`, `vmess`, `trojan`, `ss`, `hysteria2`) into a standardized Python object model. |
| 17 | +- **High-Speed Concurrent Testing**: Utilizes a hybrid architecture (Python + Go) to test dozens of configurations simultaneously, reporting latency and connection status in seconds. |
| 18 | +- **Dynamic Config Builder**: A fluent builder API to programmatically construct complex Xray JSON configurations with custom inbounds, outbounds, and routing rules. |
| 19 | +- **Live Statistics**: Connect to a running Xray-core instance's gRPC API to fetch live traffic statistics (uplink & downlink). |
| 20 | +- **Cross-Platform**: Designed to work flawlessly across Windows, macOS, and Linux environments. |
17 | 21 |
|
18 | | - `bash setup.sh` (on Linux/macOS) |
| 22 | +## 🚀 Installation |
19 | 23 |
|
20 | | -2. Activate the environment and explore the examples. |
| 24 | +Install the latest stable version from PyPI: |
| 25 | + |
| 26 | +```bash |
| 27 | +pip install python-v2ray |
| 28 | +``` |
| 29 | + |
| 30 | +## ⚡️ Quick Start: Test a List of Proxies |
| 31 | + |
| 32 | +This example demonstrates the core functionality: downloading dependencies, parsing URIs, and running a connection test. |
| 33 | + |
| 34 | +```python |
| 35 | +from pathlib import Path |
| 36 | +from python_v2ray.downloader import BinaryDownloader |
| 37 | +from python_v2ray.tester import ConnectionTester |
| 38 | +from python_v2ray.config_parser import parse_uri |
| 39 | + |
| 40 | +def run_tests(): |
| 41 | + """ |
| 42 | + An example of ensuring binaries, parsing URIs, and testing their connectivity. |
| 43 | + """ |
| 44 | + project_root = Path("./") # Assumes running from the project's root directory |
| 45 | + |
| 46 | + # --- 1. Ensure all required binaries are available --- |
| 47 | + print("--- Verifying binaries ---") |
| 48 | + try: |
| 49 | + downloader = BinaryDownloader(project_root) |
| 50 | + downloader.ensure_all() |
| 51 | + except Exception as e: |
| 52 | + print(f"Fatal Error: {e}") |
| 53 | + return |
| 54 | + |
| 55 | + # --- 2. Define your list of proxy URIs --- |
| 56 | + test_uris = [ |
| 57 | + "vless://...", |
| 58 | + "vmess://...", |
| 59 | + "hysteria2://...", |
| 60 | + # ... add more of your configs here |
| 61 | + ] |
| 62 | + |
| 63 | + # --- 3. Parse all URIs into a unified format --- |
| 64 | + print("\n* Parsing URIs...") |
| 65 | + parsed_configs = [p for p in (parse_uri(uri) for uri in test_uris) if p] |
| 66 | + if not parsed_configs: |
| 67 | + print("No valid configurations found to test.") |
| 68 | + return |
| 69 | + |
| 70 | + print(f"* Preparing to test {len(parsed_configs)} configurations concurrently...") |
| 71 | + |
| 72 | + # --- 4. Initialize and run the tester --- |
| 73 | + tester = ConnectionTester( |
| 74 | + vendor_path=str(project_root / "vendor"), |
| 75 | + core_engine_path=str(project_root / "core_engine") |
| 76 | + ) |
| 77 | + results = tester.test_uris(parsed_configs) |
| 78 | + |
| 79 | + # --- 5. Display the results, sorted by latency --- |
| 80 | + print("\n" + "="*20 + " Test Results " + "="*20) |
| 81 | + if results: |
| 82 | + sorted_results = sorted(results, key=lambda x: x.get('ping_ms', 9999)) |
| 83 | + for result in sorted_results: |
| 84 | + tag = result.get('tag', 'N/A') |
| 85 | + ping = result.get('ping_ms', -1) |
| 86 | + status = result.get('status', 'error') |
| 87 | + |
| 88 | + if status == 'success': |
| 89 | + print(f"✅ Tag: {tag:<35} | Latency: {ping:>4} ms | Status: {status}") |
| 90 | + else: |
| 91 | + print(f"❌ Tag: {tag:<35} | Latency: {ping:>4} ms | Status: {status.split('|').strip()}") |
| 92 | + else: |
| 93 | + print("No results were received from the tester.") |
| 94 | + print("="*56) |
| 95 | + |
| 96 | +if __name__ == "__main__": |
| 97 | + run_tests() |
| 98 | +``` |
| 99 | + |
| 100 | +## 🏛 Architecture: The Best of Python & Go |
| 101 | + |
| 102 | +`python-v2ray` employs a hybrid architecture for maximum efficiency: |
| 103 | + |
| 104 | +- **Python Orchestrator**: The high-level logic, config management, binary downloading, and process orchestration are handled in Python for its readability and flexibility. |
| 105 | +- **Go Test Engine**: Performance-critical network operations, such as concurrent TCP/SOCKS dialing and latency tests, are delegated to a compiled Go binary (`core_engine`). |
| 106 | + |
| 107 | +Communication between the two layers is achieved via IPC (`stdin`/`stdout`) with a simple JSON-based protocol. This design combines the development speed of Python with the raw network performance of Go. |
| 108 | + |
| 109 | +## 🛠 Advanced Usage: Running a Single Proxy |
| 110 | + |
| 111 | +```python |
| 112 | +from python_v2ray.core import XrayCore |
| 113 | +from python_v2ray.config_parser import parse_uri, XrayConfigBuilder |
| 114 | + |
| 115 | +# Your target proxy URI |
| 116 | +uri = "vless://YOUR_UUID@your.domain.com:443?security=tls&sni=your.domain.com#MyProxy" |
| 117 | + |
| 118 | +params = parse_uri(uri) |
| 119 | +if params: |
| 120 | + # Programmatically build a configuration |
| 121 | + builder = XrayConfigBuilder() |
| 122 | + builder.add_inbound({ |
| 123 | + "port": 10808, "listen": "127.0.0.1", "protocol": "socks", |
| 124 | + "settings": {"auth": "noauth", "udp": True} |
| 125 | + }) |
| 126 | + outbound = builder.build_outbound_from_params(params) |
| 127 | + builder.add_outbound(outbound) |
| 128 | + |
| 129 | + # Run Xray with the generated config |
| 130 | + # The 'with' statement ensures the process is terminated automatically |
| 131 | + with XrayCore(config_builder=builder) as xray: |
| 132 | + print("Xray is running. SOCKS proxy is available on 127.0.0.1:10808") |
| 133 | + # Your application logic here... |
| 134 | + # ... |
| 135 | + print("Xray has been stopped.") |
| 136 | +``` |
| 137 | + |
| 138 | +## 🙏 Acknowledgments |
| 139 | + |
| 140 | +This project would not be possible without the incredible work of the teams behind the core technologies it relies on. Special thanks to: |
| 141 | + |
| 142 | +- **[GFW-knocker/Xray-core](https://github.com/GFW-knocker/Xray-core)** for the powerful and versatile Xray-core. |
| 143 | +- **[apernet/hysteria](https://github.com/apernet/hysteria)** for the feature-rich, high-performance Hysteria proxy. |
| 144 | + |
| 145 | +## 🤝 Contributing |
| 146 | + |
| 147 | +Contributions are welcome! Please feel free to fork the repository, make changes, and submit a pull request. |
| 148 | + |
| 149 | +1. Fork the Project |
| 150 | +2. Create your Feature Branch (`git checkout -b feature/AmazingFeature`) |
| 151 | +3. Commit your Changes (`git commit -m 'Add some AmazingFeature'`) |
| 152 | +4. Push to the Branch (`git push origin feature/AmazingFeature`) |
| 153 | +5. Open a Pull Request |
| 154 | + |
| 155 | +## 📜 License |
| 156 | + |
| 157 | +Distributed under the GNU General Public License v3.0. See `LICENSE` for more information. |
0 commit comments