A Python client library for interacting with the Hysteria2 proxy server API.
pip install hysteria2-apifromhysteria2_apiimportHysteria2Client# Initialize the clientclient=Hysteria2Client(
base_url="http://127.0.0.1:25413", # Replace with your Hysteria2 API URLsecret="your_secret_here"# Replace with your API secret
)
# Get traffic statistics with automatic clearingtraffic_stats=client.get_traffic_stats(clear=True)
foruser_id, statsintraffic_stats.items():
print(f"User: {user_id}")
print(f"Upload: {stats.upload_bytes} bytes")
print(f"Download: {stats.download_bytes} bytes")
# Check which users are onlineonline_users=client.get_online_clients()
foruser_id, statusinonline_users.items():
ifstatus.is_online:
print(f"User {user_id} is online with {status.connections} connection(s)")
# Kick specific usersclient.kick_clients(["user1", "user2"])- Traffic Statistics: Get traffic data for all clients with option to clear after retrieval
- Online Status: Check which clients are currently connected and how many connections they have
- User Management: Kick clients by their IDs
- Type Support: Full type hinting support for better IDE integration
- Error Handling: Specialized exception classes for different error scenarios
The main client class for interacting with the Hysteria2 API.
client=Hysteria2Client(
base_url="http://127.0.0.1:25413", # Base URL of the Hysteria2 APIsecret="your_secret_here", # API secret for authenticationtimeout=10# Request timeout in seconds
)get_traffic_stats(clear=False)
- Gets traffic statistics for all clients
- Parameters:
clear(bool): Whether to clear statistics after retrieval
- Returns: Dictionary mapping client IDs to
TrafficStatsobjects
get_online_clients()
- Gets online status for all clients
- Returns: Dictionary mapping client IDs to
OnlineStatusobjects
kick_clients(client_ids)
- Kicks clients by their IDs
- Parameters:
client_ids(List[str]): List of client IDs to kick
- Returns: True if successful, raises exception otherwise
Represents traffic statistics for a client.
stats=TrafficStats(tx=1024, rx=2048)- Properties:
tx(int): Transmitted bytes (upload)rx(int): Received bytes (download)upload_bytes(int): Alias for txdownload_bytes(int): Alias for rx
Represents online status information for clients.
status=OnlineStatus(connections=2)- Properties:
connections(int): Number of active connectionsis_online(bool): Whether the client is online (has at least one connection)
- Hysteria2Error: Base exception for all Hysteria2 API errors
- Hysteria2AuthError: Raised when authentication with the API fails
- Hysteria2ConnectionError: Raised when there's an error connecting to the API
Here's an example of a script that monitors traffic and updates a local JSON file:
#!/usr/bin/env python3importjsonimportosfromhysteria2_apiimportHysteria2Client# Define static variablesCONFIG_FILE='/etc/hysteria/config.json'USERS_FILE='/etc/hysteria/users.json'API_BASE_URL='http://127.0.0.1:25413'deftraffic_status():
# ANSI color codesgreen='\033[0;32m'cyan='\033[0;36m'NC='\033[0m'# No Color# Load config to get API secretwithopen(CONFIG_FILE, 'r') asconfig_file:
config=json.load(config_file)
secret=config.get('trafficStats', {}).get('secret')
ifnotsecret:
print("Error: Secret not found in config.json")
return# Initialize API clientclient=Hysteria2Client(base_url=API_BASE_URL, secret=secret)
# Get data from APItraffic_stats=client.get_traffic_stats(clear=True)
online_status=client.get_online_clients()
# Load existing user datausers_data= {}
ifos.path.exists(USERS_FILE):
withopen(USERS_FILE, 'r') asusers_file:
users_data=json.load(users_file)
# Update user data with new informationforuser_idinlist(users_data.keys()):
users_data[user_id]["status"] ="Offline"foruser_id, statusinonline_status.items():
ifuser_idinusers_data:
users_data[user_id]["status"] ="Online"ifstatus.is_onlineelse"Offline"else:
users_data[user_id] = {
"upload_bytes": 0,
"download_bytes": 0,
"status": "Online"ifstatus.is_onlineelse"Offline"
}
foruser_id, statsintraffic_stats.items():
ifuser_idinusers_data:
users_data[user_id]["upload_bytes"] +=stats.upload_bytesusers_data[user_id]["download_bytes"] +=stats.download_byteselse:
online=user_idinonline_statusandonline_status[user_id].is_onlineusers_data[user_id] = {
"upload_bytes": stats.upload_bytes,
"download_bytes": stats.download_bytes,
"status": "Online"ifonlineelse"Offline"
}
# Save updated datawithopen(USERS_FILE, 'w') asusers_file:
json.dump(users_data, users_file, indent=4)
# Display traffic dataprint("Traffic Data:")
print("-------------------------------------------------")
print(f"{'User':<15}{'Upload':<15}{'Download':<15}{'Status':<10}")
print("-------------------------------------------------")
foruser, entryinusers_data.items():
upload=format_bytes(entry.get("upload_bytes", 0))
download=format_bytes(entry.get("download_bytes", 0))
status=entry.get("status", "Offline")
print(f"{user:<15}{green}{upload:<15}{NC}{cyan}{download:<15}{NC}{status:<10}")
defformat_bytes(bytes):
forunitin ['B', 'KB', 'MB', 'GB', 'TB']:
ifbytes<1024:
returnf"{bytes:.2f}{unit}"bytes/=1024returnf"{bytes:.2f}PB"if__name__=="__main__":
traffic_status()Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
- Hysteria2 - The high-performance proxy protocol this library interacts with