-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
217 lines (168 loc) 路 5.65 KB
/
main.py
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
#!/usr/bin/env python
"""
zebra-password-changer-cli-py
Usage: python main.py <IP_ADDRESS> <PASSWORD (4 digit, only numbers)>
"""
import ipaddress
import socket
import sys
import platform
config = {
'app_title': '== Zebra password changer ==',
'app_version': '0.1.0',
'app_file_name': 'main.py',
'printer_port': 9100,
'socket_timeout': 3,
'password_total_char': 4
}
class CliColors:
"""Cli colors
"""
HEADER = '\033[95m'
WHITE = '\33[37m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def print_version():
"""
VERSION
zebra-password-changer v0.1.0 - Python 3.10.6
"""
print(f"{CliColors.OKCYAN}VERSION{CliColors.ENDC}")
print(f" zebra-password-changer v{config['app_version']} - Python {platform.python_version()}")
sys.exit(0)
def print_help():
"""
== Zebra password changer ==
USAGE
python main.py <IP_ADDRESS> <PASSWORD>
python main.py [command]
COMMANDS
help show CLI help
version show CLI version
DESCRIPTION
CLI tool that allows changing Zebra printer's password
"""
print(f"{CliColors.OKCYAN}USAGE{CliColors.ENDC}")
print(" python main.py <IP_ADDRESS> <PASSWORD>")
print(" python main.py [command]")
print("")
print(f"{CliColors.OKCYAN}COMMANDS{CliColors.ENDC}")
print(" help", f" {CliColors.WHITE}show CLI help{CliColors.ENDC}")
print(" version", f" {CliColors.WHITE}show CLI version{CliColors.ENDC}")
print("")
print(f"{CliColors.OKCYAN}DESCRIPTION{CliColors.ENDC}")
print(" CLI tool that allows changing Zebra printers password")
sys.exit(0)
def error_msg(msg, exit=False):
"""Print error message
Args:
msg (str): message
exit (bool, optional): exit from the app, defaults to False.
"""
print(f"{CliColors.FAIL}[ERROR]{CliColors.ENDC} {msg}")
if exit:
sys.exit(0)
def usage_help_msg():
print(f"{CliColors.WARNING}use 'python main.py help' for help{CliColors.ENDC}")
def check_arguments(argument_list):
"""Check arguments
Args:
argument_list (list): arguments
"""
# No any argument -> error & exit
if not argument_list:
error_msg("There is no any argument!\n")
print_help()
# Argument is "help" -> show help & exit
if argument_list[0] == "help":
print_help()
# Argument is "version" -> show version & exit
if argument_list[0] == "version":
print_version()
# Not have 2 argument -> error & exit
if len(argument_list) != 2:
error_msg("Wrong command or argument!\n")
usage_help_msg()
sys.exit(0)
def validate_ip_address(ip_address):
# Validate ip address
try:
ipaddress.ip_address(ip_address)
except ValueError:
# invalid ip address
return False
else:
return True
def validate_password(input_password, total_char):
"""Validate password
Args:
input_password (str): password
"""
# total_char (from config) and only numbers
if not input_password.isdigit() or len(input_password) != total_char:
# invalid password
return False
else:
return True
def check_ip_and_password(input_ip_address, input_password):
valid_ip_address = validate_ip_address(input_ip_address)
valid_password = validate_password(input_password, config['password_total_char'])
if not valid_ip_address and not valid_password:
error_msg("IP address is invalid!")
error_msg(f"Password is invalid! Please enter a {config['password_total_char']} digit number.")
usage_help_msg()
sys.exit(0)
elif not valid_ip_address:
error_msg("IP adress is invalid!")
sys.exit(0)
elif not valid_password:
error_msg(f"Password is invalid! Please enter a {config['password_total_char']} digit number.")
sys.exit(0)
def socket_request(ip_address, port, timeout, zpl_code):
"""Socket request
Args:
ip_address (str): IP address
port (int): Port
timeout (int): Timeout
zpl_code (str): ZPL code to send
"""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.settimeout(timeout)
try:
sock.connect((ip_address, port))
sock.send(zpl_code)
print(f"\r{CliColors.OKGREEN}[OK]{CliColors.ENDC} {CliColors.OKBLUE}{ip_address}{CliColors.ENDC} : password has been changed.")
except TimeoutError:
error_msg(f"Request timed out while connecting to remote host {ip_address}", True)
finally:
sock.close()
def main():
""" Main function
"""
# Check arguments
full_cmd_arguments = sys.argv # Get full command-line arguments
argument_list = full_cmd_arguments[1:] # Keep all but the first
check_arguments(argument_list)
# Continue only if the argument check is passed
input_ip_address = argument_list[0]
input_password = argument_list[1]
check_ip_and_password(input_ip_address, input_password)
# Continue only if ip address and password both are valid
# Prepare the password change zpl code from input_password
fmt_zpl_code = f"^XA^KP{input_password}^JUS^XZ".encode()
# Send the password change request
socket_request(
ip_address=input_ip_address,
port=config['printer_port'],
timeout=config['socket_timeout'],
zpl_code=fmt_zpl_code
)
if __name__ == '__main__':
print(f"{CliColors.HEADER}{config['app_title']}{CliColors.ENDC}", "\n")
main()