-
Notifications
You must be signed in to change notification settings - Fork 5
/
auprint
executable file
·607 lines (501 loc) · 17.8 KB
/
auprint
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
#!/usr/bin/env python3
import argparse
import random
import socket
import time
from collections import defaultdict, namedtuple
from getpass import getpass
from itertools import chain
from os import environ
from pathlib import Path
from shutil import which
from subprocess import (DEVNULL, PIPE, CalledProcessError, check_call,
check_output, run)
from sys import exit, stderr
from urllib.parse import quote
try:
import keyring
except ImportError:
print(
"""To avoid having to enter your password every time you use auprint
install the python keyring module using `pip install keyring`.""",
file=stderr,
)
keyring = None
DEBUG = False
def debugprint(*args, **kwargs):
if DEBUG:
print(*args, **kwargs)
def debugprint_f(f):
def wrapped(*args, **kwargs):
cmd = args[0]
debugprint(cmd[0], *[repr(arg) for arg in cmd[1:]])
return f(*args, **kwargs)
return wrapped
DEBUG_FUNCTIONS = [check_call, check_output, run]
for f in DEBUG_FUNCTIONS:
globals()[f.__name__] = debugprint_f(f)
class LocalAuth:
def __init__(self, filename):
self.filename = filename
try:
with open(filename) as f:
self.username = f.read().strip()
except IOError:
self.username = None
if keyring:
self.password = keyring.get_password("auprint", "auid")
else:
self.password = None
def __setattr__(self, key, value):
super().__setattr__(key, value)
if key == "username":
try:
if value == None:
Path(self.filename).unlink()
else:
with open(self.filename, "w") as f:
f.write(self.username)
except IOError:
pass
elif key == "password":
if not keyring:
return
if value == None:
try:
keyring.delete_password("auprint", "auid")
except keyring.errors.PasswordDeleteError:
pass
else:
keyring.set_password("auprint", "auid", value)
class AUAuthenticationError(BaseException):
pass
class PrinterNotFoundError(BaseException):
pass
def gethostbyname(host, fallback=None):
try:
return socket.gethostbyname(host)
except socket.gaierror as e:
if e.errno == -2 and fallback != None:
print("Using fallback host {} for {}".format(fallback, host))
return fallback
raise
class AUPrint:
IP = gethostbyname("prt11.uni.au.dk", "10.83.17.147")
PPD_PATH = "/usr/share/ppd"
GENERIC_PPD = PPD_PATH + "/cupsfilters/Generic-PDF_Printer-PDF.ppd"
TEST_PAGE = "/usr/share/cups/data/testprint"
DOMAIN = "uni"
BUILDING_NAMES = {
"1530": "matematik",
"5335": "nygaard",
"5340": "babbage",
"5341": "turing",
"5342": "ada",
"5343": "bush",
"5344": "benjamin",
"5345": "dreyer",
"5346": "hopper",
"5347": "wiener",
"5365": "stibitz",
}
EXTRA_BUILDING_NAMES = {
"5343": "studiecafeen",
}
BUILDING_NUMBERS = {
v: k for k, v in chain(BUILDING_NAMES.items(), EXTRA_BUILDING_NAMES.items())
}
auid = None
password = None
printers = None
def __init__(self, auid, password):
self.auid = auid
self.password = password
try:
self.printers = self.get_remote_printer_list()
except CalledProcessError:
raise AUAuthenticationError()
@classmethod
def check_smbclient(cls):
if not which("smbclient"):
print(
"Error: smbclient command is not available, try installing smbclient",
file=stderr,
)
else:
samba_dir = Path("/etc/samba")
samba_conf = samba_dir / "smb.conf"
if not samba_conf.exists():
print(f"The file {samba_conf} does not exist. Trying to create it:")
check_call(
["sudo", "sh", "-c", f"mkdir -p {samba_dir} && touch {samba_conf}"]
)
print("Done.")
p = run(["smbclient"], stderr=PIPE)
for l in p.stderr.split(b"\n"):
if l.startswith(b"Usage:"):
return True
stderr.buffer.write(p.stderr)
print(
"Error: smbclient doesn't seem to work, make sure /etc/samba/smb.conf exists",
file=stderr,
)
return False
@classmethod
def check_smbclient_connection(cls):
new_env = environ.copy()
new_env["PASSWD"] = ""
p = run(["smbclient", "-L", cls.IP], stdin=DEVNULL, stdout=PIPE, env=new_env)
if b"NT_STATUS_ACCESS_DENIED" in p.stdout or b"NT_STATUS_NOT_SUPPORTED" in p.stdout:
return True
print("Error: Couldn't connect to print server with smbclient.", file=stderr)
print("Make sure you're on AU's network.", file=stderr)
print(
"If you're connecting using VPN make sure you are using https://remote.au.dk/AU-ACCESS",
file=stderr,
)
return False
@classmethod
def check_cups(cls):
try:
check_call(["systemctl", "status", "cups"], stdout=DEVNULL)
return True
except CalledProcessError:
print("The cups service doesn't seem to be started.", file=stderr)
return False
@classmethod
def check_lpadmin(cls):
if not which("lpadmin"):
print("Error: lpadmin command is not available, try installing CUPS")
else:
digits = 10
printer_name = "__auprint_test_%s" % random.randrange(
10 ** digits, 10 ** (digits + 1)
)
try:
check_call(
[
"lpadmin",
"-p",
printer_name,
"-v",
"smb://example.org/auprint_test",
]
)
return True
except CalledProcessError:
print("Error: You don't seem to be able to use lpadmin:", file=stderr)
print(
'- If you\'re using Arch Linux make sure you are in the group "sys"',
file=stderr,
)
print(
'- If you\'re using Ubuntu make sure you are in the group "lpadmin"',
file=stderr,
)
finally:
check_call(["lpadmin", "-x", printer_name])
return False
@classmethod
def check_tools(cls):
return (
cls.check_smbclient()
and cls.check_cups()
and cls.check_lpadmin()
and cls.check_smbclient_connection()
)
def pretty_name(self, name):
parts = name.split("-")
if len(parts) == 1:
return name
building = self.BUILDING_NAMES.get(parts[0], parts[0])
number = parts[1]
return "%s-%s" % (building, number)
def get_remote_printer_list(self):
new_env = environ.copy()
new_env["PASSWD"] = self.password
out = str(
check_output(
[
"smbclient",
"-I",
self.IP,
"-L",
self.IP,
"-U",
"{}\\{}".format(self.DOMAIN, self.auid),
],
env=new_env,
),
"utf-8",
)
debugprint(out)
printers = {}
for l in out.split("\n"):
if not l.startswith("\t"):
continue
parts = l.strip().split(maxsplit=2)
if len(parts) != 3:
continue
name, typ, description = parts
if typ != "Printer":
continue
printers[name] = description
return printers
def printer_url(self, name):
return "smb://{}\\{}:{}@{}/{}".format(
self.DOMAIN, self.auid, quote(self.password, safe=""), self.IP, name
)
def update_authentication(self, name, install_name):
check_call(["lpadmin", "-p", install_name, "-v", self.printer_url(name)])
def get_local_printers(self):
try:
out = str(check_output(["lpstat", "-v"]), "utf-8").strip()
printers = []
for l in out.split("\n"):
url = l.split()[-1]
if not url.startswith("smb://{}/".format(self.IP)):
continue
name = url.split("/")[-1]
install_name = l.split()[2].split(":")[0]
printers.append((name, install_name))
return printers
except CalledProcessError:
return []
def local_printer_names(self):
return (p[1] for p in self.get_local_printers())
def install_printer(self, name, install_name, ppd=None):
if ppd == None:
ppd = self.GENERIC_PPD
if name in self.printers:
check_call(
[
"lpadmin",
"-p",
install_name,
"-E",
"-P",
ppd,
"-v",
self.printer_url(name),
]
)
else:
raise PrinterNotFoundError()
def delete_printer(self, name):
if name in self.local_printer_names():
check_call(["lpadmin", "-x", name])
else:
raise PrinterNotFoundError()
def print(self, name, f):
if name in self.local_printer_names():
out = check_output(["lp", "-E", "-d", name, f], encoding="utf-8").strip()
prefix = "request id is "
suffix = " (1 file(s))"
assert out.startswith(prefix)
assert out.endswith(suffix)
return out[len(prefix) : -len(suffix)]
else:
raise PrinterNotFoundError()
def set_option(self, name, key, value):
check_call(["lpadmin", "-p", name, "-o", "{}={}".format(key, value)])
@classmethod
def get_options(cls, name):
output = check_output(["lpoptions", "-p", name, "-l"], encoding="utf-8")
options = []
for l in output.splitlines():
optname, choices = l.split(":")
choices = choices.split()
default = None
for i, v in enumerate(choices):
if v[0] == "*":
default = choices[i] = v[1:]
optname, verbose = optname.split("/")
options.append(
{
"name": optname,
"verbose_name": verbose,
"default": default,
"options": choices,
}
)
return options
def find_ppd(self, printer_type):
try:
output = check_output(
[
"lpinfo",
"--product",
printer_type,
"--exclude-schemes",
"everywhere",
"-m",
],
encoding="utf-8",
)
# TODO: Currently we just return the first match
path = output.split()[0]
prefix = "lsb/usr/"
if path.startswith(prefix):
path = self.PPD_PATH + "/" + path[len(prefix) :]
return path
except CalledProcessError:
# Nothing found
return None
def print_test_page(self, name):
return self.print(name, self.TEST_PAGE)
def test_printer(self, name):
job_id = self.print_test_page(name)
while True:
time.sleep(0.1)
out = check_output(["lpstat", "-l", "-P", name], encoding="utf-8")
status = {}
lines = out.splitlines()
for i in range(len(lines)):
if lines[i].startswith(job_id):
i += 1
while i < len(lines) and lines[i].startswith("\t"):
parts = lines[i].strip().split(": ", maxsplit=1)
if len(parts) == 2:
status[parts[0]] = parts[1]
i += 1
break
else:
print("Test page probably printed successfully")
break
if "Status" in status:
s = status["Status"]
print("Status:", s)
print("Alerts:", status["Alerts"])
status_code = s.split()[-1]
if status_code == "NT_STATUS_LOGON_FAILURE":
print(
"This probably means that the server doesn't recognize your username/password"
)
elif status_code == "NT_STATUS_ACCESS_DENIED":
print("")
break
def print_rows(rows, sep=" "):
maxlen = defaultdict(int)
for row in rows:
for i, v in enumerate(row):
maxlen[i] = max(maxlen[i], len(str(v)))
for row in rows:
for i, v in enumerate(row):
if i == len(row) - 1:
print(str(v))
else:
print(str(v).ljust(maxlen[i]), end=sep)
# print('(%s)\t%s\t%s' % (i + 1, p, matched_printers[p]))
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Manages installed printers at AU")
parser.add_argument(
"--update-passwords",
action="store_true",
help="Update passwords used for printers",
)
parser.add_argument("--debug", action="store_true", help="Print debug info")
parser.add_argument(
"--no-save",
action="store_true",
help="Disables using saved authentication info",
)
args = parser.parse_args()
if not AUPrint.check_tools():
exit(1)
DEBUG = args.debug
if args.no_save:
class FakeAuth:
__slots__ = ("username", "password")
auth = FakeAuth()
auth.username = None
auth.password = None
else:
auth = LocalAuth("auid.txt")
logged_in = False
while not logged_in:
while not auth.username:
auth.username = input("AUID (au" + "X" * 6 + "): ").strip().lower()
if not auth.username.startswith("au"):
auth.username = None
while not auth.password:
auth.password = getpass("AU password: ").strip()
try:
auprint = AUPrint(auth.username, auth.password)
logged_in = True
except AUAuthenticationError:
print("Invalid auid/password combination")
auth.username = None
auth.password = None
printers = auprint.printers
if args.update_passwords:
printers = auprint.get_local_printers()
for name, install_name in printers:
auprint.update_authentication(name, install_name)
print("Updated password for {} at {}".format(name, install_name))
else:
known_buildings = sorted(AUPrint.BUILDING_NUMBERS.items(), key=lambda x: x[1])
print("Known building names:")
rows = []
for name, number in known_buildings:
rows.append(("", name, number))
print_rows(rows)
print()
building = input("Building number/name (empty for any): ").strip()
building_number = AUPrint.BUILDING_NUMBERS.get(building, building)
print()
matched_printers = {
p: d for p, d in printers.items() if p.startswith(building_number)
}
if len(matched_printers) == 0:
print("No printers found")
else:
print("Available printers: ")
rows = []
printer_rid = []
for i, p in enumerate(matched_printers):
rows.append(("(%s)" % (i + 1), p, matched_printers[p]))
printer_rid.append(p)
print_rows(rows)
print()
opt = input("Printer to install: ").strip()
try:
opt = int(opt)
except ValueError:
exit()
opt -= 1
if not (0 <= opt < len(matched_printers)):
exit()
printer = printer_rid[opt]
printer_description = matched_printers[printer]
name = auprint.pretty_name(printer)
print()
print("Selected", printer)
custom_name = input("Install name [%s]: " % name).strip()
if custom_name:
name = custom_name
ppd = input("PPD file [{}]: ".format("generic")).strip()
if not ppd:
ppd = None
auprint.install_printer(printer, name, ppd)
# TODO: Check if PPD supports it
papersize = input("Paper size [A4]: ").strip()
if not papersize:
papersize = "A4"
auprint.set_option(name, "PageSize", papersize)
duplex = input("Duplex printing [Yn]: ").strip()
if not duplex or duplex.lower() == "y":
duplex_type = "DuplexNoTumble"
else:
duplex_type = "None"
auprint.set_option(name, "Duplex", duplex_type)
stapling = input("Portrait stapling [Yn]: ").strip()
if not stapling or stapling.lower() == "y":
staple_location = "SinglePortrait"
else:
staple_location = "None"
auprint.set_option(name, "StapleLocation", staple_location)
print("Successfully added printer %s as %s" % (printer, name))
print_test_page = input("Print test page [yN]? ").strip()
if print_test_page.lower() == "y":
auprint.test_printer(name)