Upload test 1
This commit is contained in:
@@ -0,0 +1,947 @@
|
||||
#!/usr/bin/env python3
|
||||
"""DragonCoreSSH terminal administration. Python 3 standard library only.
|
||||
|
||||
Root access to /opt/sshpanel/.env acts as local administrator authentication.
|
||||
Passwords are generated; no password input or interactive login is requested.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import datetime as dt
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import shlex
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import textwrap
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
|
||||
INSTALL_DIR = Path(os.environ.get("DRAGONCORE_DIR", "/opt/sshpanel"))
|
||||
ENV_FILE = INSTALL_DIR / ".env"
|
||||
SERVICE = os.environ.get("DRAGONCORE_SERVICE", "sshpanel")
|
||||
|
||||
|
||||
class CLIError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def require_root():
|
||||
if os.geteuid() != 0:
|
||||
raise CLIError("Run from a root shell (or use sudo menu).")
|
||||
|
||||
|
||||
def read_env():
|
||||
try:
|
||||
fd = os.open(ENV_FILE, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
|
||||
with os.fdopen(fd, encoding="utf-8") as handle:
|
||||
if not stat.S_ISREG(os.fstat(handle.fileno()).st_mode):
|
||||
raise CLIError(".env must be a regular file")
|
||||
lines = handle.readlines()
|
||||
except OSError as exc:
|
||||
raise CLIError(f"Cannot read {ENV_FILE}: {exc}") from exc
|
||||
values = {}
|
||||
for line in lines:
|
||||
if "=" in line and not line.lstrip().startswith("#"):
|
||||
key, value = line.rstrip("\n").split("=", 1)
|
||||
values[key.strip()] = value.strip().strip('"')
|
||||
return lines, values
|
||||
|
||||
|
||||
def api_password():
|
||||
token = read_env()[1].get("ADMIN_TOKEN", "")
|
||||
if len(token) < 32:
|
||||
raise CLIError("ADMIN_TOKEN is missing or too short in .env")
|
||||
return token
|
||||
|
||||
|
||||
def api_base():
|
||||
address = read_env()[1].get("ADMIN_HTTP_ADDR", "127.0.0.1:9090")
|
||||
try:
|
||||
parsed = urllib.parse.urlsplit("http://" + address)
|
||||
port = parsed.port
|
||||
if not port or not 1 <= port <= 65535:
|
||||
raise ValueError("invalid port")
|
||||
except ValueError as exc:
|
||||
raise CLIError(f"Invalid ADMIN_HTTP_ADDR: {exc}") from exc
|
||||
# Always connect locally, including when the API is explicitly exposed
|
||||
# for managed-server integrations.
|
||||
host = "[::1]" if parsed.hostname in ("::", "::1") else "127.0.0.1"
|
||||
return f"http://{host}:{port}"
|
||||
|
||||
|
||||
def request(method, path, data=None, timeout=25):
|
||||
if not path.startswith("/") or path.startswith("//"):
|
||||
raise CLIError("Invalid API path")
|
||||
body = None if data is None else json.dumps(data).encode("utf-8")
|
||||
req = urllib.request.Request(
|
||||
api_base() + path, data=body, method=method,
|
||||
headers={"Authorization": "Bearer " + api_password(),
|
||||
"Content-Type": "application/json", "Accept": "application/json"},
|
||||
)
|
||||
try:
|
||||
# Do not send the bearer credential through an inherited HTTP proxy.
|
||||
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
with opener.open(req, timeout=timeout) as response:
|
||||
raw = response.read(2 * 1024 * 1024)
|
||||
return json.loads(raw) if raw.strip() else None
|
||||
except urllib.error.HTTPError as exc:
|
||||
detail = exc.read(2048).decode("utf-8", "replace").strip()
|
||||
raise CLIError(f"API {exc.code}: {detail}") from exc
|
||||
except (urllib.error.URLError, TimeoutError) as exc:
|
||||
raise CLIError(f"API unavailable at {api_base()}: {exc}") from exc
|
||||
|
||||
|
||||
def write_env_token(token):
|
||||
if len(token) < 32 or not all(ch.isalnum() or ch in "-_" for ch in token):
|
||||
raise CLIError("API password must have 32+ letters, digits, - or _")
|
||||
lines, _ = read_env()
|
||||
replaced = False
|
||||
out = []
|
||||
for line in lines:
|
||||
if line.startswith("ADMIN_TOKEN="):
|
||||
if not replaced:
|
||||
out.append("ADMIN_TOKEN=" + token + "\n")
|
||||
replaced = True
|
||||
else:
|
||||
out.append(line)
|
||||
if not replaced:
|
||||
out.append("ADMIN_TOKEN=" + token + "\n")
|
||||
old = os.stat(ENV_FILE, follow_symlinks=False)
|
||||
fd, tmp = tempfile.mkstemp(prefix=".env.dragoncore-", dir=ENV_FILE.parent)
|
||||
try:
|
||||
os.fchmod(fd, 0o600)
|
||||
os.fchown(fd, old.st_uid, old.st_gid)
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
||||
handle.writelines(out)
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
os.replace(tmp, ENV_FILE)
|
||||
dirfd = os.open(ENV_FILE.parent, os.O_RDONLY)
|
||||
try:
|
||||
os.fsync(dirfd)
|
||||
finally:
|
||||
os.close(dirfd)
|
||||
finally:
|
||||
if os.path.exists(tmp):
|
||||
os.unlink(tmp)
|
||||
|
||||
|
||||
def service_action(action):
|
||||
proc = subprocess.run(["systemctl", action, SERVICE], capture_output=True, text=True)
|
||||
if proc.returncode:
|
||||
raise CLIError((proc.stderr or proc.stdout).strip() or f"systemctl {action} failed")
|
||||
|
||||
|
||||
def rotate_api_password():
|
||||
old = api_password()
|
||||
new = secrets.token_urlsafe(36)
|
||||
write_env_token(new)
|
||||
try:
|
||||
service_action("restart")
|
||||
last_error = None
|
||||
for _ in range(12):
|
||||
try:
|
||||
request("GET", "/api/users") # Verify the new token is active.
|
||||
last_error = None
|
||||
break
|
||||
except CLIError as exc:
|
||||
last_error = exc
|
||||
time.sleep(1)
|
||||
if last_error:
|
||||
raise last_error
|
||||
except CLIError as exc:
|
||||
write_env_token(old)
|
||||
try:
|
||||
service_action("restart")
|
||||
except CLIError:
|
||||
pass
|
||||
raise CLIError(f"Rotation failed; previous password restored: {exc}") from exc
|
||||
print("New API password:", new)
|
||||
|
||||
|
||||
def ask(label, default=""):
|
||||
suffix = f" [{default}]" if default != "" else ""
|
||||
result = input(f"{label}{suffix}: ").strip()
|
||||
return result or str(default)
|
||||
|
||||
|
||||
def number(label, default, minimum=0, maximum=1000000):
|
||||
raw = ask(label, default)
|
||||
try:
|
||||
value = int(raw)
|
||||
except ValueError as exc:
|
||||
raise CLIError(f"{label} must be a number") from exc
|
||||
if not minimum <= value <= maximum:
|
||||
raise CLIError(f"{label} must be between {minimum} and {maximum}")
|
||||
return value
|
||||
|
||||
|
||||
def expiry(default=""):
|
||||
raw = ask("Expiry (YYYY-MM-DD, days from now, or 'never')", default or "never")
|
||||
if raw.lower() in ("never", "none", "0"):
|
||||
return ""
|
||||
try:
|
||||
day = dt.date.today() + dt.timedelta(days=int(raw)) if raw.isdecimal() else dt.date.fromisoformat(raw)
|
||||
return day.isoformat() + "T23:59:59Z"
|
||||
except ValueError as exc:
|
||||
raise CLIError("Enter YYYY-MM-DD, number of days, or never") from exc
|
||||
|
||||
|
||||
def confirm(label):
|
||||
return input(label + " Type YES: ").strip() == "YES"
|
||||
|
||||
|
||||
def size(n):
|
||||
n = float(n or 0)
|
||||
for unit in ("B", "KiB", "MiB", "GiB", "TiB"):
|
||||
if abs(n) < 1024 or unit == "TiB":
|
||||
return f"{n:.1f} {unit}"
|
||||
n /= 1024
|
||||
|
||||
|
||||
def terminal_columns():
|
||||
override = os.environ.get("DRAGONCORE_COLUMNS", "")
|
||||
if override.isdecimal() and 24 <= int(override) <= 240:
|
||||
return int(override)
|
||||
return max(24, shutil.get_terminal_size(fallback=(80, 24)).columns)
|
||||
|
||||
|
||||
def print_wrapped(value, indent=""):
|
||||
width = max(20, terminal_columns() - len(indent) - 1)
|
||||
for part in textwrap.wrap(str(value), width=width, break_long_words=True) or [""]:
|
||||
print(indent + part)
|
||||
|
||||
|
||||
def parse_expiry(value):
|
||||
if not value:
|
||||
return None
|
||||
try:
|
||||
parsed = dt.datetime.fromisoformat(value.replace("Z", "+00:00"))
|
||||
return parsed if parsed.tzinfo else parsed.replace(tzinfo=dt.timezone.utc)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def local_meminfo():
|
||||
try:
|
||||
lines = Path("/proc/meminfo").read_text().splitlines()
|
||||
values = {k.rstrip(":"): int(v.split()[0]) * 1024 for k, v in (line.split(":", 1) for line in lines)}
|
||||
total = values["MemTotal"]
|
||||
return total, max(0, total - values["MemAvailable"])
|
||||
except (OSError, KeyError, ValueError):
|
||||
return 0, 0
|
||||
|
||||
|
||||
def collect_vps_status():
|
||||
"""Read live host and DragonCore data; degraded API data never blocks the menu."""
|
||||
try:
|
||||
os_name = next((line.split("=", 1)[1].strip().strip('"')
|
||||
for line in Path("/etc/os-release").read_text().splitlines()
|
||||
if line.startswith("PRETTY_NAME=")), "Linux")
|
||||
except OSError:
|
||||
os_name = "Linux"
|
||||
try:
|
||||
seconds = int(float(Path("/proc/uptime").read_text().split()[0]))
|
||||
uptime = f"{seconds // 86400}d {(seconds % 86400) // 3600}h"
|
||||
except (OSError, ValueError, IndexError):
|
||||
uptime = "--"
|
||||
try:
|
||||
service = subprocess.run(["systemctl", "is-active", SERVICE], capture_output=True, text=True)
|
||||
state = service.stdout.strip()
|
||||
if state not in ("active", "inactive", "failed", "activating", "deactivating"):
|
||||
state = "unknown"
|
||||
except OSError:
|
||||
state = "unknown"
|
||||
stats = users = xray = None
|
||||
for path, key in (("/api/stats", "stats"), ("/api/users", "users"),
|
||||
("/api/xray/status", "xray")):
|
||||
try:
|
||||
value = request("GET", path, timeout=2)
|
||||
except (CLIError, ValueError):
|
||||
value = None
|
||||
if key == "stats":
|
||||
stats = value if isinstance(value, dict) else None
|
||||
elif key == "users":
|
||||
users = value if isinstance(value, list) else None
|
||||
else:
|
||||
xray = value if isinstance(value, dict) else None
|
||||
|
||||
total_mem, used_mem = local_meminfo()
|
||||
if stats and stats.get("mem_total_bytes"):
|
||||
total_mem = stats["mem_total_bytes"]
|
||||
used_mem = stats.get("mem_used_bytes", 0)
|
||||
now = dt.datetime.now(dt.timezone.utc)
|
||||
expired = sum(1 for u in users or [] if (e := parse_expiry(u.get("expires_at"))) and e <= now)
|
||||
interfaces = (stats or {}).get("interfaces") or []
|
||||
try:
|
||||
disk = shutil.disk_usage("/")
|
||||
disk_pct = 100 * disk.used / disk.total if disk.total else 0
|
||||
except OSError:
|
||||
disk_pct = 0
|
||||
return {
|
||||
"host": os.uname().nodename, "os": os_name, "uptime": uptime,
|
||||
"time": dt.datetime.now().astimezone().strftime("%Y-%m-%d %H:%M"),
|
||||
"cores": os.cpu_count() or 1, "cpu": (stats or {}).get("cpu_percent"),
|
||||
"mem_total": total_mem, "mem_used": used_mem,
|
||||
"disk_pct": disk_pct,
|
||||
"ssh_total": len(users) if users is not None else None,
|
||||
"ssh_online": sum(1 for u in users or [] if u.get("active_conns", 0) > 0) if users is not None else None,
|
||||
"ssh_expired": expired if users is not None else None,
|
||||
"xray_online": xray.get("online_users") if xray else None,
|
||||
"down_mbps": max((item.get("rx_mbps", 0) for item in interfaces), default=0),
|
||||
"up_mbps": max((item.get("tx_mbps", 0) for item in interfaces), default=0),
|
||||
"service": state, "api_online": stats is not None and users is not None,
|
||||
}
|
||||
|
||||
|
||||
def render_vps_status(s, columns=None):
|
||||
"""Render VPS status within the terminal width, including narrow phones."""
|
||||
cols = columns or terminal_columns()
|
||||
width = min(74, max(20, cols - 4))
|
||||
def field(value):
|
||||
return "--" if value is None else str(value)
|
||||
def line(value):
|
||||
return "┃ " + value.ljust(width) + " ┃"
|
||||
cpu = "--" if s["cpu"] is None else f"{s['cpu']:.1f}%"
|
||||
ram = (f"{size(s['mem_used'])}/{size(s['mem_total'])}"
|
||||
if s["mem_total"] else "--")
|
||||
if cols < 60:
|
||||
rows = [
|
||||
"DRAGONCORESSH • VPS",
|
||||
f"OS: {s['os']}",
|
||||
f"Host: {s['host']} {s['time'][-5:]}",
|
||||
f"CPU: {cpu} / {s['cores']} cores",
|
||||
f"RAM: {ram} Disk: {s['disk_pct']:.0f}%",
|
||||
f"Uptime: {s['uptime']} Service: {s['service']}",
|
||||
f"SSH: {field(s['ssh_online'])} on / {field(s['ssh_total'])} total",
|
||||
f"Expired: {field(s['ssh_expired'])} Xray: {field(s['xray_online'])} on",
|
||||
f"Net: ↓ {s['down_mbps']:.1f} ↑ {s['up_mbps']:.1f} Mbps"
|
||||
if s["api_online"] else "API offline; VPS data local",
|
||||
]
|
||||
else:
|
||||
rows = [
|
||||
"DRAGONCORESSH • VPS STATUS",
|
||||
f"OS: {s['os']} Host: {s['host']}",
|
||||
f"Time: {s['time']} Uptime: {s['uptime']} Service: {s['service']}",
|
||||
f"CPU: {cpu} ({s['cores']} cores) RAM: {ram} Disk: {s['disk_pct']:.0f}%",
|
||||
f"SSH: {field(s['ssh_online'])} online | {field(s['ssh_expired'])} expired | "
|
||||
f"{field(s['ssh_total'])} total Xray: {field(s['xray_online'])} online",
|
||||
f"Network: ↓ {s['down_mbps']:.2f} Mbps ↑ {s['up_mbps']:.2f} Mbps"
|
||||
if s["api_online"] else "API: unavailable; local VPS metrics shown above",
|
||||
]
|
||||
wrapped = (piece for row in rows for piece in textwrap.wrap(row, width=width, break_long_words=True))
|
||||
return "\n".join(["┏" + "━" * (width + 2) + "┓", *(line(part) for part in wrapped),
|
||||
"┗" + "━" * (width + 2) + "┛"])
|
||||
|
||||
|
||||
def list_users():
|
||||
users = request("GET", "/api/users") or []
|
||||
if terminal_columns() < 72:
|
||||
for u in sorted(users, key=lambda row: row["username"]):
|
||||
print_wrapped(f"{u['username']} {u.get('active_conns', 0)}/{u.get('max_connections', 0)} online")
|
||||
print_wrapped(f"Usage {size(u.get('total_bytes', 0))} "
|
||||
f"Expires {str(u.get('expires_at') or 'never')[:10]}", " ")
|
||||
else:
|
||||
print(f"{'USER':<24} {'ONLINE':>6} {'LIMIT':>6} {'USAGE':>12} EXPIRES")
|
||||
for u in sorted(users, key=lambda row: row["username"]):
|
||||
print(f"{u['username']:<24} {u.get('active_conns', 0):>6} "
|
||||
f"{u.get('max_connections', 0):>6} {size(u.get('total_bytes', 0)):>12} "
|
||||
f"{str(u.get('expires_at') or 'never')[:10]}")
|
||||
print(f"Total: {len(users)}")
|
||||
return users
|
||||
|
||||
|
||||
def user_payload(u):
|
||||
fields = ("username", "max_connections", "limit_mbps_up", "limit_mbps_down",
|
||||
"data_quota_bytes", "quota_action", "quota_throttle_mbps", "totp_secret",
|
||||
"totp_period", "totp_window", "totp_digits", "allow_static_password",
|
||||
"use_pam", "owner_username")
|
||||
p = {field: u[field] for field in fields if field in u}
|
||||
p["expires_at"] = u.get("expires_at") or ""
|
||||
return p
|
||||
|
||||
|
||||
def get_user(name):
|
||||
return next((u for u in request("GET", "/api/users") or [] if u["username"] == name), None)
|
||||
|
||||
|
||||
def create_user(default_days=30, test_hours=None):
|
||||
name = ask("SSH username").lower()
|
||||
if not name:
|
||||
raise CLIError("Username required")
|
||||
if get_user(name):
|
||||
raise CLIError("User exists; choose Edit SSH user")
|
||||
password = secrets.token_urlsafe(18)
|
||||
expires_at = ((dt.datetime.now(dt.timezone.utc) + dt.timedelta(hours=test_hours)).isoformat(timespec="seconds")
|
||||
if test_hours else expiry(str(default_days)))
|
||||
p = {"username": name, "password": password, "max_connections": number("Max connections", 1, 0, 10000),
|
||||
"expires_at": expires_at, "limit_mbps_up": 0, "limit_mbps_down": 0,
|
||||
"data_quota_bytes": 0, "quota_action": "throttle", "quota_throttle_mbps": 10}
|
||||
request("POST", "/api/users/create", p)
|
||||
print(f"SSH user: {name}\nGenerated SSH password: {password}")
|
||||
|
||||
|
||||
def edit_user():
|
||||
name = ask("SSH username").lower()
|
||||
u = get_user(name)
|
||||
if not u:
|
||||
raise CLIError("User not found")
|
||||
p = user_payload(u)
|
||||
print("1 Expiry 2 Connections 3 Bandwidth 4 Quota 5 Generate new password")
|
||||
choice = ask("Option")
|
||||
if choice == "1":
|
||||
p["expires_at"] = expiry(str(u.get("expires_at") or "")[:10])
|
||||
elif choice == "2":
|
||||
p["max_connections"] = number("Max connections", u.get("max_connections", 1), 0, 10000)
|
||||
elif choice == "3":
|
||||
p["limit_mbps_up"] = number("Upload Mbps (0 = default)", u.get("limit_mbps_up", 0))
|
||||
p["limit_mbps_down"] = number("Download Mbps (0 = default)", u.get("limit_mbps_down", 0))
|
||||
elif choice == "4":
|
||||
gib = number("Quota GiB (0 = unlimited)", round(u.get("data_quota_bytes", 0) / 1024**3))
|
||||
p["data_quota_bytes"] = gib * 1024**3
|
||||
p["quota_action"] = ask("On quota: throttle/block", u.get("quota_action") or "throttle")
|
||||
p["quota_throttle_mbps"] = number("Throttle Mbps", u.get("quota_throttle_mbps") or 10)
|
||||
elif choice == "5":
|
||||
p["password"] = secrets.token_urlsafe(18)
|
||||
else:
|
||||
return
|
||||
request("POST", "/api/users/create", p)
|
||||
print("Saved.")
|
||||
if choice == "5":
|
||||
print("Generated SSH password:", p["password"])
|
||||
|
||||
|
||||
def delete_user():
|
||||
name = ask("SSH username").lower()
|
||||
if confirm(f"Delete SSH user {name}?"):
|
||||
request("DELETE", "/api/users/delete?" + urllib.parse.urlencode({"username": name}))
|
||||
print("Deleted.")
|
||||
|
||||
|
||||
def reset_traffic():
|
||||
name = ask("SSH username").lower()
|
||||
if confirm(f"Reset usage for {name}?"):
|
||||
request("POST", "/api/users/reset-traffic", {"username": name})
|
||||
print("Traffic reset.")
|
||||
|
||||
|
||||
def delete_expired_users():
|
||||
now = dt.datetime.now(dt.timezone.utc)
|
||||
expired = [u["username"] for u in request("GET", "/api/users") or []
|
||||
if (end := parse_expiry(u.get("expires_at"))) and end <= now]
|
||||
if not expired:
|
||||
print("No expired SSH users.")
|
||||
return
|
||||
print("Expired SSH users:", ", ".join(expired))
|
||||
if confirm(f"Delete all {len(expired)} expired SSH users?"):
|
||||
for name in expired:
|
||||
request("DELETE", "/api/users/delete?" + urllib.parse.urlencode({"username": name}))
|
||||
print(f"Deleted {len(expired)} SSH users.")
|
||||
|
||||
|
||||
def user_report():
|
||||
for u in request("GET", "/api/users") or []:
|
||||
print()
|
||||
print_wrapped(f"{u['username']} | connections {u.get('active_conns', 0)}/{u.get('max_connections', 0)}"
|
||||
f" | expires {str(u.get('expires_at') or 'never')[:10]}")
|
||||
quota = u.get("data_quota_bytes", 0)
|
||||
print_wrapped(f"Usage {size(u.get('total_bytes', 0))}/{size(quota) if quota else 'unlimited'}"
|
||||
f" | speed ↑ {size(u.get('up_bytes_per_sec', 0))}/s"
|
||||
f" ↓ {size(u.get('down_bytes_per_sec', 0))}/s", " ")
|
||||
|
||||
|
||||
def xray_inbounds():
|
||||
inbounds = request("GET", "/api/xray/inbounds") or []
|
||||
for inbound in inbounds:
|
||||
endpoint = ("shared SSH/TLS ports" if inbound.get("shared_port") else
|
||||
f"port {inbound.get('port')}")
|
||||
print_wrapped(f"{inbound.get('tag')} ({inbound.get('protocol')}/{inbound.get('network') or 'tcp'}, "
|
||||
f"{endpoint}, path {inbound.get('path') or '-'})")
|
||||
for c in inbound.get("clients") or []:
|
||||
print_wrapped(f"{c.get('name') or c.get('email') or c.get('uuid')} "
|
||||
f"online={c.get('online', False)} "
|
||||
f"usage={size(c.get('total_bytes', 0))}", " ")
|
||||
print_wrapped(str(c.get('uuid')), " ")
|
||||
return inbounds
|
||||
|
||||
|
||||
def xray_shared_port():
|
||||
"""Configure an HTTP transport on the panel's existing public ports."""
|
||||
server = request("GET", "/api/server/config")
|
||||
xray = server.get("xray") or {}
|
||||
if xray.get("mode", "native") == "external":
|
||||
raise CLIError("Shared ports require native Xray emulator mode")
|
||||
listeners = [server.get("listen") or "0.0.0.0:80", *(server.get("extra_listen") or [])]
|
||||
tls_listeners = [entry.get("listen") for entry in server.get("tls_forwarders") or []]
|
||||
print_wrapped("Public SSH/HTTP: " + ", ".join(listeners))
|
||||
if tls_listeners:
|
||||
print_wrapped("Public TLS: " + ", ".join(tls_listeners))
|
||||
config = request("GET", "/api/xray/config")
|
||||
inbounds = config.setdefault("inbounds", [])
|
||||
candidates = [ib for ib in inbounds if ib.get("protocol") in ("vless", "vmess")]
|
||||
for ib in candidates:
|
||||
print_wrapped(f"{ib.get('tag')} ({ib.get('protocol')})"
|
||||
+ (" [shared]" if ib.get("dragoncoreSharedPort") else ""), " ")
|
||||
tag = ask("Inbound tag (new or listed)")
|
||||
if not tag or any(ch.isspace() for ch in tag):
|
||||
raise CLIError("Enter a tag without spaces")
|
||||
inbound = next((ib for ib in candidates if ib.get("tag") == tag), None)
|
||||
if inbound is None and any(ib.get("tag") == tag for ib in inbounds):
|
||||
raise CLIError("That tag belongs to an unsupported inbound")
|
||||
transport = ask("Transport (ws/xhttp)",
|
||||
((inbound or {}).get("streamSettings") or {}).get("network", "ws")).lower()
|
||||
transport = {"websocket": "ws", "splithttp": "xhttp"}.get(transport, transport)
|
||||
if transport not in ("ws", "xhttp"):
|
||||
raise CLIError("Shared port requires ws or xhttp")
|
||||
existing_paths = set()
|
||||
for ib in inbounds:
|
||||
if ib is inbound or not ib.get("dragoncoreSharedPort"):
|
||||
continue
|
||||
stream = ib.get("streamSettings") or {}
|
||||
settings = stream.get("wsSettings") if stream.get("network") in ("ws", "websocket") else stream.get("xhttpSettings")
|
||||
path = (settings or {}).get("path", "").rstrip("/")
|
||||
existing_paths.add(path)
|
||||
def overlaps_shared(path):
|
||||
return any(path == old or path.startswith(old + "/") or old.startswith(path + "/")
|
||||
for old in existing_paths)
|
||||
|
||||
auto = next(f"/c{i}" for i in range(1, 10000) if not overlaps_shared(f"/c{i}"))
|
||||
old_stream = (inbound or {}).get("streamSettings") or {}
|
||||
old_settings = old_stream.get("wsSettings" if transport == "ws" else "xhttpSettings") or {}
|
||||
entered = ask("Path (blank generates one)", old_settings.get("path", ""))
|
||||
path = entered or auto
|
||||
if not path.startswith("/"):
|
||||
path = "/" + path
|
||||
path = path.rstrip("/")
|
||||
if path in ("", "/") or any(ch in path for ch in "?#%\\ \t\r\n") or "//" in path or any(
|
||||
segment in (".", "..") for segment in path.split("/")):
|
||||
raise CLIError("Use a distinct URL path like /c1")
|
||||
if overlaps_shared(path):
|
||||
raise CLIError("Path overlaps another shared Xray inbound")
|
||||
if inbound is None:
|
||||
protocol = ask("Protocol (vless/vmess)", "vless").lower()
|
||||
if protocol not in ("vless", "vmess"):
|
||||
raise CLIError("Protocol must be vless or vmess")
|
||||
client_uuid = str(uuid.uuid4())
|
||||
inbound = {"tag": tag, "protocol": protocol,
|
||||
"settings": {"clients": [{"id": client_uuid, "email": tag + "@dragoncore.local"}]}}
|
||||
inbounds.append(inbound)
|
||||
print("Generated client UUID:", client_uuid)
|
||||
else:
|
||||
print_wrapped("The existing inbound transport will change; its clients are preserved.")
|
||||
# Port is informational for shared inbounds: the panel already owns all
|
||||
# public sockets. Clients use the port of whichever SSH/TLS listener they choose.
|
||||
inbound["port"] = int(listeners[0].rsplit(":", 1)[-1])
|
||||
inbound["dragoncoreSharedPort"] = True
|
||||
stream = inbound.setdefault("streamSettings", {})
|
||||
stream["network"] = transport
|
||||
stream["security"] = "none" # the panel's TLS forwarder terminates TLS
|
||||
stream.pop("tlsSettings", None)
|
||||
stream.pop("wsSettings", None)
|
||||
stream.pop("xhttpSettings", None)
|
||||
stream.pop("splithttpSettings", None)
|
||||
stream["wsSettings" if transport == "ws" else "xhttpSettings"] = {"path": path}
|
||||
print_wrapped(f"Shared {transport.upper()} path: {path}")
|
||||
if not confirm("Save and apply this Xray inbound?"):
|
||||
return
|
||||
request("POST", "/api/xray/config", config)
|
||||
status = request("GET", "/api/xray/status") or {}
|
||||
action = "restart" if status.get("running") else "start"
|
||||
request("POST", f"/api/xray/{action}", {})
|
||||
print_wrapped("Active on the public SSH/HTTP ports and configured TLS ports."
|
||||
" Set the client path above; use TLS security in the client when using a TLS port.")
|
||||
|
||||
|
||||
def xray_create():
|
||||
inbounds = xray_inbounds()
|
||||
tag = ask("Inbound tag")
|
||||
if not any(x.get("tag") == tag for x in inbounds):
|
||||
raise CLIError("Choose an inbound tag from the list")
|
||||
name = ask("Client name")
|
||||
if not name:
|
||||
raise CLIError("Client name required")
|
||||
client_uuid = str(uuid.uuid4())
|
||||
data = {"inbound_tag": tag, "uuid": client_uuid,
|
||||
"name": name, "email": name.lower().replace(" ", "-") + "@dragoncore.local",
|
||||
"expires_at": expiry("30"), "max_connections": 0,
|
||||
"data_quota_bytes": 0, "quota_action": "block", "quota_throttle_mbps": 1}
|
||||
request("POST", "/api/xray/clients/add", data)
|
||||
print("Created Xray client UUID:", client_uuid)
|
||||
|
||||
|
||||
def xray_delete():
|
||||
tag = ask("Inbound tag")
|
||||
client_uuid = ask("Client UUID")
|
||||
if confirm(f"Delete Xray client {client_uuid}?"):
|
||||
query = urllib.parse.urlencode({"inbound_tag": tag, "uuid": client_uuid})
|
||||
request("DELETE", "/api/xray/clients/remove?" + query)
|
||||
print("Deleted.")
|
||||
|
||||
|
||||
def xray_edit():
|
||||
client_uuid = ask("Client UUID")
|
||||
client = next((c for inbound in request("GET", "/api/xray/inbounds") or []
|
||||
for c in inbound.get("clients") or [] if c.get("uuid") == client_uuid), None)
|
||||
if not client:
|
||||
raise CLIError("Xray client not found")
|
||||
p = {"uuid": client_uuid, "name": client.get("name") or "",
|
||||
"email": client.get("email") or "", "expires_at": client.get("expires_at") or "",
|
||||
"max_connections": client.get("max_conns") or 0,
|
||||
"data_quota_bytes": client.get("data_quota_bytes") or 0,
|
||||
"quota_action": client.get("quota_action") or "block",
|
||||
"quota_throttle_mbps": client.get("quota_throttle_mbps") or 1}
|
||||
print("1 Expiry 2 Connection limit 3 Quota 4 Name")
|
||||
choice = ask("Option")
|
||||
if choice == "1":
|
||||
p["expires_at"] = expiry(str(p["expires_at"])[:10])
|
||||
elif choice == "2":
|
||||
p["max_connections"] = number("Max connections (0 = unlimited)", p["max_connections"], 0, 10000)
|
||||
elif choice == "3":
|
||||
p["data_quota_bytes"] = number("Quota GiB (0 = unlimited)", round(p["data_quota_bytes"] / 1024**3)) * 1024**3
|
||||
p["quota_action"] = ask("On quota: block/throttle", p["quota_action"])
|
||||
p["quota_throttle_mbps"] = number("Throttle Mbps", p["quota_throttle_mbps"])
|
||||
elif choice == "4":
|
||||
p["name"] = ask("Name", p["name"])
|
||||
else:
|
||||
return
|
||||
request("POST", "/api/xray/clients/update", p)
|
||||
print("Saved.")
|
||||
|
||||
|
||||
def xray_reset_traffic():
|
||||
client_uuid = ask("Client UUID")
|
||||
if confirm(f"Reset traffic for {client_uuid}?"):
|
||||
request("POST", "/api/xray/clients/reset-traffic", {"uuid": client_uuid})
|
||||
print("Traffic reset.")
|
||||
|
||||
|
||||
def edit_json(path):
|
||||
data = request("GET", path)
|
||||
fd, name = tempfile.mkstemp(prefix="dragoncore-", suffix=".json")
|
||||
try:
|
||||
os.fchmod(fd, 0o600)
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as out:
|
||||
json.dump(data, out, indent=2, ensure_ascii=False)
|
||||
out.write("\n")
|
||||
before = Path(name).read_bytes()
|
||||
editor = shlex.split(os.environ.get("EDITOR") or (shutil.which("nano") or shutil.which("vi") or ""))
|
||||
if not editor or subprocess.run([*editor, name]).returncode:
|
||||
raise CLIError("No working editor (install nano or set EDITOR); changes discarded")
|
||||
after = Path(name).read_bytes()
|
||||
if after == before:
|
||||
print("No changes.")
|
||||
return
|
||||
updated = json.loads(after)
|
||||
if not confirm("Apply these configuration changes through the API?"):
|
||||
return
|
||||
request("POST", path, updated)
|
||||
print("Configuration saved.")
|
||||
finally:
|
||||
os.unlink(name)
|
||||
|
||||
|
||||
def set_banner():
|
||||
cfg = request("GET", "/api/server/config")
|
||||
print("Enter banner text, finish with a line containing only a dot:")
|
||||
lines = []
|
||||
while True:
|
||||
line = input()
|
||||
if line == ".":
|
||||
break
|
||||
lines.append(line)
|
||||
cfg["banner"] = "\n".join(lines)
|
||||
request("POST", "/api/server/config", cfg)
|
||||
print("Banner applied.")
|
||||
|
||||
|
||||
def set_ssh_ports():
|
||||
cfg = request("GET", "/api/server/config")
|
||||
cfg["listen"] = ask("Primary SSH address (IP:port)", cfg.get("listen") or "0.0.0.0:80")
|
||||
current = ", ".join(cfg.get("extra_listen") or [])
|
||||
extras = input(f"Extra addresses, comma separated [{current}] (enter - to clear): ").strip()
|
||||
extras = "" if extras == "-" else (extras or current)
|
||||
cfg["extra_listen"] = [part.strip() for part in extras.split(",") if part.strip()]
|
||||
result = request("POST", "/api/server/config", cfg)
|
||||
print("SSH listener settings applied.")
|
||||
if result:
|
||||
print(json.dumps(result, indent=2)[:2000])
|
||||
|
||||
|
||||
def set_ssh_limits():
|
||||
cfg = request("GET", "/api/server/config")
|
||||
cfg["default_limit_mbps_up"] = number("Default upload Mbps (0 = unlimited)", cfg.get("default_limit_mbps_up", 0))
|
||||
cfg["default_limit_mbps_down"] = number("Default download Mbps (0 = unlimited)", cfg.get("default_limit_mbps_down", 0))
|
||||
cfg["max_total_connections"] = number("Global SSH connection cap (0 = default)", cfg.get("max_total_connections", 0), 0, 1000000)
|
||||
request("POST", "/api/server/config", cfg)
|
||||
print("Default limits applied.")
|
||||
|
||||
|
||||
def status():
|
||||
print(render_vps_status(collect_vps_status()))
|
||||
try:
|
||||
stats = request("GET", "/api/stats")
|
||||
print("\nNetwork interfaces:")
|
||||
for iface in stats.get("interfaces") or []:
|
||||
if terminal_columns() < 72:
|
||||
print_wrapped(f"{iface['name']} ↓ {iface.get('rx_mbps', 0):.2f} Mbps "
|
||||
f"↑ {iface.get('tx_mbps', 0):.2f} Mbps", " ")
|
||||
print_wrapped(f"RX {size(iface.get('rx_bytes', 0))} "
|
||||
f"TX {size(iface.get('tx_bytes', 0))}", " ")
|
||||
else:
|
||||
print(f" {iface['name']:<18} ↓ {iface.get('rx_mbps', 0):>8.2f} Mbps "
|
||||
f"↑ {iface.get('tx_mbps', 0):>8.2f} Mbps "
|
||||
f"RX {size(iface.get('rx_bytes', 0))} TX {size(iface.get('tx_bytes', 0))}")
|
||||
except CLIError as exc:
|
||||
print(exc)
|
||||
|
||||
|
||||
def connection_status():
|
||||
cfg = request("GET", "/api/server/config")
|
||||
print_wrapped("Public SSH: " + ", ".join([cfg.get("listen", "--"), *(cfg.get("extra_listen") or [])]))
|
||||
print_wrapped("Local SSH: " + cfg.get("local_ssh_listen", "127.0.0.1:2222"))
|
||||
for listener in cfg.get("tls_forwarders") or []:
|
||||
print_wrapped("TLS SSH: " + listener.get("listen", "--"))
|
||||
for name, label, fields in (
|
||||
("bhttp", "BHTTP", ("listen", "shared_ports")),
|
||||
("hcr", "HCR", ("listen", "shared_ports")),
|
||||
("btun", "BTUN", ("tcp_listen", "udp_listen", "shared_ports")),
|
||||
("dnstt", "DNSTT", ("domain", "udp_listen")),
|
||||
("udpgw", "UDPGW", ("listen",)),
|
||||
("xray", "Xray", ("mode", "enabled")),
|
||||
):
|
||||
block = cfg.get(name)
|
||||
if block is None:
|
||||
print(f"{label}: disabled")
|
||||
else:
|
||||
details = " ".join(f"{f}={block[f]}" for f in fields if f in block)
|
||||
print_wrapped(f"{label}: configured {details}")
|
||||
|
||||
|
||||
def protocol_stats():
|
||||
for label, path in (("DNSTT", "/api/dnstt"), ("BHTTP", "/api/bhttp"),
|
||||
("HCR", "/api/hcr"), ("BTUN", "/api/btun")):
|
||||
try:
|
||||
print(f"\n{label}: {json.dumps(request('GET', path), indent=2)[:1200]}")
|
||||
except CLIError as exc:
|
||||
print(f"{label}: {exc}")
|
||||
|
||||
|
||||
def protocol_logs():
|
||||
print("1 DNSTT 2 BHTTP 3 HCR 4 BTUN")
|
||||
selected = ask("Protocol")
|
||||
endpoint = {"1": "dnstt", "2": "bhttp", "3": "hcr", "4": "btun"}.get(selected)
|
||||
if not endpoint:
|
||||
raise CLIError("Invalid protocol")
|
||||
result = request("GET", f"/api/{endpoint}/logs")
|
||||
if isinstance(result, list):
|
||||
print("\n".join(str(line) for line in result[-60:]))
|
||||
else:
|
||||
print(json.dumps(result, indent=2)[-8000:])
|
||||
|
||||
|
||||
def generate_tls_certificate(lets_encrypt=False):
|
||||
domain = ask("Certificate domain")
|
||||
if not domain:
|
||||
raise CLIError("Domain required")
|
||||
payload = {"domain": domain}
|
||||
path = "/api/tls/generate-selfsigned"
|
||||
if lets_encrypt:
|
||||
payload["email"] = ask("Contact email")
|
||||
path = "/api/tls/letsencrypt"
|
||||
result = request("POST", path, payload)
|
||||
print(json.dumps(result, indent=2))
|
||||
|
||||
|
||||
def regenerate_dnstt_key():
|
||||
if confirm("Replace the DNSTT private key? Existing client keys will stop working."):
|
||||
print(json.dumps(request("POST", "/api/dnstt/genkey", {}), indent=2))
|
||||
|
||||
|
||||
def connection_menu():
|
||||
menu("CONNECTION MODES", {
|
||||
"1": ("Ports and transports", connection_status),
|
||||
"2": ("DNSTT / BHTTP / HCR / BTUN statistics", protocol_stats),
|
||||
"3": ("Edit listeners and protocol settings", lambda: edit_json("/api/server/config")),
|
||||
"4": ("TLS certificates", lambda: print(json.dumps(request("GET", "/api/tls/certs"), indent=2))),
|
||||
"5": ("DNSTT public key", lambda: print(json.dumps(request("GET", "/api/dnstt/pubkey"), indent=2))),
|
||||
"6": ("Protocol logs", protocol_logs),
|
||||
"7": ("Generate self-signed TLS certificate", generate_tls_certificate),
|
||||
"8": ("Request Let's Encrypt certificate", lambda: generate_tls_certificate(True)),
|
||||
"9": ("Regenerate DNSTT key", regenerate_dnstt_key),
|
||||
})
|
||||
|
||||
|
||||
def traffic_history():
|
||||
data = request("GET", "/api/vnstat")
|
||||
print(f"Today: {size(data.get('today_total_bytes', 0))} "
|
||||
f"This month: {size(data.get('month_total_bytes', 0))}")
|
||||
for label in ("daily", "monthly"):
|
||||
print(f"\n{label.title()} by interface:")
|
||||
for row in data.get(label) or []:
|
||||
print_wrapped(f"{row.get('period', '--')} {row.get('iface', '--')} "
|
||||
f"↓ {size(row.get('rx_bytes', 0))} "
|
||||
f"↑ {size(row.get('tx_bytes', 0))}", " ")
|
||||
|
||||
|
||||
def system_log_view():
|
||||
source = ask("Log source: panel/dnstt/xray", "panel").lower()
|
||||
if source not in ("panel", "dnstt", "xray"):
|
||||
raise CLIError("Choose panel, dnstt or xray")
|
||||
data = request("GET", f"/api/system/logs?source={source}&lines=100")
|
||||
print("\n".join(data.get("lines") or []))
|
||||
|
||||
|
||||
def observability_menu():
|
||||
menu("VPS AND TRAFFIC", {
|
||||
"1": ("VPS and live network rates", status),
|
||||
"2": ("SSH online / traffic report", user_report),
|
||||
"3": ("Xray online / clients", xray_inbounds),
|
||||
"4": ("Daily and monthly traffic", traffic_history),
|
||||
"5": ("System logs", system_log_view),
|
||||
"6": ("Build and update status", lambda: print(json.dumps(request("GET", "/api/system/update-status"), indent=2))),
|
||||
})
|
||||
|
||||
|
||||
def logs():
|
||||
subprocess.run(["journalctl", "-u", SERVICE, "-n", "80", "--no-pager"])
|
||||
|
||||
|
||||
def render_menu(title, options, vps_status=None, columns=None):
|
||||
cols = columns or terminal_columns()
|
||||
width = min(48, max(20, cols - 2))
|
||||
lines = []
|
||||
if vps_status is not None:
|
||||
lines.extend((render_vps_status(vps_status, cols), ""))
|
||||
heading = " DRAGONCORESSH │ " + title
|
||||
lines.extend(("═" * width, *textwrap.wrap(heading, width=width), "═" * width))
|
||||
for key, (label, _) in options.items():
|
||||
prefix = f" {key:>2} "
|
||||
parts = textwrap.wrap(label, width=width - len(prefix), break_long_words=True) or [""]
|
||||
lines.append(prefix + parts[0])
|
||||
lines.extend(" " * len(prefix) + part for part in parts[1:])
|
||||
lines.append(" 0 Back / exit")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def menu(title, options):
|
||||
while True:
|
||||
vps = collect_vps_status() if title == "MAIN MENU" else None
|
||||
print("\n" + render_menu(title, options, vps))
|
||||
choice = input("Choose: ").strip().lstrip("0") or "0"
|
||||
if choice == "0":
|
||||
return
|
||||
entry = options.get(choice)
|
||||
if not entry:
|
||||
print("Invalid option.")
|
||||
continue
|
||||
try:
|
||||
entry[1]()
|
||||
except (CLIError, ValueError, json.JSONDecodeError, OSError) as exc:
|
||||
print("Error:", exc)
|
||||
except KeyboardInterrupt:
|
||||
print("\nCancelled.")
|
||||
|
||||
|
||||
def ssh_menu():
|
||||
menu("SSH ACCOUNTS", {"1": ("List / online / usage", list_users),
|
||||
"2": ("Create (generated password)", create_user),
|
||||
"3": ("Create test (24 hours)", lambda: create_user(test_hours=24)),
|
||||
"4": ("Edit / renew / reset password", edit_user),
|
||||
"5": ("Detailed account report", user_report),
|
||||
"6": ("Reset traffic", reset_traffic),
|
||||
"7": ("Delete expired users", delete_expired_users),
|
||||
"8": ("Delete one user", delete_user)})
|
||||
|
||||
|
||||
def xray_action(action):
|
||||
request("POST", f"/api/xray/{action}", {})
|
||||
print(f"Xray {action} completed.")
|
||||
|
||||
|
||||
def xray_menu():
|
||||
menu("XRAY", {"1": ("Inbounds and clients", xray_inbounds),
|
||||
"2": ("Create client (generated UUID)", xray_create),
|
||||
"3": ("Edit client", xray_edit),
|
||||
"4": ("Reset client traffic", xray_reset_traffic),
|
||||
"5": ("Delete client", xray_delete),
|
||||
"6": ("Status", lambda: print(json.dumps(request("GET", "/api/xray/status"), indent=2))),
|
||||
"7": ("Edit Xray JSON", lambda: edit_json("/api/xray/config")),
|
||||
"8": ("Start Xray", lambda: xray_action("start")),
|
||||
"9": ("Stop Xray", lambda: xray_action("stop") if confirm("Stop Xray connections?") else None),
|
||||
"10": ("Restart Xray", lambda: xray_action("restart")),
|
||||
"11": ("Xray logs", lambda: print(json.dumps(request("GET", "/api/xray/logs"), indent=2)[-8000:])),
|
||||
"12": ("Repair Xray stats", lambda: request("POST", "/api/xray/stats/repair", {}) if confirm("Repair Xray statistics?") else None),
|
||||
"13": ("Share SSH/TLS ports (WS/XHTTP)", xray_shared_port)})
|
||||
|
||||
|
||||
def config_menu():
|
||||
menu("CONFIGURATION", {"1": ("Set SSH banner", set_banner),
|
||||
"2": ("Change SSH listener ports", set_ssh_ports),
|
||||
"3": ("Default bandwidth / connection limits", set_ssh_limits),
|
||||
"4": ("All SSH / DNSTT / BHTTP / BTUN / HCR settings", lambda: edit_json("/api/server/config")),
|
||||
"5": ("Xray JSON", lambda: edit_json("/api/xray/config")),
|
||||
"6": ("Telegram bot configuration", lambda: print(json.dumps(request("GET", "/api/bot/config"), indent=2))),
|
||||
"7": ("Managed servers", lambda: print(json.dumps(request("GET", "/api/servers"), indent=2)))})
|
||||
|
||||
|
||||
def api_menu():
|
||||
menu("API PASSWORD", {"1": ("View current password", lambda: print("API password:", api_password())),
|
||||
"2": ("Generate new password and restart service", rotate_api_password)})
|
||||
|
||||
|
||||
def main_menu_options():
|
||||
return {
|
||||
"1": ("SSH accounts", ssh_menu),
|
||||
"2": ("Xray accounts and service", xray_menu),
|
||||
"3": ("Connection modes and ports", connection_menu),
|
||||
"4": ("VPS status, users and traffic", observability_menu),
|
||||
"5": ("Configuration", config_menu),
|
||||
"6": ("API password (view / rotate)", api_menu),
|
||||
"7": ("Recent logs", logs),
|
||||
"8": ("Restart service", lambda: service_action("restart")),
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="DragonCoreSSH CLI administration")
|
||||
parser.add_argument("--mobile", action="store_true", help="force a 40-column phone layout")
|
||||
parser.add_argument("command", nargs="?", choices=("menu", "status", "users", "api-password", "logs"), default="menu")
|
||||
parser.add_argument("action", nargs="?", choices=("show", "change"))
|
||||
args = parser.parse_args()
|
||||
require_root()
|
||||
if args.mobile:
|
||||
os.environ["DRAGONCORE_COLUMNS"] = "40"
|
||||
if args.command == "api-password":
|
||||
if args.action == "show":
|
||||
print(api_password())
|
||||
elif args.action == "change":
|
||||
rotate_api_password()
|
||||
else:
|
||||
api_menu()
|
||||
elif args.action:
|
||||
parser.error("action is only valid with api-password")
|
||||
elif args.command == "users":
|
||||
list_users()
|
||||
elif args.command == "status":
|
||||
status()
|
||||
elif args.command == "logs":
|
||||
logs()
|
||||
else:
|
||||
menu("MAIN MENU", main_menu_options())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except (CLIError, KeyboardInterrupt) as error:
|
||||
print(f"Error: {error}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
Reference in New Issue
Block a user