-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathWebScriptsClient.py
More file actions
1408 lines (1149 loc) · 42.2 KB
/
WebScriptsClient.py
File metadata and controls
1408 lines (1149 loc) · 42.2 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
###################
# Official WebScripts client. Implements client for default WebScripts features.
# Copyright (C) 2021 Maurice Lambert
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
###################
"""
This package implements the "official" WebScripts client.
This package implements client for default WebScripts features.
Basic:
~# python -m WebScriptsClient -u Admin -p Admin exec "show_license.py" http://127.0.0.1:8000/web/auth/
ExitCode: 1
Errors: USAGE: show_license.py [part required string]
~# python -m WebScriptsClient -u Admin -p Admin exec "show_license.py copyright" http://127.0.0.1:8000/web/auth/
WebScripts Copyright (C) 2021, 2022 Maurice Lambert
This program comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to redistribute it
under certain conditions.
ExitCode: 0
Errors:
~# python -m WebScriptsClient -u Admin -p Admin exec "show_license.py copyright error" http://127.0.0.1:8000/web/auth/
WebScripts Copyright (C) 2021, 2022 Maurice Lambert
This program comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to redistribute it
under certain conditions.
ExitCode: 2
Errors: ERROR: unexpected arguments ['error']
Full examples:
~# python WebScriptsClient.py -v -u Admin -p Admin test http://127.0.0.1:8000/web/
~# python WebScriptsClient.py -v -u Admin -p Admin download -f "LICENSE.txt" "LICENSE.txt" http://127.0.0.1:8000/web/
~# python WebScriptsClient.py -v -u Admin -p Admin download -s -f "LICENSE.txt" "LICENSE.txt" http://127.0.0.1:8000/web/
~# python WebScriptsClient.py -v -u Admin -p Admin download -o test.txt -f "LICENSE.txt" "LICENSE.txt" http://127.0.0.1:8000/web/
-# python -c "print('test')" > test.txt
~# python WebScriptsClient.py -v -u Admin -p Admin upload -r 1000 -w 1000 -d 1000 -f test.txt test.txt http://127.0.0.1:8000/web/
~# python WebScriptsClient.py -v -u Admin -p Admin upload -6 -b -C -H -c dGVzdA== test.txt http://127.0.0.1:8000/web/
~# python -c "print('test')" | python WebScriptsClient.py -v -u Admin -p Admin upload test.txt http://127.0.0.1:8000/web/
~# python WebScriptsClient.py -v -u Admin -P request -s title -n Maurice -r request -c 500 http://127.0.0.1:8000/web/
~# python WebScriptsClient.py -v -A exec "test_config.py" http://127.0.0.1:8000/web/
~# python -c "print('test')" | python WebScriptsClient.py -v -u Admin -p Admin exec "test_config.py" -o test.txt -I http://127.0.0.1:8000/web/
~# python -c "print('test')" > test.txt
~# python WebScriptsClient.py -v -u Admin -p Admin exec "test_config.py" -I test.txt http://127.0.0.1:8000/web/
~# python WebScriptsClient.py -v -u Admin -p Admin exec "test_config.py --test test3 --test4 -t" -i "test1" "test2" http://127.0.0.1:8000/web/
~# python -m WebScriptsClient -u Admin -p Admin exec password_generator.py http://127.0.0.1:8000/web/auth/
~# python -m WebScriptsClient -u Admin -p Admin exec "show_license.py license" http://127.0.0.1:8000/web/auth/
~# python -m WebScriptsClient -u Admin -p Admin exec "show_license.py copyright codeheader" http://127.0.0.1:8000/web/auth/
~# python WebScriptsClient.py -v info http://127.0.0.1:8000/web/
~# python WebScriptsClient.py -a AdminAdminAdminAdminAdminAdminAdminAdminAdminAdminAdminAdminAdminAdminAdminAdminAdminAdminAdminAdminAdminAdminAdminAdminAdminAdminAdminAdminAdminAdminAdminAdmin info -a -c -d -s "test_config.py" "/auth/" http://127.0.0.1:8000/web/
>>> client = WebScriptsClient("http://127.0.0.1:8000/web/", username="user", password="pass", api_key="api key")
>>> client.auth()
>>> scripts = client.get_scripts(refresh=False)
>>> client.upload("upload.txt", open("upload.txt"), no_compression=False, is_base64=False, hidden=False, binary=False, read_permissions=0, write_permissions=1000, delete_permissions=1000)
>>> file = client.download("upload.txt", save=True)
>>> client.request("Access", "I need access to test_config.py", "Maurice LAMBERT", error_code=500)
>>> arguments = client.args_command_to_webscripts(["--test", "test1", "test3"])
>>> inputs = client.args_command_to_webscripts(["--test", "test1", "test3"], is_inputs=True)
>>> for output, error, code in client.execute_script("test_config.py", arguments, inputs): print(output, end="")
>>> print(f"Error code: {code}")
>>> print(f"Error: {error}")
"""
__version__ = "0.0.4"
__author__ = "Maurice Lambert"
__author_email__ = "mauricelambert434@gmail.com"
__maintainer__ = "Maurice Lambert"
__maintainer_email__ = "mauricelambert434@gmail.com"
__description__ = """
This package implements the "official" WebScripts client.
This package implements client for default WebScripts features.
"""
license = "GPL-3.0 License"
__url__ = "https://github.com/mauricelambert/WebScriptsClient"
copyright = """
WebScriptsClient Copyright (C) 2022 Maurice Lambert
This program comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to redistribute it
under certain conditions.
"""
__license__ = license
__copyright__ = copyright
__all__ = [
"WebScriptsClient",
"WebScriptsError",
"WebScriptsPermissionsError",
"WebScriptsScriptNotFoundError",
"WebScriptsAuthenticationError",
]
from urllib.request import (
build_opener,
Request,
OpenerDirector,
HTTPDefaultErrorHandler,
HTTPRedirectHandler,
)
from platform import python_version, uname, python_implementation
from logging import StreamHandler, Formatter, Logger, getLogger
from argparse import ArgumentParser, Namespace, FileType
from typing import TypeVar, Tuple, List, Dict, Union
from http.client import HTTPResponse, HTTPMessage
from collections.abc import Callable, Iterator
from gzip import open as gzipopen, GzipFile
from ssl import _create_unverified_context
from sys import exit, stdout, argv, stdin
from urllib.response import addinfourl
from io import TextIOWrapper, BytesIO
from functools import wraps, partial
from tempfile import TemporaryFile
from urllib.parse import urlparse
from urllib.error import URLError
from operator import itemgetter
from shutil import copyfileobj
from json import load, dumps
from base64 import b64encode
from getpass import getpass
from shlex import shlex
Json = TypeVar("Json", dict, list, str, int, float, bool, None)
def get_custom_logger() -> Logger:
"""
This function create a custom logger.
"""
logger = getLogger(__name__)
formatter = Formatter(
fmt=(
"%(asctime)s%(levelname)-9s(%(levelno)s) "
"{%(name)s - %(filename)s:%(lineno)d} %(message)s"
),
datefmt="[%Y-%m-%d %H:%M:%S] ",
)
stream = StreamHandler(stream=stdout)
stream.setFormatter(formatter)
logger.addHandler(stream)
return logger
class __JsonPython:
"""
This class create object and subobject from Json Structure.
"""
def __init__(self, data: Json):
logger_debug(f"Creating a {self.__class__.__name__}...")
if isinstance(data, dict):
logger_info("A dict is detected.")
for key, value in data.items():
if isinstance(value, dict):
logger_info("Launch a recursive instance.")
setattr(self, key.replace("-", "_"), NoName(value))
else:
setattr(self, key.replace("-", "_"), value)
logger_debug("Add __dict__ methods...")
dict_ = self.__dict__
for attribute in dir(data):
if isinstance(getattr(data, attribute), Callable) and (
not attribute.startswith("__")
and not attribute.endswith("__")
):
setattr(self, attribute, getattr(dict_, attribute))
logger_info("__dict__ methods is added.")
class Script(__JsonPython):
pass
class Argument(__JsonPython):
pass
class NoName(__JsonPython):
pass
class WebScriptsError(Exception):
pass
class WebScriptsPermissionsError(WebScriptsError):
pass
class WebScriptsScriptNotFoundError(WebScriptsError):
pass
class WebScriptsAuthenticationError(WebScriptsError):
pass
class GETTER:
"""
This class implements the optimized itemgetter.
"""
output = itemgetter("stdout", "stderr", "code")
class WebScriptsOpener(HTTPDefaultErrorHandler, HTTPRedirectHandler):
"""
This class implements a WebScripts opener to open URLs with urllib.
"""
def http_error_403(
self,
request: Request,
response: HTTPResponse,
code: int,
message: str,
headers: HTTPMessage,
) -> None:
"""
This function implements action on HTTP error 403.
"""
log = f"HTTP error {code}: {message} -> you do not have permissions."
url = request.get_full_url()
command = (
f"{argv[0]} [(-a <KEY>|-A|-u <USER> -p <PASSWORD>|-u -P)]"
" request -n [name] -s Access -r"
f' "I need access to this script." {url}'
)
logger_error(log)
print(
f"{log}\nYou can request access to the administrator "
f"with:\n\t{command}"
)
raise WebScriptsPermissionsError(
"You do not have access to this script."
)
def http_error_404(
self,
request: Request,
response: HTTPResponse,
code: int,
message: str,
headers: HTTPMessage,
) -> None:
"""
This function implements action on HTTP error 404.
"""
log = f"HTTP error {code}: {message} -> this script does not exists."
logger_error(log)
print(log)
raise WebScriptsScriptNotFoundError("This script does not exists.")
def http_error_302(
self,
request: Request,
response: HTTPResponse,
code: int,
message: str,
headers: HTTPMessage,
) -> None:
"""
This function implements action on HTTP error 302
used to redirect on the auth page.
"""
log = f"HTTP error {code}: {message} -> you do not have permissions."
url = request.get_full_url()
command = (
f"{argv[0]} [(-a <KEY>|-A|-u <USER> -p <PASSWORD>|-u -P)]"
" request -n [name] -s Access -r"
f' "I need access to this script." {url}'
)
logger_error(log)
print(
f"{log}\nYou can request access to the administrator "
f"with:\n\t{command}"
)
raise WebScriptsPermissionsError(
"You do not have access to this script."
)
class WebScriptsAuthOpener(HTTPRedirectHandler):
def http_error_302(
self,
request: Request,
response: HTTPResponse,
code: int,
message: str,
headers: HTTPMessage,
) -> addinfourl:
"""
This function implements action on HTTP error 302
used to redirect user on the Web page after authentication.
"""
logger_debug("Capture redirect response (/auth/ -> /web/)...")
return addinfourl(response, headers, request.get_full_url(), code)
opener: OpenerDirector = build_opener(WebScriptsAuthOpener)
authopener: Callable = opener.open
opener: OpenerDirector = build_opener(WebScriptsOpener)
urlopen: Callable = opener.open
logger: Logger = get_custom_logger()
logger_debug: Callable = logger.debug
logger_info: Callable = logger.info
logger_warning: Callable = logger.warning
logger_error: Callable = logger.error
logger_critical: Callable = logger.critical
class WebScriptsClient:
"""
This class implements the "official" WebScripts client.
"""
def __init__(
self,
url: str,
username: str = None,
password: str = None,
api_key: str = None,
):
logger_debug("Creating a WebScriptsClient...")
logger_debug("Get URL...")
url = urlparse(url)
url = self.url = f"{url.scheme}://{url.netloc}"
self.username = username
self.password = password
self.api_key = api_key
logger_info("URL and credentials are save as attribute.")
self.api_data = None
self.scripts: List[Script] = None
system = uname()
headers = self.headers = {
"User-Agent": (
f"WebScriptsClient/{__version__} (Python"
f"[{python_implementation()}]/{python_version()};"
f" {system.system}/{system.release}) {system.node}"
),
"Origin": url,
}
logger_debug("Build credentials...")
if username is not None and password is not None:
logger_debug("Build BasicAuth...")
credentials = self.credentials = b64encode(
f"{username}:{password}".encode()
).decode()
headers["Authorization"] = f"Basic {credentials}"
if api_key is not None:
logger_debug("Add Api-Key...")
headers["Api-Key"] = api_key
def auth(self, *args, **kwargs) -> None:
"""
This function requests the /auth/ script to get a API Token.
args and kwargs are sent to urllib.request.urlopen function.
"""
logger_debug("Build request for /auth/ script...")
username = self.username
password = self.password
api_key = self.api_key
headers = self.headers
arguments = None
if username and password:
logger_debug(
"Build arguments with username and password and"
" remove Authorization header..."
)
arguments = {"--username": username, "--password": password}
del headers["Authorization"]
if api_key:
logger_debug(
"Build arguments with API key and remove Api-Key header..."
)
arguments = {"--api-key": api_key}
del headers["Api-Key"]
if arguments is None:
logger_warning(
"No credentials found, do not perform authentication."
)
return None
logger_debug("Send request for /auth/ script...")
response = self.execute(
"/auth/", arguments, {}, *args, urlopen=authopener, **kwargs
)
logger_debug("Response received.")
cookie = response.headers["Set-Cookie"]
logger_debug("Cookie found.")
if cookie.startswith("SessionID=0:"):
logger_error("Authentication error, your are not authenticated.")
raise WebScriptsAuthenticationError(
"Authentication error, your are not authenticated."
)
elif not cookie.startswith("SessionID="):
raise WebScriptsAuthenticationError(
"Received cookie is not valid."
)
headers["Api-Token"] = cookie
logger_info("You are authenticated.")
def get_scripts(
self, *args, refresh: bool = False, **kwargs
) -> List[Script]:
"""
This function requests WebScripts API to build Scripts and Arguments.
"""
logger_debug(
"Request /api/ (informations about scripts and arguments)."
)
api_data = self.api_data
if refresh or not api_data:
logger_debug("Send request.")
response = urlopen(
Request(f"{self.url}/api/", headers=self.headers),
*args,
**kwargs,
)
api_data = self.api_data = load(response)
scripts = self.scripts = []
for script_dict in api_data.values():
arguments = script_dict.pop("args")
script = Script(script_dict)
script.arguments = [
Argument(argument_dict) for argument_dict in arguments
]
scripts.append(script)
logger_info("Scripts object are built.")
return scripts
def execute_script(
self,
script_name: Union[Script, str],
arguments: Dict[str, Json],
inputs: Dict[str, Json],
*args,
**kwargs,
) -> Iterator[Tuple[str, str, int]]:
"""
This function requests a WebScripts script and returns output.
args and kwargs are sent to urllib.request.urlopen function.
"""
if isinstance(script_name, Script):
logger_debug("Get name from Script...")
script_name = script_name.name
logger_debug("Build the path of the script...")
path = f"/api/scripts/{script_name}"
response = self.execute(path, arguments, inputs, *args, **kwargs)
data = load(response)
yield GETTER.output(data)
logger_info("First output is loaded and returned.")
key = data.get("key")
if key:
yield from self.get_real_time_output(key, data, *args, **kwargs)
def get_real_time_output(
self, key: str, data: Dict[str, Json], *args, **kwargs
) -> Iterator[Tuple[str, str, int]]:
"""
This function returns outputs of script with the "real time output"
WebScripts feature.
args and kwargs are sent to urllib.request.urlopen function.
"""
request = Request(
f"{self.url}/api/script/get/{key}", headers=self.headers
)
logger_info("Second request is built.")
while "key" in data:
logger_debug("Send a new request...")
response = urlopen(
request,
*args,
**kwargs,
)
logger_info("A new response is received.")
data = load(response)
yield GETTER.output(data)
logger_info("New output is loaded and returned.")
def execute(
self,
path: str,
arguments: Dict[str, Json],
inputs: Dict[str, Json],
*args,
urlopen=urlopen,
**kwargs,
) -> HTTPResponse:
"""
This function executes a script and returns the response.
args and kwargs are sent to urllib.request.urlopen function.
"""
logger_debug("Launch script execution..")
headers = self.headers.copy()
headers["Content-Type"] = "application/json"
logger_debug("Build arguments...")
arguments = {
key: {"value": value, "input": False}
for key, value in arguments.items()
}
inputs = {
key: {"value": value, "input": True}
for key, value in inputs.items()
}
arguments.update(inputs)
logger_info("Arguments are built.")
request = Request(
f"{self.url}{path}",
method="POST",
data=dumps({"arguments": arguments}).encode(),
headers=headers,
)
logger_info("Request are built. Send request...")
return urlopen(request, *args, **kwargs)
def upload(
self,
filename: str,
file: Union[TextIOWrapper, BytesIO, bytes],
*args,
no_compression: bool = None,
is_base64: bool = None,
hidden: bool = None,
binary: bool = None,
read_permissions: int = None,
write_permissions: int = None,
delete_permissions: int = None,
**kwargs,
) -> None:
"""
This function uploads a file on WebScripts server.
"""
logger_debug("Build headers...")
headers = self.headers.copy()
headers["Content-Type"] = "application/octet-stream"
if no_compression:
headers["No-Compression"] = "yes"
if is_base64:
headers["Is-Base64"] = "yes"
if hidden:
headers["Hidden"] = "yes"
if binary:
headers["Binary"] = "yes"
if read_permissions:
headers["Read-Permission"] = str(read_permissions)
if write_permissions:
headers["Write-Permission"] = str(write_permissions)
if delete_permissions:
headers["Delete-Permission"] = str(delete_permissions)
if not isinstance(file, bytes):
length = 0
data = file.read(10240)
while data:
length += len(data)
data = file.read(10240)
file.seek(0)
headers["Content-Length"] = str(length)
logger_info("Headers are built. Build request...")
request = Request(
f"{self.url}/share/upload/{filename}",
data=file,
headers=headers,
method="POST",
)
logger_info("Request built. Send request...")
urlopen(
request,
*args,
**kwargs,
)
logger_info("Get response without error. File is uploaded.")
def download(
self, filename: str, *args, save: bool = True, **kwargs
) -> GzipFile:
"""
This function downloads a file from WebScripts server.
"""
headers = self.headers.copy()
headers["Accept-Encoding"] = "identity, gzip"
logger_debug("Build download request...")
request = Request(
f"{self.url}/share/Download/filename/{filename}",
headers=headers,
)
logger_debug("Send download request...")
response = urlopen(
request,
*args,
**kwargs,
)
logger_info("Get download response without error.")
if response.headers["Content-Encoding"] == "gzip":
logger_debug("Decompress response...")
content = gzipopen(response)
else:
logger_debug("Save response in temp file...")
content = TemporaryFile()
copyfileobj(response, content)
content.seek(0)
if save:
logger_debug("Save the contents of the downloaded file...")
with open(filename, "wb") as output_file:
copyfileobj(content, output_file)
content.seek(0)
logger_debug("Return the contents of the downloaded file...")
return content
def request(
self, title: str, request: str, name: str, error_code: int = 0
) -> None:
"""
This function send a request or report to the WebScripts
Administrator.
"""
logger_debug("Build request...")
self.execute(
f"/error_pages/Request/send/{error_code}",
{
"title": title,
"request": request,
"name": name,
"error": str(error_code),
},
{},
)
logger_debug("Request sent successfully.")
@staticmethod
def args_command_to_webscripts(
arguments: List[str], is_inputs: bool = False
) -> Dict[str, Json]:
"""
This function returns WebScripts arguments from
command line arguments (List[str]).
"""
prefix = "input" if is_inputs else "arg"
webscripts_args: Dict[str, Json] = {}
counter = 1
logger_debug("Parse arguments to build WebScripts arguments...")
for argument in arguments:
if argument.startswith("-"):
logger_debug(f"Get optional argument: {argument}.")
webscripts_args[argument] = True
else:
logger_debug(f"Get argument value: {argument}")
webscripts_args[f"{prefix}_{counter}"] = argument
counter += 1
logger_info("WebScripts arguments are built.")
return webscripts_args
def parser() -> Namespace:
"""
This function parse command line arguments.
"""
parser = ArgumentParser(
description=(
'This package is the "official" WebScripts client. This '
"package implements client for default WebScripts features."
)
)
subparsers = parser.add_subparsers(
dest="action", help="Use default features of the WebScripts server."
)
add_parser = subparsers.add_parser
information = add_parser(
"info",
help=(
"Get the available scripts, arguments, and information about them."
),
)
execution = add_parser(
"exec", help="Execute a script on WebScripts Server."
)
upload = add_parser("upload", help="Upload a file on WebScripts Server.")
download = add_parser(
"download", help="Download files from WebScripts Server."
)
request = add_parser(
"request", help="Request or report to WebScripts administrator."
)
# test =
add_parser("test", help="Test WebScripts server and client.")
execution_add_argument = execution.add_argument
execution_add_argument(
"command", help="Command to execute script on WebScripts Server."
)
execution_add_argument(
"-o",
"--output-filename",
"--output",
nargs="?",
type=FileType("w"),
default=stdout,
help="Output file to save the result.",
)
inputs = execution.add_mutually_exclusive_group()
inputs_add_argument = inputs.add_argument
inputs_add_argument(
"-i",
"--inputs",
nargs="+",
action="extend",
help="Inputs value for script inputs.",
)
inputs_add_argument(
"-I",
"--input-filename",
"--input",
nargs="?",
type=FileType("rb"),
const=stdin.buffer,
help="Input file for script inputs.",
)
request_add_argument = request.add_argument
request_add_argument(
"-s", "--subject", help="The request/report subject.", default=""
)
request_add_argument(
"-n", "--name", help="Your name (Firstname LASTNAME).", default=""
)
request_add_argument(
"-r", "--request", help="The request/report.", default=""
)
request_add_argument(
"-c",
"--error-code",
help="The HTTP error code {403, 404, 406, 500 ...}.",
type=int,
default=0,
)
download_add_argument = download.add_argument
download_add_argument(
"-f",
"--filenames",
help="Filenames to download.",
nargs="+",
action="extend",
required=True,
)
download_add_argument(
"-o",
"--output-filename",
"--output",
nargs="?",
type=FileType("wb"),
default=stdout.buffer,
help="Filename to write the downloaded content.",
)
download_add_argument(
"-s",
"--save",
action="store_true",
help="Save the download in the same local filename.",
)
upload_add_argument = upload.add_argument
upload_add_argument(
"-6",
"--base64",
"--64",
action="store_true",
help="Upload a base64 encoded file on the server.",
)
upload_add_argument(
"-C",
"--no-compression",
action="store_true",
help="Do not compress the file on the server.",
)
upload_add_argument(
"-H",
"--hidden",
action="store_true",
help="Hide the file on the server.",
)
upload_add_argument(
"-b",
"--binary",
"--bin",
action="store_true",
help="Upload a binary file on the server.",
)
upload_add_argument(
"-r",
"--read-permission",
"--read",
type=int,
help="Read permission on the server.",
)
upload_add_argument(
"-w",
"--write-permission",
"--write",
type=int,
help="Write permission on the server.",
)
upload_add_argument(
"-d",
"--delete-permission",
"--delete",
type=int,
help="Delete permission on the server.",
)
upload_add_argument("filename", help="The file name of the uploaded file.")
content = upload.add_mutually_exclusive_group()
content_add_argument = content.add_argument
content_add_argument(
"-f",
"--file",
help="The filename of the file to upload on the server.",
)
content_add_argument("-c", "--content", help="Content of the file.")
information_add_argument = information.add_argument
information_add_argument(
"-a",
"--no-arguments",
action="store_true",
help="Do not print arguments.",
)
information_add_argument(
"-d",
"--no-descriptions",
action="store_true",
help="Do not print description.",
)
information_add_argument(
"-c",
"--no-categories",
action="store_true",
help="Do not print categories.",
)
information_add_argument(
"-s",
"--scripts",
nargs="+",
action="extend",
help="Information about specific scripts.",
)
parser_add_argument = parser.add_argument
parser_add_argument(
"-v",
"--verbose",
action="store_true",
help="Verbose mode (print logs).",
)
parser_add_argument(
"-i",
"--insecure",
action="store_true",
help="Do not check SSL certificate.",
)
parser_add_argument(
"-u",
"--username",
help="WebScripts username to use for this connection.",
)
parser_add_argument(
"url",
help="URL of the WebScripts server, example: http://127.0.0.1:8000",
)
password = parser.add_mutually_exclusive_group()
password_add_argument = password.add_argument
password_add_argument(
"-p",
"--password",
help="WebScripts password to use for this connection.",
)
password_add_argument(
"-P",