File: rconclt.py

package info (click to toggle)
python-rcon 2.4.9-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 348 kB
  • sloc: python: 1,224; makefile: 42; sh: 6
file content (75 lines) | stat: -rw-r--r-- 2,000 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
"""RCON client CLI."""

from argparse import ArgumentParser, Namespace
from logging import DEBUG, INFO, basicConfig, getLogger
from pathlib import Path

from rcon import battleye, source
from rcon.config import CONFIG_FILES, LOG_FORMAT, from_args
from rcon.errorhandler import ErrorHandler


__all__ = ["main"]


LOGGER = getLogger("rconclt")


def get_args() -> Namespace:
    """Parse and return the command line arguments."""

    parser = ArgumentParser(description="A Minecraft RCON client.")
    parser.add_argument("server", help="the server to connect to")
    parser.add_argument(
        "-B",
        "--battleye",
        action="store_true",
        help="use BattlEye RCon instead of Source RCON",
    )
    parser.add_argument(
        "-c",
        "--config",
        type=Path,
        metavar="file",
        default=CONFIG_FILES,
        help="the configuration file",
    )
    parser.add_argument(
        "-d", "--debug", action="store_true", help="print additional debug information"
    )
    parser.add_argument(
        "-t",
        "--timeout",
        type=float,
        metavar="seconds",
        help="connection timeout in seconds",
    )
    parser.add_argument("command", help="command to execute on the server")
    parser.add_argument(
        "argument", nargs="*", default=(), help="arguments for the command"
    )
    return parser.parse_args()


def run() -> None:
    """Run the RCON client."""

    args = get_args()
    basicConfig(format=LOG_FORMAT, level=DEBUG if args.debug else INFO)
    host, port, passwd = from_args(args)
    client_cls = battleye.Client if args.battleye else source.Client

    with client_cls(host, port, timeout=args.timeout) as client:
        client.login(passwd)

        if text := client.run(args.command, *args.argument):
            print(text, flush=True)


def main() -> int:
    """Run the main script with exceptions handled."""

    with ErrorHandler(LOGGER) as handler:
        run()

    return handler.exit_code