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
|
#!/usr/bin/python
# Copyright (C) 2013, John Sigurd Skogtvedt <jss@linuxavdelingen.no>
#
# 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 2 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, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# /etc/xdg/autostart/standardskriver.desktop eksempel:
# [Desktop Entry]
# Type=Application
# Exec=standardskriver
# Name=standardskriver
# StartupNotify=false
CFG_FILE = '/etc/standardskriver.cfg'
CFG_FILE_EXAMPLE = '''[settings]
order = machine groups
delete lpoptions = yes
# MAC address or IP = printer
# hostname = printer
# hostname.domain = printer
# LTSP client IP = printer
# (globbing works)
[machine]
00:01:02:03:04:05 = printer01
172.16.34.64 = printer02
hostname = printer01
hostname.domain = printer02
# group name = printer
# (globbing works)
[groups]
group1 = printer01
group2 = printer02
'''
from glob import glob
from fnmatch import fnmatchcase
import sys
import os
import subprocess
import re
from socket import gethostname, getfqdn
from optparse import OptionParser
from ConfigParser import RawConfigParser
macaddrs = [open(a).read().replace(':', '').strip().lower() for a in glob('/sys/class/net/*/address')]
macaddrs = [a for a in macaddrs if a]
parser = OptionParser()
parser.add_option('-n', '--dryrun', action='store_true', help='only show what would be done')
options, args = parser.parse_args()
if not os.path.exists(CFG_FILE):
print >>sys.stderr, 'Configuration file %s is missing.' % CFG_FILE
print >>sys.stderr, 'To create it, redirect the following example to %s and edit the file.' % CFG_FILE
print CFG_FILE_EXAMPLE
sys.exit(1)
cfg = RawConfigParser()
# hack: mac addrs contain :, which clashes with cfg syntax
cfg.OPTCRE = re.compile(
r'(?P<option>[^=\s][^=]*)' # very permissive!
r'\s*(?P<vi>[=])\s*' # any number of space/tab,
# followed by separator
# (=), followed
# by any # space/tab
r'(?P<value>.*)$' # everything up to eol
)
cfg.readfp(open(CFG_FILE, 'rb'))
for x in cfg.get('settings', 'order').split():
if not x in ('machine', 'groups'):
print 'invalid value %s in settings/order' % s
sys.exit(1)
hostnames = []
hostnames.append(gethostname())
hostnames.append(getfqdn())
re_ipaddr = re.compile(r'inet addr:(\S+)')
ipaddrs = []
try:
ipaddrs.append(os.environ['SSH_CLIENT'].split()[0])
except KeyError:
pass
p = subprocess.Popen(['/sbin/ifconfig'], stdout=subprocess.PIPE)
for line in p.stdout:
m = re_ipaddr.search(line)
if m:
ipaddrs.append(m.group(1))
p.wait()
p = subprocess.Popen(['id', '-Gn'], stdout=subprocess.PIPE)
groups = p.stdout.read().split()
p.wait()
#print groups
def get_group_match():
for group, printer in cfg.items('groups'):
if group.strip('@') in groups: return printer
return None
def get_machine_match():
for machine, printer in cfg.items('machine'):
if any(fnmatchcase(macaddr, machine.replace('-', '').replace(':', '')) for macaddr in macaddrs) or \
any(fnmatchcase(ipaddr, machine) for ipaddr in ipaddrs) or \
any(fnmatchcase(hostname, machine) for hostname in hostnames):
return printer
return None
matches = []
for item in cfg.get('settings', 'order').split():
if item == 'machine': matches.append(get_machine_match())
elif item == 'groups': matches.append(get_group_match())
else: raise ValueError('%s is not machine or groups' % item)
try:
printer = [x for x in matches if x][0]
except IndexError: # no match
if cfg.getboolean('settings', 'delete lpoptions'):
lpoptions_filename = os.path.expanduser('~/.cups/lpoptions')
if options.dryrun:
print 'would delete %s' % lpoptions_filename
else:
try:
os.unlink(lpoptions_filename)
except OSError:
pass
sys.exit(0)
args = ['lpoptions', '-d', printer]
if options.dryrun:
print 'would call %s' % (' '.join(args))
else:
subprocess.call(args)
|