Skip to content
HarvsGPublic

About

A python wrapper for the GL-inet firmware version 4 API

Resources

Stars

4 stars

Watchers

2 watching

Forks

Latest commit

 

History

152 Commits

Folders and files

Repository files navigation

gli4py

Tests Pylint CodeQL PyPI Version Python Versions License: GPL v3 Ruff pre-commit Home Assistant Integration

An asynchronous Python 3 API wrapper for GL.iNet routers running firmware version 4.x.

GL.iNet routers are built on OpenWrt, providing extensive customization combined with a user-friendly web interface and a locally accessible JSON-RPC API. gli4py provides a native, non-blocking Python interface to query and manage these devices.

Home Assistant Integration: gli4py is the core library powering the Home Assistant GL-iNet v4 Integration (ha-glinet4-integration).


Features

  • Authentication & Security

    • Asynchronous challenge-response authentication supporting MD5, SHA-256, and SHA-512 hashing algorithms computed off the main thread.
    • Dedicated exception hierarchy differentiating session expiry (TokenError), invalid credentials (AuthenticationError), and login rate-limiting (LockoutError).
    • Fast reachability check and login state tracking.
  • System Diagnostics & Control

    • Retrieve router model, MAC address, and firmware version.
    • Query CPU load, free memory, and real-time network traffic status.
    • Trigger graceful router reboot with optional delay.
    • Read and toggle the router's status LED indicators.
  • Network & Client Monitoring

    • List active connected clients with real-time bandwidth and signal stats.
    • Query DHCP leases (active and static clients).
    • Internet reachability verification and ping diagnostics.
  • Cellular / Modem (LTE & 5G)

    • Query modem hardware status and capabilities.
    • Retrieve SIM card details (IMEI, IMSI, ICCID).
    • Inspect cellular signal strength and carrier connection status.
  • Wi-Fi Management

    • Inspect 2.4 GHz and 5 GHz radio interfaces with optional key/credential redaction.
    • Enable or disable individual Wi-Fi interfaces.
  • VPN Management

    • WireGuard: List client configurations, retrieve active connection status, and start/stop WireGuard clients with automated schema adaptation across firmware versions (< 4.8 and >= 4.8).
    • Tailscale: Check Tailscale connection state, configuration, and start or stop the Tailscale service.
  • Typing

    • From version 0.1.0 all responses are typed at runtime meaning that your consumers can be sure that they are receiving the objects they hope for. This makes writing software a self-documenting doddle

Installation

pip install gli4py

For development or test environments requiring the in-process mock router and fixtures:

pip install "gli4py[mock]"

Quick Start

import asyncio
from gli4py import GLinet


async def main() -> None:
    # Initialize the client (default base URL is typically http://192.168.8.1/rpc)
    router = GLinet(base_url="http://192.168.8.1/rpc")

    # Check if the router is reachable
    if not await router.router_reachable():
        print("Router is not reachable.")
        return

    # Authenticate
    await router.login("root", "your_router_password")
    print(f"Logged in successfully. Session ID: {router.sid}")

    # Query system information
    info = await router.router_info()
    print(f"Device: {info.get('model')} (Firmware {info.get('firmware_version')})")

    # Query connected clients
    clients = await router.connected_clients()
    print(f"\nConnected clients ({len(clients)}):")
    for client in clients:
        print(f" - {client.get('name', 'Unknown')} ({client.get('ip')})")


if __name__ == "__main__":
    asyncio.run(main())

See examples.md for sample API payloads and responses.


Development Setup

Local Development

  1. Clone the repository:
git clone https://github.com/HarvsG/gli4py.git
cd gli4py
  1. Ensure Python 3.11+ is installed:
python3 -V
  1. Install Poetry (if not already installed):
pipx install poetry
# Or via official installer: curl -sSL https://install.python-poetry.org | python3 -
  1. Install dependencies with Poetry:
poetry install
  1. Install pre-commit hooks:
poetry run pre-commit install

Running Tests

  • Unit Tests (no router required, runs offline and in CI by default):
poetry run pytest
  • Live Hardware Tests (requires a physical GL.iNet router): Run live API tests by passing the --live flag, with target URL and password arguments:
# Using a password file (router_pwd in root or tests/):
poetry run pytest --live --url 192.168.8.1

# Or passing credentials directly:
poetry run pytest --live --url 192.168.8.1 --password your_password

# Enable disruptive tests (WiFi toggling, VPN toggling, reboot):
poetry run pytest --live --url 192.168.8.1 --disruptive-tests

Note: Router URL and password can also be configured via environment variables (ROUTER_URL, ROUTER_PASSWORD). In most development environments where PYTHONASYNCIODEBUG or PYTHONDEVMODE is set, prefix with PYTHONDEVMODE="" PYTHONASYNCIODEBUG="".

Code Formatting & Linting

# Run pre-commit checks on all files
poetry run pre-commit run --all-files

# Or run tools directly
poetry run ruff check .
poetry run ruff format --check .
poetry run pylint $(git ls-files '*.py')

Dev Setup Alongside Home Assistant & Custom Component

To test gli4py locally within a Home Assistant development container alongside the custom component:

  1. Clone gli4py into your VS Code /workspaces/ directory alongside core and glinet.

    Tip: In VS Code, press Ctrl + Shift + P (or Cmd + Shift + P on macOS) and choose Workspaces: Add Folder to Workspace... to add /workspaces/gli4py directly to your multi-root workspace alongside core and glinet.

  2. Inside your Home Assistant virtual environment (ha-env), install the editable package:
pip install -e /workspaces/gli4py
  1. Ensure the custom component has "/workspaces/gli4py/" in "python.analysis.extraPaths" in .vscode/settings.json.

API Enumeration

The repository includes gli-enumerate (or python3 -m gli4py.enumeration), a utility to probe a GL.iNet router to discover which API modules and methods are supported by the device's firmware and produce a JSON report.

Sensitive information (passwords, Wi-Fi keys, session tokens, serial numbers, and IP/MAC addresses) is automatically redacted from the output. By default, enumeration runs in a safe, read-only mode by skipping methods that alter router configuration or state.

Examples

Basic read-only probe:

gli-enumerate -u 192.168.8.1 -p your_router_password

Target a specific module or endpoint:

gli-enumerate -u 192.168.8.1 -p your_router_password -m wifi
gli-enumerate -u 192.168.8.1 -p your_router_password -e system.get_info

Share report or subsection via pastebin:

# Upload full report to paste.rs:
gli-enumerate -u 192.168.8.1 -p your_router_password --quiet | curl --data-binary @- https://paste.rs

# Or pipe a specific subsection using jq:
gli-enumerate -u 192.168.8.1 -p your_router_password --quiet | jq '.modules.wifi' | curl --data-binary @- https://paste.rs

Probe all endpoints (including write methods):

Caution: Probing write methods will alter the router's configuration or state.

gli-enumerate -u 192.168.8.1 -p your_router_password --no-read-only

For all available flags and options, run:

gli-enumerate --help
# or from a repository checkout:
python3 -m gli4py.enumeration --help

Related Projects


License

This project is licensed under the GNU General Public License v3.0.

About

A python wrapper for the GL-inet firmware version 4 API

Resources

Stars

4 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages