zte-wrapper 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,225 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[codz]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py.cover
50
+ *.lcov
51
+ .hypothesis/
52
+ .pytest_cache/
53
+ cover/
54
+
55
+ # Translations
56
+ *.mo
57
+ *.pot
58
+
59
+ # Django stuff:
60
+ *.log
61
+ local_settings.py
62
+ db.sqlite3
63
+ db.sqlite3-journal
64
+
65
+ # Flask stuff:
66
+ instance/
67
+ .webassets-cache
68
+
69
+ # Scrapy stuff:
70
+ .scrapy
71
+
72
+ # Sphinx documentation
73
+ docs/_build/
74
+
75
+ # PyBuilder
76
+ .pybuilder/
77
+ target/
78
+
79
+ # Jupyter Notebook
80
+ .ipynb_checkpoints
81
+
82
+ # IPython
83
+ profile_default/
84
+ ipython_config.py
85
+
86
+ # pyenv
87
+ # For a library or package, you might want to ignore these files since the code is
88
+ # intended to run in multiple environments; otherwise, check them in:
89
+ # .python-version
90
+
91
+ # pipenv
92
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
93
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
94
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
95
+ # install all needed dependencies.
96
+ # Pipfile.lock
97
+
98
+ # UV
99
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
100
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
101
+ # commonly ignored for libraries.
102
+ # uv.lock
103
+
104
+ # poetry
105
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
106
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
107
+ # commonly ignored for libraries.
108
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
109
+ # poetry.lock
110
+ # poetry.toml
111
+
112
+ # pdm
113
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
114
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
115
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
116
+ # pdm.lock
117
+ # pdm.toml
118
+ .pdm-python
119
+ .pdm-build/
120
+
121
+ # pixi
122
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
123
+ # pixi.lock
124
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
125
+ # in the .venv directory. It is recommended not to include this directory in version control.
126
+ .pixi/*
127
+ !.pixi/config.toml
128
+
129
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
130
+ __pypackages__/
131
+
132
+ # Celery stuff
133
+ celerybeat-schedule*
134
+ celerybeat.pid
135
+
136
+ # Redis
137
+ *.rdb
138
+ *.aof
139
+ *.pid
140
+
141
+ # RabbitMQ
142
+ mnesia/
143
+ rabbitmq/
144
+ rabbitmq-data/
145
+
146
+ # ActiveMQ
147
+ activemq-data/
148
+
149
+ # SageMath parsed files
150
+ *.sage.py
151
+
152
+ # Environments
153
+ .env
154
+ .envrc
155
+ .venv
156
+ .test-venv
157
+ env/
158
+ venv/
159
+ ENV/
160
+ env.bak/
161
+ venv.bak/
162
+
163
+ # Spyder project settings
164
+ .spyderproject
165
+ .spyproject
166
+
167
+ # Rope project settings
168
+ .ropeproject
169
+
170
+ # mkdocs documentation
171
+ /site
172
+
173
+ # mypy
174
+ .mypy_cache/
175
+ .dmypy.json
176
+ dmypy.json
177
+
178
+ # Pyre type checker
179
+ .pyre/
180
+
181
+ # pytype static type analyzer
182
+ .pytype/
183
+
184
+ # Cython debug symbols
185
+ cython_debug/
186
+
187
+ # PyCharm
188
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
189
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
190
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
191
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
192
+ # .idea/
193
+
194
+ # Abstra
195
+ # Abstra is an AI-powered process automation framework.
196
+ # Ignore directories containing user credentials, local state, and settings.
197
+ # Learn more at https://abstra.io/docs
198
+ .abstra/
199
+
200
+ # Visual Studio Code
201
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
202
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
203
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
204
+ # you could uncomment the following to ignore the entire vscode folder
205
+ # .vscode/
206
+ # Temporary file for partial code execution
207
+ tempCodeRunnerFile.py
208
+
209
+ # Ruff stuff:
210
+ .ruff_cache/
211
+
212
+ # PyPI configuration file
213
+ .pypirc
214
+
215
+ # Marimo
216
+ marimo/_static/
217
+ marimo/_lsp/
218
+ __marimo__/
219
+
220
+ # Streamlit
221
+ .streamlit/secrets.toml
222
+
223
+ .password
224
+
225
+ test.py
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 ctih1
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1,97 @@
1
+ Metadata-Version: 2.5
2
+ Name: zte-wrapper
3
+ Version: 1.0.0
4
+ Summary: A wrapper that lets you interact with the new ZTE WebUI
5
+ Project-URL: Homepage, https://github.com/ctih1/zte-wrapper
6
+ Project-URL: Issues, https://github.com/ctih1/zte-wrapper/issues
7
+ Author-email: ctih1 <contact@ctih1.fi>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Requires-Python: >=3.9
13
+ Requires-Dist: aiohttp
14
+ Description-Content-Type: text/markdown
15
+
16
+ # ZTE-Wrapper
17
+
18
+ An API wrapper for modern ZTE routers using a more advanced authentication method. This has only been tested on an MC888B. If you have any feedback, please share!
19
+
20
+ ## Features
21
+ "Support" in this case means that it can be controlled via the library.
22
+
23
+
24
+ | Feature | Support |
25
+ | ------------------------------------- | ------- |
26
+ | Create portforward rules | ✅ |
27
+ | Delete portforward rules | ✅ |
28
+ | List portforward rules | ✅ |
29
+ | Send SMS | ✅ |
30
+ | Read SMS | ✅ |
31
+ | List wireless devices | ✅ |
32
+ | List wired devices | ✅ |
33
+ | Get signal strength | ✅ |
34
+ | Band information | ✅ |
35
+ | Usage statistics | ✅ |
36
+ | Firewall (e.g. domain/port filtering) | ❌ |
37
+ | DHCP Settings | ✅ |
38
+ | MAC-IP bindings | ✅ |
39
+ | DDNS settings | ✅ |
40
+ | VPN settings | ❌ |
41
+ | Network tools (e.g. traceroute/ping) | ✅ |
42
+ | "Preferred position" tools | ❌* |
43
+
44
+ *: Not planning on implementing
45
+
46
+
47
+ <details>
48
+ <summary>Features as overlayed on web panel</summary>
49
+
50
+ (based on commit a7baa3b)
51
+
52
+
53
+ ![Network tab](screenshots/network.png)
54
+
55
+
56
+ ![WiFi tab](screenshots/wifi.png)
57
+
58
+
59
+ ![Devices tab](screenshots/devices.png)
60
+
61
+
62
+ ![Data usage tab](screenshots/datausage.png)
63
+
64
+
65
+ ![Router tab](screenshots/router.png)
66
+
67
+
68
+ ![SMS tab](screenshots/sms.png)
69
+
70
+
71
+ ![Security tab](screenshots/security.png)
72
+
73
+
74
+ ![System tab](screenshots/system.png)
75
+
76
+ </details>
77
+
78
+ ## Roadmap
79
+ 1. ~~Implement DDNS-settings~~
80
+
81
+ 2. Publish onto PyPI
82
+
83
+ 3. More reliable error handling
84
+
85
+ 4. Implement rest of the features
86
+
87
+ 5. Implement better documentation
88
+
89
+ 6. Write tests
90
+
91
+ ## Notes
92
+ - When referring to "megabytes" or "bytes", they are in base 2 format (e.g. 1Gib = 1024Mib)
93
+ - Authenticating (aka. running any of the API calls) logs off other clients from the admin web panel.
94
+ - Even thought the `apn` wrapper *should* be able to change DNS settings, I've found that it doesn't work. This might have been patched in an update?
95
+
96
+ ## Why?
97
+ I wanted to harvest statistics from the router to my Prometheus instance. I might actually rewrite the entire admin webpage since it's kind of horrible
@@ -0,0 +1,82 @@
1
+ # ZTE-Wrapper
2
+
3
+ An API wrapper for modern ZTE routers using a more advanced authentication method. This has only been tested on an MC888B. If you have any feedback, please share!
4
+
5
+ ## Features
6
+ "Support" in this case means that it can be controlled via the library.
7
+
8
+
9
+ | Feature | Support |
10
+ | ------------------------------------- | ------- |
11
+ | Create portforward rules | ✅ |
12
+ | Delete portforward rules | ✅ |
13
+ | List portforward rules | ✅ |
14
+ | Send SMS | ✅ |
15
+ | Read SMS | ✅ |
16
+ | List wireless devices | ✅ |
17
+ | List wired devices | ✅ |
18
+ | Get signal strength | ✅ |
19
+ | Band information | ✅ |
20
+ | Usage statistics | ✅ |
21
+ | Firewall (e.g. domain/port filtering) | ❌ |
22
+ | DHCP Settings | ✅ |
23
+ | MAC-IP bindings | ✅ |
24
+ | DDNS settings | ✅ |
25
+ | VPN settings | ❌ |
26
+ | Network tools (e.g. traceroute/ping) | ✅ |
27
+ | "Preferred position" tools | ❌* |
28
+
29
+ *: Not planning on implementing
30
+
31
+
32
+ <details>
33
+ <summary>Features as overlayed on web panel</summary>
34
+
35
+ (based on commit a7baa3b)
36
+
37
+
38
+ ![Network tab](screenshots/network.png)
39
+
40
+
41
+ ![WiFi tab](screenshots/wifi.png)
42
+
43
+
44
+ ![Devices tab](screenshots/devices.png)
45
+
46
+
47
+ ![Data usage tab](screenshots/datausage.png)
48
+
49
+
50
+ ![Router tab](screenshots/router.png)
51
+
52
+
53
+ ![SMS tab](screenshots/sms.png)
54
+
55
+
56
+ ![Security tab](screenshots/security.png)
57
+
58
+
59
+ ![System tab](screenshots/system.png)
60
+
61
+ </details>
62
+
63
+ ## Roadmap
64
+ 1. ~~Implement DDNS-settings~~
65
+
66
+ 2. Publish onto PyPI
67
+
68
+ 3. More reliable error handling
69
+
70
+ 4. Implement rest of the features
71
+
72
+ 5. Implement better documentation
73
+
74
+ 6. Write tests
75
+
76
+ ## Notes
77
+ - When referring to "megabytes" or "bytes", they are in base 2 format (e.g. 1Gib = 1024Mib)
78
+ - Authenticating (aka. running any of the API calls) logs off other clients from the admin web panel.
79
+ - Even thought the `apn` wrapper *should* be able to change DNS settings, I've found that it doesn't work. This might have been patched in an update?
80
+
81
+ ## Why?
82
+ I wanted to harvest statistics from the router to my Prometheus instance. I might actually rewrite the entire admin webpage since it's kind of horrible
@@ -0,0 +1,33 @@
1
+ [project]
2
+ name = "zte-wrapper"
3
+ version = "1.0.0"
4
+ authors = [
5
+ { name="ctih1", email="contact@ctih1.fi" },
6
+ ]
7
+ description = "A wrapper that lets you interact with the new ZTE WebUI"
8
+ readme = "README.md"
9
+ requires-python = ">=3.9"
10
+ classifiers = [
11
+ "Programming Language :: Python :: 3",
12
+ "Operating System :: OS Independent",
13
+ ]
14
+ dependencies = [
15
+ "aiohttp"
16
+ ]
17
+ license = "MIT"
18
+ license-files = ["LICEN[CS]E*"]
19
+
20
+ [project.urls]
21
+ Homepage = "https://github.com/ctih1/zte-wrapper"
22
+ Issues = "https://github.com/ctih1/zte-wrapper/issues"
23
+
24
+ [build-system]
25
+ requires = ["hatchling >= 1.26"]
26
+ build-backend = "hatchling.build"
27
+
28
+ [tool.hatch.build.targets.sdist]
29
+ exclude = [
30
+ ".vscode",
31
+ "notes",
32
+ "screenshots"
33
+ ]
@@ -0,0 +1,8 @@
1
+ [pytest]
2
+ pythonpath = src/
3
+
4
+ log_cli = 1
5
+ log_cli_level = INFO
6
+ log_cli_format = %(asctime)s [%(levelname)8s] %(message)s (%(filename)s:%(lineno)s)
7
+ log_cli_date_format=%Y-%m-%d %H:%M:%S
8
+ addopts = --cov=. --cov-report=xml
@@ -0,0 +1,5 @@
1
+ from zte_wrapper.helpers import utf_16_encode, utf_16_decode
2
+
3
+
4
+ def test_utf_16_be_encoding():
5
+ assert utf_16_decode(utf_16_encode("hello")) == "hello"
File without changes
@@ -0,0 +1,167 @@
1
+ import logging
2
+ import aiohttp
3
+ from hashlib import sha256
4
+ import urllib.parse
5
+ import time
6
+ import json
7
+ from typing import Literal, Dict, Any, Tuple
8
+ from copy import deepcopy
9
+
10
+ logger = logging.getLogger("zte")
11
+
12
+ GOFORM_COMMANDS = Literal["goform_get_cmd_process", "goform_set_cmd_process"]
13
+ HEADERS = {
14
+ "Accept": "application/json, text/javascript, */*; q=0.01",
15
+ "Accept-Encoding": "gzip, deflate",
16
+ "Accept-Language": "en-US,en;q=0.5",
17
+ "Connection": "keep-alive",
18
+ "Host": "192.168.32.1",
19
+ "Referer": "http://192.168.32.1/",
20
+ "Sec-Gpc": "1",
21
+ "User-Agent": "Mozilla",
22
+ "X-Requested-With": "XMLHttpRequest",
23
+ }
24
+
25
+
26
+ def zte_sha256_string(input: str) -> str:
27
+ return sha256(input.encode("UTF-8")).hexdigest().upper()
28
+
29
+
30
+ class ZTEAuthWrapper:
31
+ def __init__(self, webui_address: str, password: str) -> None:
32
+ self.address: str = webui_address
33
+ self.__password = zte_sha256_string(password)
34
+ self.__auth_code: str | None = None
35
+
36
+ self.headers = HEADERS
37
+ self.headers["Referer"] = f"http://{self.address}/"
38
+ self.headers["Host"] = self.address
39
+
40
+ self.session: aiohttp.ClientSession | None = None
41
+
42
+ def construct_url(self, command: GOFORM_COMMANDS, args: Dict[str, Any]) -> str:
43
+ base_url = f"http://{self.address}/goform/{command}/?"
44
+
45
+ url = base_url + urllib.parse.urlencode(
46
+ {k: urllib.parse.quote(str(v)) for k, v in args.items()}
47
+ )
48
+
49
+ logger.debug(f"Constructed url {url}")
50
+ return url
51
+
52
+ def get_timestamp(self) -> int:
53
+ return round(time.time() * 1000)
54
+
55
+ async def __get_ld(self) -> str:
56
+ async with aiohttp.ClientSession() as session:
57
+ res = await session.get(
58
+ self.construct_url(
59
+ "goform_get_cmd_process",
60
+ {"isTest": "false", "cmd": "LD", "_": self.get_timestamp()},
61
+ ),
62
+ headers=self.headers,
63
+ )
64
+
65
+ logger.info("Got LD token")
66
+ return json.loads((await res.text())).get(
67
+ "LD"
68
+ ) # json.loads instead of res.json() because the stupid API returns the stuff as text/html
69
+
70
+ async def __get_rd0_rd1(self) -> Tuple[str, str]:
71
+ res = await self.request(
72
+ "GET",
73
+ self.construct_url(
74
+ "goform_get_cmd_process",
75
+ {
76
+ "isTest": "false",
77
+ "cmd": "cr_version,wa_inner_version",
78
+ "multi_data": "1",
79
+ },
80
+ ),
81
+ )
82
+ res_text = await res.text()
83
+ logger.debug(f"Retrieved rd0 and rd1: {res_text}")
84
+
85
+ data = json.loads(res_text)
86
+ return (data["wa_inner_version"], data["cr_version"])
87
+
88
+ async def __get_rd_token(self) -> str:
89
+ res = await self.request(
90
+ "GET",
91
+ self.construct_url(
92
+ "goform_get_cmd_process",
93
+ {"isTest": "false", "cmd": "RD", "_": self.get_timestamp()},
94
+ ),
95
+ )
96
+ logger.debug("")
97
+ return json.loads(await res.text())["RD"]
98
+
99
+ # please check notes/tokens.md if it breaks, it might help you a little
100
+ async def construct_ad_token(self) -> str:
101
+ rd0, rd1 = await self.__get_rd0_rd1()
102
+ first_step = zte_sha256_string(rd0 + rd1)
103
+ rd_token = await self.__get_rd_token()
104
+ return zte_sha256_string(first_step + rd_token)
105
+
106
+ async def refresh_auth(self) -> str:
107
+ ld_token: str = await self.__get_ld()
108
+ hashed_password: str = zte_sha256_string(self.__password + ld_token)
109
+
110
+ async with aiohttp.ClientSession() as session:
111
+ logger.debug("Refreshing authentication")
112
+ res = await session.post(
113
+ self.construct_url("goform_set_cmd_process", {}),
114
+ data={
115
+ "isTest": "false",
116
+ "goformId": "LOGIN",
117
+ "password": hashed_password,
118
+ },
119
+ headers=self.headers,
120
+ )
121
+ self.__auth_code = str(res.cookies.get("stok"))
122
+
123
+ return self.__auth_code
124
+
125
+ async def confirm_auth(self) -> bool:
126
+ res = await self.request(
127
+ "GET",
128
+ self.construct_url(
129
+ "goform_get_cmd_process",
130
+ {"isTest": "false", "cmd": "date_month", "_": self.get_timestamp()},
131
+ ),
132
+ skip_auth_check=True,
133
+ )
134
+
135
+ result = bool(json.loads(await res.text())["date_month"])
136
+ logger.debug(f"Logged in? {result}")
137
+
138
+ return result
139
+
140
+ async def request(
141
+ self, method: Literal["GET", "POST"], *args, **kwargs
142
+ ) -> aiohttp.ClientResponse:
143
+ if not self.session:
144
+ self.session = aiohttp.ClientSession()
145
+
146
+ headers = deepcopy(self.headers)
147
+ headers["Cookie"] = f'stok="{self.__auth_code}"'
148
+
149
+ if kwargs.get("skip_auth_check"):
150
+ logger.debug("Skipping authentication checks...")
151
+ del kwargs["skip_auth_check"]
152
+ else:
153
+ if not await self.confirm_auth():
154
+ await self.refresh_auth()
155
+ headers["Cookie"] = f'stok="{self.__auth_code}"'
156
+
157
+ if method == "GET":
158
+ res = await self.session.get(*args, **kwargs, headers=headers)
159
+ elif method == "POST":
160
+ res = await self.session.post(*args, **kwargs, headers=headers)
161
+
162
+ return res
163
+
164
+ async def close(self) -> None:
165
+ logger.info("Closign aiohttp client")
166
+ if self.session:
167
+ await self.session.close()
@@ -0,0 +1,17 @@
1
+ from datetime import datetime
2
+
3
+
4
+ def utf_16_decode(inp: str) -> str:
5
+ return bytes.fromhex(inp).decode("utf-16-be")
6
+
7
+
8
+ def utf_16_encode(inp: str) -> str:
9
+ return inp.encode("utf-16-be").hex().upper()
10
+
11
+
12
+ def get_zte_timestring(timezone_offset: int) -> str:
13
+ now = datetime.now()
14
+
15
+ output = f"{str(now.year)[2:]};{now.month};{now.day};{now.hour+1};{now.minute};{now.second};+{timezone_offset}"
16
+
17
+ return output