├── .gitignore
├── AirPrint_Generator.py
├── AirPrint_Generator_Outset.py
├── AirPrinter-Template-Outset.plist
├── AirPrinter-Template.plist
├── LICENSE.md
├── Printer-Template.plist
├── README.md
├── Template.csv
└── print_generator.py
/.gitignore:
--------------------------------------------------------------------------------
1 | *.pkginfo
2 |
--------------------------------------------------------------------------------
/AirPrint_Generator.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/munki/munki-python
2 |
3 | # AirPrint_Generator
4 | # Version 1.1
5 | # Updated 3/17/22
6 |
7 | from __future__ import absolute_import, print_function
8 |
9 | import argparse
10 | import csv
11 | import os
12 | import re
13 | import sys
14 |
15 | try:
16 | from plistlib import load as load_plist # Python 3
17 | from plistlib import dump as dump_plist
18 | except ImportError:
19 | from plistlib import readPlist as load_plist # Python 2
20 | from plistlib import writePlist as dump_plist
21 |
22 |
23 | def getOptionsString(optionList):
24 | # optionList should be a list item
25 | optionsString = ''
26 | for option in optionList:
27 | if option == optionList[-1]:
28 | optionsString += "\"%s\":\"%s\"" % (str(option.split('=')[0]), str(option.split('=')[1]))
29 | else:
30 | optionsString += "\"%s\":\"%s\"" % (str(option.split('=')[0]), str(option.split('=')[1])) + ', '
31 | return optionsString
32 |
33 | parser = argparse.ArgumentParser(description='Generate a Munki nopkg-style pkginfo for printer installation.')
34 | parser.add_argument('--printername', help='Name of printer queue. May not contain spaces, tabs, # or /. Required.')
35 | parser.add_argument('--address', help='IP or DNS address of printer. Defaults to ipp:// which should be used for AirPrint. Required.')
36 | parser.add_argument('--location', help='Location name for printer. Optional. Defaults to printername.')
37 | parser.add_argument('--displayname', help='Display name for printer (and Munki pkginfo). Optional. Defaults to printername.')
38 | parser.add_argument('--desc', help='Description for Munki pkginfo only. Optional.')
39 | parser.add_argument('--requires', help='Required packages in form of space-delimited \'CanonDriver1 CanonDriver2\'. Optional.')
40 | parser.add_argument('--options', nargs='*', dest='options', help='Printer options in form of space-delimited \'Option1=Key Option2=Key Option3=Key\', etc. Optional.')
41 | parser.add_argument('--version', help='Version number of Munki pkginfo. Optional. Defaults to 1.0.', default='1.0')
42 | parser.add_argument('--icon', help='Specifies an existing icon in the Munki repo to display for the printer in Managed Software Center. Optional.')
43 | parser.add_argument('--csv', help='Path to CSV file containing printer info. If CSV is provided, all other options are ignored.')
44 | args = parser.parse_args()
45 |
46 |
47 | pwd = os.path.dirname(os.path.realpath(__file__))
48 | f = open(os.path.join(pwd, 'AirPrinter-Template.plist'), 'rb')
49 | templatePlist = load_plist(f)
50 | f.close()
51 |
52 | if args.csv:
53 | # A CSV was found, use that for all data.
54 | with open(args.csv, mode='r') as infile:
55 | reader = csv.reader(infile)
56 | next(reader, None) # skip the header row
57 | for row in reader:
58 | newPlist = dict(templatePlist)
59 | # each row contains 10 elements:
60 | # Printer name, location, display name, address, driver, description, options, version, requires, icon
61 | # options in the form of "Option=Value Option2=Value Option3=Value"
62 | # requires in the form of "package1 package2" Note: the space seperator
63 | theOptionString = ''
64 | if row[6] != "":
65 | theOptionString = getOptionsString(row[6].split(" "))
66 | # First, change the plist keys in the pkginfo itself
67 | newPlist['display_name'] = row[2]
68 | newPlist['description'] = row[5]
69 | newPlist['name'] = "Printer_" + str(row[0]) # set to printer name
70 | # Check for an icon
71 | if row[9] != "":
72 | newPlist['icon_name'] = row[9]
73 | # Check for a version number
74 | if row[7] != "":
75 | # Assume the user specified a version number
76 | version = row[7]
77 | else:
78 | # Use the default version of 1.0
79 | version = "1.0"
80 | newPlist['version'] = version
81 | # Check for a protocol listed in the address
82 | if '://' in row[3]:
83 | # Assume the user passed in a full address and protocol
84 | address = row[3]
85 | else:
86 | # Assume the user wants to use the default, ipp://
87 | address = 'ipp://' + row[3]
88 | # Set the path to the programmatically generated PPD
89 | driver = '/tmp/%s.ppd' % row[0]
90 |
91 | # Now change the variables in the installcheck_script
92 | newPlist['installcheck_script'] = newPlist['installcheck_script'].replace("PRINTERNAME", row[0])
93 | newPlist['installcheck_script'] = newPlist['installcheck_script'].replace("OPTIONS", theOptionString)
94 | newPlist['installcheck_script'] = newPlist['installcheck_script'].replace("LOCATION", row[1].replace('"', ''))
95 | newPlist['installcheck_script'] = newPlist['installcheck_script'].replace("DISPLAY_NAME", row[2].replace('"', ''))
96 | newPlist['installcheck_script'] = newPlist['installcheck_script'].replace("ADDRESS", address)
97 | # Now change the variables in the preinstall_script
98 | newPlist['preinstall_script'] = newPlist['preinstall_script'].replace("PRINTERNAME", row[0])
99 | newPlist['preinstall_script'] = newPlist['preinstall_script'].replace("ADDRESS", address)
100 | # Now change the variables in the postinstall_script
101 | newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("PRINTERNAME", row[0])
102 | newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("LOCATION", row[1].replace('"', ''))
103 | newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("DISPLAY_NAME", row[2].replace('"', ''))
104 | newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("ADDRESS", address)
105 | newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("DRIVER", driver)
106 | newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("OPTIONS", theOptionString)
107 | # Now change the one variable in the uninstall_script
108 | newPlist['uninstall_script'] = newPlist['uninstall_script'].replace("PRINTERNAME", row[0])
109 | # Add required packages if passed in the csv
110 | if row[8] != "":
111 | newPlist['requires'] = row[8].split(' ')
112 | # Write out the file
113 | newFileName = "Printer-" + row[0] + "-" + version + ".pkginfo"
114 | f = open(newFileName, 'wb')
115 | dump_plist(newPlist, f)
116 | f.close()
117 | else:
118 | if not args.printername:
119 | print(os.path.basename(sys.argv[0]) + ': error: argument --printername is required', file=sys.stderr)
120 | parser.print_usage()
121 | sys.exit(1)
122 | #if not args.driver:
123 | # print(os.path.basename(sys.argv[0]) + ': error: argument --driver is required', file=sys.stderr)
124 | # parser.print_usage()
125 | # sys.exit(1)
126 | if not args.address:
127 | print(os.path.basename(sys.argv[0]) + ': error: argument --address is required', file=sys.stderr)
128 | parser.print_usage()
129 | sys.exit(1)
130 |
131 | if re.search(r"[\s#/]", args.printername):
132 | # printernames can't contain spaces, tabs, # or /. See lpadmin manpage for details.
133 | print("ERROR: Printernames can't contain spaces, tabs, # or /.", file=sys.stderr)
134 | sys.exit(1)
135 |
136 | if args.desc:
137 | description = args.desc
138 | else:
139 | description = ""
140 |
141 | if args.displayname:
142 | displayName = args.displayname
143 | else:
144 | displayName = str(args.printername)
145 |
146 | if args.location:
147 | location = args.location
148 | else:
149 | location = args.printername
150 |
151 | if args.version:
152 | version = str(args.version)
153 | else:
154 | version = "1.0"
155 |
156 | if args.requires:
157 | requires = args.requires
158 | else:
159 | requires = ""
160 |
161 | if args.icon:
162 | icon = args.icon
163 | else:
164 | icon = ""
165 |
166 | if args.options:
167 | optionsString = str(args.options[0]).split(' ')
168 | optionsString = getOptionsString(optionsString)
169 | else:
170 | optionsString = ''
171 |
172 | # Set the path to the automatically created PPD
173 | driver = '/tmp/%s.ppd' % args.printername
174 |
175 | if '://' in args.address:
176 | # Assume the user passed in a full address and protocol
177 | address = args.address
178 | else:
179 | # Assume the user wants to use the default, ipp://
180 | address = 'ipp://' + args.address
181 |
182 | newPlist = dict(templatePlist)
183 | # root pkginfo variable replacement
184 | newPlist['description'] = description
185 | newPlist['display_name'] = displayName
186 | newPlist['name'] = "Printer_" + args.printername
187 | newPlist['version'] = version
188 | newPlist['icon_name'] = icon
189 | # installcheck_script variable replacement
190 | newPlist['installcheck_script'] = templatePlist['installcheck_script'].replace("PRINTERNAME", args.printername)
191 | newPlist['installcheck_script'] = newPlist['installcheck_script'].replace("ADDRESS", address)
192 | newPlist['installcheck_script'] = newPlist['installcheck_script'].replace("DISPLAY_NAME", displayName)
193 | newPlist['installcheck_script'] = newPlist['installcheck_script'].replace("LOCATION", location.replace('"', ''))
194 | newPlist['installcheck_script'] = newPlist['installcheck_script'].replace("OPTIONS", optionsString)
195 | # preinstall_script variable replacment
196 | newPlist['preinstall_script'] = templatePlist['preinstall_script'].replace("PRINTERNAME", args.printername)
197 | newPlist['preinstall_script'] = newPlist['preinstall_script'].replace("ADDRESS", address)
198 | # postinstall_script variable replacement
199 | newPlist['postinstall_script'] = templatePlist['postinstall_script'].replace("PRINTERNAME", args.printername)
200 | newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("ADDRESS", address)
201 | newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("DISPLAY_NAME", displayName)
202 | newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("LOCATION", location.replace('"', ''))
203 | newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("DRIVER", driver)
204 | newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("OPTIONS", optionsString)
205 | # uninstall_script variable replacement
206 | newPlist['uninstall_script'] = templatePlist['uninstall_script'].replace("PRINTERNAME", args.printername)
207 | # required packages
208 | if requires != "":
209 | newPlist['requires'] = [r.replace('\\', '') for r in re.split(r"(?
2 |
3 |
4 |
5 | autoremove
6 |
7 | catalogs
8 |
9 | testing
10 |
11 | category
12 | Printers
13 | description
14 | DESCRIPTION
15 | display_name
16 | DISPLAY_NAME
17 | installcheck_script
18 | #!/usr/local/munki/munki-python
19 | import subprocess
20 | import sys
21 | import shlex
22 |
23 | printerOptions = { OPTIONS }
24 |
25 | cmd = ['/usr/bin/lpoptions', '-p', 'PRINTERNAME', '-l']
26 | proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
27 | (lpoptLongOut, lpoptErr) = proc.communicate()
28 |
29 | # lpoptions -p printername -l will still exit 0 even if printername does not exist
30 | # but it will print to stderr
31 | if lpoptErr:
32 | print(lpoptErr)
33 | sys.exit(0)
34 |
35 | cmd = ['/usr/bin/lpoptions', '-p', 'PRINTERNAME']
36 | proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
37 | (lpoptOut, lpoptErr) = proc.communicate()
38 |
39 | #Note: lpoptions -p printername will never fail. If PRINTERNAME does not exist, it
40 | #will still exit 0, but just produce no output.
41 | #Thanks, cups, I was having a good day until now.
42 |
43 | for option in lpoptLongOut.splitlines():
44 | for myOption in printerOptions.keys():
45 | optionName = option.split("/", 1)[0]
46 | optionValues = option.split("/",1)[1].split(":")[1].strip().split(" ")
47 | for opt in optionValues:
48 | if "*" in opt:
49 | actualOptionValue = opt.replace('*', '')
50 | break
51 | if optionName == myOption:
52 | if not printerOptions[myOption].lower() == actualOptionValue.lower():
53 | print("Found mismatch: %s is '%s', should be '%s'" % (myOption, printerOptions[myOption], actualOptionValue))
54 | sys.exit(0)
55 |
56 | try:
57 | lpoptOut = lpoptOut.decode("utf-8")
58 | except UnicodeDecodeError:
59 | sys.exit(0)
60 |
61 | optionDict = {}
62 | for builtOption in shlex.split(lpoptOut):
63 | try:
64 | optionDict[builtOption.split("=")[0]] = builtOption.split("=")[1]
65 | except:
66 | optionDict[builtOption.split("=")[0]] = None
67 |
68 | comparisonDict = { "device-uri":"ADDRESS", "printer-info":"DISPLAY_NAME", "printer-location":"LOCATION" }
69 | for keyName in comparisonDict.keys():
70 | comparisonDict[keyName] = None if comparisonDict[keyName].strip() == "" else comparisonDict[keyName]
71 | optionDict[keyName] = None if keyName not in optionDict or optionDict[keyName].strip() == "" else optionDict[keyName]
72 | if not comparisonDict[keyName] == optionDict[keyName]:
73 | print("Settings mismatch: %s is '%s', should be '%s'" % (keyName, optionDict[keyName], comparisonDict[keyName]))
74 | sys.exit(0)
75 |
76 | sys.exit(1)
77 | installer_type
78 | nopkg
79 | minimum_os_version
80 | 10.7.0
81 | name
82 | Printer_DISPLAYNAME
83 | postinstall_script
84 | #!/usr/local/munki/munki-python
85 | import subprocess
86 | import sys
87 |
88 | # Populate these options if you want to set specific options for the printer. E.g. duplexing installed, etc.
89 | printerOptions = { OPTIONS }
90 |
91 | cmd = [ '/usr/sbin/lpadmin', '-x', 'PRINTERNAME' ]
92 | proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
93 | (lpadminxOut, lpadminxErr) = proc.communicate()
94 |
95 | # Install the printer
96 | cmd = [ '/usr/sbin/lpadmin',
97 | '-p', 'PRINTERNAME',
98 | '-L', 'LOCATION',
99 | '-D', 'DISPLAY_NAME',
100 | '-v', 'ADDRESS',
101 | '-P', "DRIVER",
102 | '-E',
103 | '-o', 'printer-is-shared=false',
104 | '-o', 'printer-error-policy=abort-job' ]
105 |
106 | for option in printerOptions.keys():
107 | cmd.append("-o")
108 | cmd.append(str(option) + "=" + str(printerOptions[option]))
109 |
110 | proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
111 | (lpadminOut, lpadminErr) = proc.communicate()
112 |
113 | if lpadminErr:
114 | if "Printer drivers are deprecated" in lpadminErr:
115 | # work around lpadmin deprecation message
116 | print("Install successful - caught deprecation message; preventing exit 1")
117 | pass
118 | else:
119 | print("Error: %s" % lpadminErr)
120 | sys.exit(1)
121 | print("Results: %s" % lpadminOut)
122 | sys.exit(0)
123 | preinstall_script
124 | #!/bin/zsh
125 |
126 | ## Programmatically generate an Outset on-demand script that will create the AirPrint PPD
127 |
128 | # Check for a logged in user so we don't attempt this at the login window
129 |
130 | currentUser=$(stat -f %Su "/dev/console")
131 |
132 | if [[ "$currentUser" == "root" ]]
133 | then
134 | echo "No user is currently logged in, exiting."
135 | exit 1
136 | fi
137 |
138 | # Define the script
139 |
140 | line1="#!/bin/zsh"
141 | line2="/System/Library/Printers/Libraries/ipp2ppd ADDRESS everywhere > /tmp/PRINTERNAME.ppd"
142 |
143 | # Write it to disk
144 |
145 | echo $line1 > /usr/local/outset/on-demand/PRINTERNAME-PPD-Generator.sh
146 | echo $line2 >> /usr/local/outset/on-demand/PRINTERNAME-PPD-Generator.sh
147 |
148 | # Fix the permissions so Outset will execute it
149 |
150 | /bin/chmod 755 /usr/local/outset/on-demand/PRINTERNAME-PPD-Generator.sh
151 |
152 | # Trigger an Outset on-demand run so the logged in user will execute the script
153 |
154 | /usr/bin/touch /private/tmp/.com.github.outset.ondemand.launchd
155 |
156 | # Give it time to run
157 |
158 | sleep 10
159 |
160 | # Make sure it all worked and the PPD is where we want it before attempting to install the printer
161 |
162 | if
163 | [[ ! -f /tmp/PRINTERNAME.ppd ]]
164 | then
165 | echo "The PPD doesn't exist where expected, exiting.'"
166 | exit 1
167 | fi
168 | unattended_install
169 |
170 | uninstall_method
171 | uninstall_script
172 | uninstall_script
173 | #!/bin/sh
174 | /usr/sbin/lpadmin -x PRINTERNAME
175 | uninstallable
176 |
177 | version
178 | VERSION
179 |
180 |
181 |
--------------------------------------------------------------------------------
/AirPrinter-Template.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | autoremove
6 |
7 | catalogs
8 |
9 | testing
10 |
11 | category
12 | Printers
13 | description
14 | DESCRIPTION
15 | display_name
16 | DISPLAY_NAME
17 | installcheck_script
18 | #!/usr/local/munki/munki-python
19 | import subprocess
20 | import sys
21 | import shlex
22 |
23 | printerOptions = { OPTIONS }
24 |
25 | cmd = ['/usr/bin/lpoptions', '-p', 'PRINTERNAME', '-l']
26 | proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
27 | (lpoptLongOut, lpoptErr) = proc.communicate()
28 |
29 | # lpoptions -p printername -l will still exit 0 even if printername does not exist
30 | # but it will print to stderr
31 | if lpoptErr:
32 | print(lpoptErr)
33 | sys.exit(0)
34 |
35 | cmd = ['/usr/bin/lpoptions', '-p', 'PRINTERNAME']
36 | proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
37 | (lpoptOut, lpoptErr) = proc.communicate()
38 |
39 | #Note: lpoptions -p printername will never fail. If PRINTERNAME does not exist, it
40 | #will still exit 0, but just produce no output.
41 | #Thanks, cups, I was having a good day until now.
42 |
43 | for option in lpoptLongOut.splitlines():
44 | for myOption in printerOptions.keys():
45 | optionName = option.split("/", 1)[0]
46 | optionValues = option.split("/",1)[1].split(":")[1].strip().split(" ")
47 | for opt in optionValues:
48 | if "*" in opt:
49 | actualOptionValue = opt.replace('*', '')
50 | break
51 | if optionName == myOption:
52 | if not printerOptions[myOption].lower() == actualOptionValue.lower():
53 | print("Found mismatch: %s is '%s', should be '%s'" % (myOption, printerOptions[myOption], actualOptionValue))
54 | sys.exit(0)
55 |
56 | try:
57 | lpoptOut = lpoptOut.decode("utf-8")
58 | except UnicodeDecodeError:
59 | sys.exit(0)
60 |
61 | optionDict = {}
62 | for builtOption in shlex.split(lpoptOut):
63 | try:
64 | optionDict[builtOption.split("=")[0]] = builtOption.split("=")[1]
65 | except:
66 | optionDict[builtOption.split("=")[0]] = None
67 |
68 | comparisonDict = { "device-uri":"ADDRESS", "printer-info":"DISPLAY_NAME", "printer-location":"LOCATION" }
69 | for keyName in comparisonDict.keys():
70 | comparisonDict[keyName] = None if comparisonDict[keyName].strip() == "" else comparisonDict[keyName]
71 | optionDict[keyName] = None if keyName not in optionDict or optionDict[keyName].strip() == "" else optionDict[keyName]
72 | if not comparisonDict[keyName] == optionDict[keyName]:
73 | print("Settings mismatch: %s is '%s', should be '%s'" % (keyName, optionDict[keyName], comparisonDict[keyName]))
74 | sys.exit(0)
75 |
76 | sys.exit(1)
77 | installer_type
78 | nopkg
79 | minimum_os_version
80 | 10.7.0
81 | name
82 | Printer_DISPLAYNAME
83 | postinstall_script
84 | #!/usr/local/munki/munki-python
85 | import subprocess
86 | import sys
87 |
88 | # Populate these options if you want to set specific options for the printer. E.g. duplexing installed, etc.
89 | printerOptions = { OPTIONS }
90 |
91 | cmd = [ '/usr/sbin/lpadmin', '-x', 'PRINTERNAME' ]
92 | proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
93 | (lpadminxOut, lpadminxErr) = proc.communicate()
94 |
95 | # Install the printer
96 | cmd = [ '/usr/sbin/lpadmin',
97 | '-p', 'PRINTERNAME',
98 | '-L', 'LOCATION',
99 | '-D', 'DISPLAY_NAME',
100 | '-v', 'ADDRESS',
101 | '-P', "DRIVER",
102 | '-E',
103 | '-o', 'printer-is-shared=false',
104 | '-o', 'printer-error-policy=abort-job' ]
105 |
106 | for option in printerOptions.keys():
107 | cmd.append("-o")
108 | cmd.append(str(option) + "=" + str(printerOptions[option]))
109 |
110 | proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
111 | (lpadminOut, lpadminErr) = proc.communicate()
112 |
113 | if lpadminErr:
114 | if "Printer drivers are deprecated" in lpadminErr:
115 | # work around lpadmin deprecation message
116 | print("Install successful - caught deprecation message; preventing exit 1")
117 | pass
118 | else:
119 | print("Error: %s" % lpadminErr)
120 | sys.exit(1)
121 | print("Results: %s" % lpadminOut)
122 | sys.exit(0)
123 | preinstall_script
124 | #!/bin/zsh
125 |
126 | ## Generate the AirPrint PPD using ipp2ppd
127 |
128 | /System/Library/Printers/Libraries/ipp2ppd ADDRESS everywhere > /tmp/PRINTERNAME.ppd
129 |
130 | # Make sure the PPD is where we want it before attempting to install the printer
131 |
132 | if
133 | [[ ! -f /tmp/PRINTERNAME.ppd ]]
134 | then
135 | echo "The PPD doesn't exist where expected, exiting.'"
136 | exit 1
137 | fi
138 | unattended_install
139 |
140 | uninstall_method
141 | uninstall_script
142 | uninstall_script
143 | #!/bin/sh
144 | /usr/sbin/lpadmin -x PRINTERNAME
145 | uninstallable
146 |
147 | version
148 | VERSION
149 |
150 |
151 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
--------------------------------------------------------------------------------
/Printer-Template.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | autoremove
6 |
7 | catalogs
8 |
9 | testing
10 |
11 | category
12 | Printers
13 | description
14 | DESCRIPTION
15 | display_name
16 | DISPLAY_NAME
17 | installcheck_script
18 | #!/usr/local/munki/munki-python
19 | import subprocess
20 | import sys
21 | import shlex
22 |
23 | printerOptions = { OPTIONS }
24 |
25 | cmd = ['/usr/bin/lpoptions', '-p', 'PRINTERNAME', '-l']
26 | proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
27 | (lpoptLongOut, lpoptErr) = proc.communicate()
28 |
29 | # lpoptions -p printername -l will still exit 0 even if printername does not exist
30 | # but it will print to stderr
31 | if lpoptErr:
32 | print(lpoptErr)
33 | sys.exit(0)
34 |
35 | cmd = ['/usr/bin/lpoptions', '-p', 'PRINTERNAME']
36 | proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
37 | (lpoptOut, lpoptErr) = proc.communicate()
38 |
39 | #Note: lpoptions -p printername will never fail. If PRINTERNAME does not exist, it
40 | #will still exit 0, but just produce no output.
41 | #Thanks, cups, I was having a good day until now.
42 |
43 | for option in lpoptLongOut.splitlines():
44 | for myOption in printerOptions.keys():
45 | optionName = option.split("/", 1)[0]
46 | optionValues = option.split("/",1)[1].split(":")[1].strip().split(" ")
47 | for opt in optionValues:
48 | if "*" in opt:
49 | actualOptionValue = opt.replace('*', '')
50 | break
51 | if optionName == myOption:
52 | if not printerOptions[myOption].lower() == actualOptionValue.lower():
53 | print("Found mismatch: %s is '%s', should be '%s'" % (myOption, printerOptions[myOption], actualOptionValue))
54 | sys.exit(0)
55 |
56 | try:
57 | lpoptOut = lpoptOut.decode("utf-8")
58 | except UnicodeDecodeError:
59 | sys.exit(0)
60 |
61 | optionDict = {}
62 | for builtOption in shlex.split(lpoptOut):
63 | try:
64 | optionDict[builtOption.split("=")[0]] = builtOption.split("=")[1]
65 | except:
66 | optionDict[builtOption.split("=")[0]] = None
67 |
68 | comparisonDict = { "device-uri":"ADDRESS", "printer-info":"DISPLAY_NAME", "printer-location":"LOCATION" }
69 | for keyName in comparisonDict.keys():
70 | comparisonDict[keyName] = None if comparisonDict[keyName].strip() == "" else comparisonDict[keyName]
71 | optionDict[keyName] = None if keyName not in optionDict or optionDict[keyName].strip() == "" else optionDict[keyName]
72 | if not comparisonDict[keyName] == optionDict[keyName]:
73 | print("Settings mismatch: %s is '%s', should be '%s'" % (keyName, optionDict[keyName], comparisonDict[keyName]))
74 | sys.exit(0)
75 |
76 | sys.exit(1)
77 | installer_type
78 | nopkg
79 | minimum_os_version
80 | 10.7.0
81 | name
82 | Printer_DISPLAYNAME
83 | postinstall_script
84 | #!/usr/local/munki/munki-python
85 | import subprocess
86 | import sys
87 |
88 | # Populate these options if you want to set specific options for the printer. E.g. duplexing installed, etc.
89 | printerOptions = { OPTIONS }
90 |
91 | cmd = [ '/usr/sbin/lpadmin', '-x', 'PRINTERNAME' ]
92 | proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
93 | (lpadminxOut, lpadminxErr) = proc.communicate()
94 |
95 | # Install the printer
96 | cmd = [ '/usr/sbin/lpadmin',
97 | '-p', 'PRINTERNAME',
98 | '-L', 'LOCATION',
99 | '-D', 'DISPLAY_NAME',
100 | '-v', 'ADDRESS',
101 | '-P', "DRIVER",
102 | '-E',
103 | '-o', 'printer-is-shared=false',
104 | '-o', 'printer-error-policy=abort-job' ]
105 |
106 | for option in printerOptions.keys():
107 | cmd.append("-o")
108 | cmd.append(str(option) + "=" + str(printerOptions[option]))
109 |
110 | proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
111 | (lpadminOut, lpadminErr) = proc.communicate()
112 |
113 | if lpadminErr:
114 | if "Printer drivers are deprecated" in lpadminErr:
115 | # work around lpadmin deprecation message
116 | print("Install successful - caught deprecation message; preventing exit 1")
117 | pass
118 | else:
119 | print("Error: %s" % lpadminErr)
120 | sys.exit(1)
121 | print("Results: %s" % lpadminOut)
122 | sys.exit(0)
123 | unattended_install
124 |
125 | uninstall_method
126 | uninstall_script
127 | uninstall_script
128 | #!/bin/sh
129 | /usr/sbin/lpadmin -x PRINTERNAME
130 | uninstallable
131 |
132 | version
133 | VERSION
134 |
135 |
136 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ### Note: This project was archived by author Nick McSpadden on 8/11/20.
2 | I plan to make additional commits in this fork and continue using it. Pull requests are welcome.
3 |
4 | * [wycomco has another fork](https://github.com/wycomco/PrinterGenerator) that is under active development and is worth checking out.
5 |
6 | PrinterGenerator
7 | ================
8 |
9 | This script will generate a ["nopkg"](https://groups.google.com/d/msg/munki-dev/hmfPZ7sgW6k/q6vIkPIPepoJ) style pkginfo file for [Munki](https://github.com/munki/munki/wiki) to install a printer.
10 |
11 | See [Managing Printers with Munki](https://github.com/munki/munki/wiki/Managing-Printers-With-Munki) for more details.
12 |
13 | ## Usage
14 |
15 | The script can either take arguments on the command line, or a CSV file containing a list of printers with all the necessary information.
16 |
17 | The script will generate a pkginfo file. This pkginfo file is a "nopkg" style, and thus has three separate scripts:
18 |
19 | * installcheck_script
20 | * postinstall_script
21 | * uninstall_script
22 |
23 | The installcheck_script looks for an existing print queue named PRINTERNAME. If it does not find one, it will exit 0 and trigger an installation request. If it does find one, it will compare all of the options provided (DRIVER, ADDRESS, DISPLAYNAME, LOCATION, and OPTIONS) for differences. If there are any differences, it will trigger an installation request.
24 |
25 | The postinstall_script will attempt to delete the existing print queue named PRINTERNAME first, and then will reinstall the queue with the specified options.
26 | *Note that it does not check to see if the printer queue is in use at the time, so it is possible that existing print jobs will be cancelled if a user is printing when a Munki reinstall occurs.*
27 |
28 | The uninstall_script will delete the printer queue named PRINTERNAME if uninstallation is triggered.
29 |
30 | ### Using a CSV file:
31 |
32 | A template CSV file is provided to make it easy to generate multiple pkginfos in one run. Pass the path to the csv file with `--csv`:
33 |
34 | ```
35 | ./print_generator.py --csv /path/to/printers.csv
36 | ```
37 | *Note: if a CSV file is provided, all other command line arguments are ignored.*
38 |
39 | The CSV file's columns should be pretty self-explanatory:
40 |
41 | * Printer name: Name of the print queue
42 | * Location: The "location" of the printer
43 | * Display name: The visual name that shows up in the Printers & Scanners pane of the System Preferences, and in the print dialogue boxes. Also used in the Munki pkginfo.
44 | * Address: The IP or DNS address of the printer. The template uses the form: `lpr://ADDRESS`. Change to another protocol in the template if necessary.
45 | * Driver: Name of the driver file in /Library/Printers/PPDs/Contents/Resources/.
46 | * Description: Used only in the Munki pkginfo.
47 | * Options: Any printer options that should be specified. These **must** be space-delimited key=value pairs, such as "HPOptionDuplexer=True OutputMode=normal". **Do not use commas to separate the options, because this is a comma-separated values file.**
48 | * Version: Used only in the Munki pkginfo.
49 | * Requires: Required packages for Munki pkginfo. These **must** be space-delimited, such as "CanonDriver1 CanonDriver2".
50 | * Icon: Optionally specify an existing icon in the Munki repo to display for the printer in Managed Software Center.
51 |
52 | The CSV file is not sanity-checked for invalid entries or blank fields, so double check your file and test your pkginfos thoroughly.
53 |
54 | ### Command-line options:
55 |
56 | A full description of usage is available with:
57 |
58 | ```
59 | ./print_generator.py -h
60 | usage: print_generator.py [-h] [--printername PRINTERNAME] [--driver DRIVER]
61 | [--address ADDRESS] [--location LOCATION]
62 | [--displayname DISPLAYNAME] [--desc DESC]
63 | [--requires REQUIRES]
64 | [--options [OPTIONS [OPTIONS ...]]]
65 | [--version VERSION] [--icon ICON] [--csv CSV]
66 |
67 | Generate a Munki nopkg-style pkginfo for printer installation.
68 |
69 | optional arguments:
70 | -h, --help show this help message and exit
71 | --printername PRINTERNAME
72 | Name of printer queue. May not contain spaces, tabs, #
73 | or /. Required.
74 | --driver DRIVER Name of driver file in
75 | /Library/Printers/PPDs/Contents/Resources/. Can be
76 | relative or full path. Required.
77 | --address ADDRESS IP or DNS address of printer. If no protocol is
78 | specified, defaults to lpd://. Required.
79 | --location LOCATION Location name for printer. Optional. Defaults to
80 | printername.
81 | --displayname DISPLAYNAME
82 | Display name for printer (and Munki pkginfo).
83 | Optional. Defaults to printername.
84 | --desc DESC Description for Munki pkginfo only. Optional.
85 | --requires REQUIRES Required packages in form of space-delimited
86 | 'CanonDriver1 CanonDriver2'. Optional.
87 | --options [OPTIONS [OPTIONS ...]]
88 | Printer options in form of space-delimited
89 | 'Option1=Key Option2=Key Option3=Key', etc. Optional.
90 | --version VERSION Version number of Munki pkginfo. Optional. Defaults to
91 | 1.0.
92 | --icon ICON Name of exisiting icon in Munki repo. Optional.
93 | --csv CSV Path to CSV file containing printer info. If CSV is
94 | provided, all other options are ignored.
95 | ```
96 |
97 | As in the above CSV section, the arguments are all the same:
98 |
99 | * `--printername`: Name of the print queue. May not contain spaces, tabs, "#" or "/" characters. **Required.**
100 | * `--driver`: Name of the driver file in /Library/Printers/PPDs/Contents/Resources/. This can be either a relative path (i.e. the filename in the path above), or a full path (starting with "/Library"). **Required.**
101 | * `--address`: The IP or DNS address of the printer. If no protocol is specified, `lpd://ADDRESS` will be used. **Required.**
102 | * `--location`: The "location" of the printer. If not provided, this will default to the value of `--printername`.
103 | * `--displayname`: The visual name that shows up in the Printers & Scanners pane of the System Preferences, and in the print dialogue boxes. Also used in the Munki pkginfo. If not provided, this will default to the value of `--printername`.
104 | * `--desc`: Used only in the Munki pkginfo. If not provided, will default to an empty string ("").
105 | * `--requires`: Add required packages in the Munki pkginfo. If not provided, no packages will be required.
106 | * `--options`: Any number of printer options that should be specified. These should be space-delimited key=value pairs, such as "HPOptionDuplexer=True OutputMode=normal".
107 | * `--version`: The version number of the Munki pkginfo. Defaults to "1.0".
108 | * `--icon`: Used only in the Munki pkginfo. If not provided, will default to an empty string ("").
109 |
110 | ### Figuring out options:
111 |
112 | Printer options can be determined by using `lpoptions` on an existing printer queue:
113 | `/usr/bin/lpoptions -p YourPrinterQueueName -l`
114 |
115 | Here's a snip of output:
116 |
117 | ```
118 | OutputMode/Quality: high-speed-draft fast-normal *normal best highest
119 | HPColorMode/Color: *colorsmart colorsync grayscale
120 | ColorModel/Color Model: *RGB RGBW
121 | HPPaperSource/Source: *Tray1
122 | Resolution/Resolution: *300x300dpi 600x600dpi 1200x1200dpi
123 | ```
124 |
125 | Options typically have the actual PPD option name on the left side of the /, and a display name (which is likely to show up in the printer settings dialogue boxes) on the right of the /. The possible values for the printer are listed after the colon. The current option is marked with an "*".
126 |
127 | Despite `lpoptions` using a "Name/Nice Name: Value *Value Value" format, the option must be specified more strictly:
128 | "HPColorMode=grayscale"
129 |
130 | This is the format you must use when passing options to `--options`, or specifying them in the CSV file.
131 |
132 | *Note that `/usr/bin/lpoptions -l` without specifying a printer will list options for the default printer.*
133 |
134 |
135 | ### Example:
136 | ```
137 | ./print_generator.py --printername="MyPrinterQueue" \
138 | --driver="HP officejet 5500 series.ppd.gz" \
139 | --address="10.0.0.1" \
140 | --location="Tech Office" \
141 | --displayname="My Printer Queue" \
142 | --desc="Black and white printer in Tech Office" \
143 | --requires="CanonPrinterDriver" \
144 | --options="HPOptionDuplexer=True OutputMode=normal" \
145 | --icon="HP LaserJet 4250.icns" \
146 | --version=1.5
147 | ```
148 |
149 | The output pkginfo file generated:
150 |
151 | ```
152 |
153 |
154 |
155 |
156 | autoremove
157 |
158 | catalogs
159 |
160 | testing
161 |
162 | description
163 | Black and white printer in Tech Office
164 | display_name
165 | My Printer Queue
166 | icon_name
167 | HP LaserJet 4250.icns
168 | installcheck_script
169 | #!/usr/bin/python
170 | import subprocess
171 | import sys
172 | import shlex
173 |
174 | printerOptions = { "HPOptionDuplexer":"True", "OutputMode":"normal" }
175 |
176 | cmd = ['/usr/bin/lpoptions', '-p', 'MyPrinterQueue', '-l']
177 | proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
178 | (lpoptLongOut, lpoptErr) = proc.communicate()
179 |
180 | # lpoptions -p printername -l will still exit 0 even if printername does not exist
181 | # but it will print to stderr
182 | if lpoptErr:
183 | print lpoptErr
184 | sys.exit(0)
185 |
186 | cmd = ['/usr/bin/lpoptions', '-p', 'MyPrinterQueue']
187 | proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
188 | (lpoptOut, lpoptErr) = proc.communicate()
189 |
190 | #Note: lpoptions -p printername will never fail. If MyPrinterQueue does not exist, it
191 | #will still exit 0, but just produce no output.
192 | #Thanks, cups, I was having a good day until now.
193 |
194 | for option in lpoptLongOut.splitlines():
195 | for myOption in printerOptions.keys():
196 | optionName = option.split("/", 1)[0]
197 | optionValues = option.split("/",1)[1].split(":")[1].strip().split(" ")
198 | for opt in optionValues:
199 | if "*" in opt:
200 | actualOptionValue = opt.replace('*', '')
201 | break
202 | if optionName == myOption:
203 | if not printerOptions[myOption].lower() == actualOptionValue.lower():
204 | print "Found mismatch: %s is '%s', should be '%s'" % (myOption, printerOptions[myOption], actualOptionValue)
205 | sys.exit(0)
206 |
207 | optionDict = {}
208 | for builtOption in shlex.split(lpoptOut):
209 | try:
210 | optionDict[builtOption.split("=")[0]] = builtOption.split("=")[1]
211 | except:
212 | optionDict[builtOption.split("=")[0]] = None
213 |
214 | comparisonDict = { "device-uri":"lpd://10.0.0.1", "printer-info":"My Printer Queue", "printer-location":"Tech Office" }
215 | for keyName in comparisonDict.keys():
216 | if not comparisonDict[keyName] == optionDict[keyName]:
217 | print "Settings mismatch: %s is '%s', should be '%s'" % (keyName, optionDict[keyName], comparisonDict[keyName])
218 | sys.exit(0)
219 |
220 | sys.exit(1)
221 | installer_type
222 | nopkg
223 | minimum_os_version
224 | 10.7.0
225 | name
226 | AddPrinter_MyPrinterQueue
227 | postinstall_script
228 | #!/usr/bin/python
229 | import subprocess
230 | import sys
231 |
232 | # Populate these options if you want to set specific options for the printer. E.g. duplexing installed, etc.
233 | printerOptions = { "HPOptionDuplexer":"True", "OutputMode":"normal" }
234 |
235 | cmd = [ '/usr/sbin/lpadmin', '-x', 'MyPrinterQueue' ]
236 | proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
237 | (lpadminxOut, lpadminxErr) = proc.communicate()
238 |
239 | # Install the printer
240 | cmd = [ '/usr/sbin/lpadmin',
241 | '-p', 'MyPrinterQueue',
242 | '-L', 'Tech Office',
243 | '-D', 'My Printer Queue',
244 | '-v', 'lpd://10.0.0.1',
245 | '-P', "/Library/Printers/PPDs/Contents/Resources/HP officejet 5500 series.ppd.gz",
246 | '-E',
247 | '-o', 'printer-is-shared=false',
248 | '-o', 'printer-error-policy=abort-job' ]
249 |
250 | for option in printerOptions.keys():
251 | cmd.append("-o")
252 | cmd.append(str(option) + "=" + str(printerOptions[option]))
253 |
254 | proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
255 | (lpadminOut, lpadminErr) = proc.communicate()
256 |
257 | if lpadminErr:
258 | print "Error: %s" % lpadminErr
259 | sys.exit(1)
260 | print "Results: %s" % lpadminOut
261 | sys.exit(0)
262 | requires
263 |
264 | CanonPrinterDriver
265 |
266 | unattended_install
267 |
268 | uninstall_method
269 | uninstall_script
270 | uninstall_script
271 | #!/bin/bash
272 | /usr/sbin/lpadmin -x MyPrinterQueue
273 | uninstallable
274 |
275 | version
276 | 1.5
277 |
278 |
279 | ```
280 |
--------------------------------------------------------------------------------
/Template.csv:
--------------------------------------------------------------------------------
1 | Printer Name,Location,Display Name,Address,Driver,Description,Options,Version,Requires,Munki Icon
2 | MyPrinterQueue,Tech Office,My Printer Queue,10.0.0.1,HP officejet 5500 series.ppd.gz,Black and white printer in Tech Office,HPOptionDuplexer=True OutputMode=normal,1.0,HPPrinterDriver,HP LaserJet 4250.png
3 |
--------------------------------------------------------------------------------
/print_generator.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/munki/munki-python
2 |
3 | # Version 1.21
4 | # Updated 3/17/22
5 |
6 | from __future__ import absolute_import, print_function
7 |
8 | import argparse
9 | import csv
10 | import os
11 | import re
12 | import sys
13 |
14 | try:
15 | from plistlib import load as load_plist # Python 3
16 | from plistlib import dump as dump_plist
17 | except ImportError:
18 | from plistlib import readPlist as load_plist # Python 2
19 | from plistlib import writePlist as dump_plist
20 |
21 |
22 | def getOptionsString(optionList):
23 | # optionList should be a list item
24 | optionsString = ''
25 | for option in optionList:
26 | if option == optionList[-1]:
27 | optionsString += "\"%s\":\"%s\"" % (str(option.split('=')[0]), str(option.split('=')[1]))
28 | else:
29 | optionsString += "\"%s\":\"%s\"" % (str(option.split('=')[0]), str(option.split('=')[1])) + ', '
30 | return optionsString
31 |
32 | parser = argparse.ArgumentParser(description='Generate a Munki nopkg-style pkginfo for printer installation.')
33 | parser.add_argument('--printername', help='Name of printer queue. May not contain spaces, tabs, # or /. Required.')
34 | parser.add_argument('--driver', help='Name of driver file in /Library/Printers/PPDs/Contents/Resources/. Can be relative or full path. Required.')
35 | parser.add_argument('--address', help='IP or DNS address of printer. If no protocol is specified, defaults to lpd://. Required.')
36 | parser.add_argument('--location', help='Location name for printer. Optional. Defaults to printername.')
37 | parser.add_argument('--displayname', help='Display name for printer (and Munki pkginfo). Optional. Defaults to printername.')
38 | parser.add_argument('--desc', help='Description for Munki pkginfo only. Optional.')
39 | parser.add_argument('--requires', help='Required packages in form of space-delimited \'CanonDriver1 CanonDriver2\'. Optional.')
40 | parser.add_argument('--options', nargs='*', dest='options', help='Printer options in form of space-delimited \'Option1=Key Option2=Key Option3=Key\', etc. Optional.')
41 | parser.add_argument('--version', help='Version number of Munki pkginfo. Optional. Defaults to 1.0.', default='1.0')
42 | parser.add_argument('--icon', help='Specifies an existing icon in the Munki repo to display for the printer in Managed Software Center. Optional.')
43 | parser.add_argument('--csv', help='Path to CSV file containing printer info. If CSV is provided, all other options are ignored.')
44 | args = parser.parse_args()
45 |
46 |
47 | pwd = os.path.dirname(os.path.realpath(__file__))
48 | f = open(os.path.join(pwd, 'Printer-Template.plist'), 'rb')
49 | templatePlist = load_plist(f)
50 | f.close()
51 |
52 | if args.csv:
53 | # A CSV was found, use that for all data.
54 | with open(args.csv, mode='r') as infile:
55 | reader = csv.reader(infile)
56 | next(reader, None) # skip the header row
57 | for row in reader:
58 | newPlist = dict(templatePlist)
59 | # each row contains 10 elements:
60 | # Printer name, location, display name, address, driver, description, options, version, requires, icon
61 | # options in the form of "Option=Value Option2=Value Option3=Value"
62 | # requires in the form of "package1 package2" Note: the space seperator
63 | theOptionString = ''
64 | if row[6] != "":
65 | theOptionString = getOptionsString(row[6].split(" "))
66 | # First, change the plist keys in the pkginfo itself
67 | newPlist['display_name'] = row[2]
68 | newPlist['description'] = row[5]
69 | newPlist['name'] = "Printer_" + str(row[0]) # set to printer name
70 | # Check for an icon
71 | if row[9] != "":
72 | newPlist['icon_name'] = row[9]
73 | # Check for a version number
74 | if row[7] != "":
75 | # Assume the user specified a version number
76 | version = row[7]
77 | else:
78 | # Use the default version of 1.0
79 | version = "1.0"
80 | newPlist['version'] = version
81 | # Check for a protocol listed in the address
82 | if '://' in row[3]:
83 | # Assume the user passed in a full address and protocol
84 | address = row[3]
85 | else:
86 | # Assume the user wants to use the default, lpd://
87 | address = 'lpd://' + row[3]
88 | # Append the driver path to the driver file specified in the csv
89 | driver = '/Library/Printers/PPDs/Contents/Resources/%s' % row[4]
90 |
91 | # Now change the variables in the installcheck_script
92 | newPlist['installcheck_script'] = newPlist['installcheck_script'].replace("PRINTERNAME", row[0])
93 | newPlist['installcheck_script'] = newPlist['installcheck_script'].replace("OPTIONS", theOptionString)
94 | newPlist['installcheck_script'] = newPlist['installcheck_script'].replace("LOCATION", row[1].replace('"', ''))
95 | newPlist['installcheck_script'] = newPlist['installcheck_script'].replace("DISPLAY_NAME", row[2].replace('"', ''))
96 | newPlist['installcheck_script'] = newPlist['installcheck_script'].replace("ADDRESS", address)
97 | # Now change the variables in the postinstall_script
98 | newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("PRINTERNAME", row[0])
99 | newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("LOCATION", row[1].replace('"', ''))
100 | newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("DISPLAY_NAME", row[2].replace('"', ''))
101 | newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("ADDRESS", address)
102 | newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("DRIVER", driver)
103 | newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("OPTIONS", theOptionString)
104 | # Now change the one variable in the uninstall_script
105 | newPlist['uninstall_script'] = newPlist['uninstall_script'].replace("PRINTERNAME", row[0])
106 | # Add required packages if passed in the csv
107 | if row[8] != "":
108 | newPlist['requires'] = row[8].split(' ')
109 | # Write out the file
110 | newFileName = "Printer-" + row[0] + "-" + version + ".pkginfo"
111 | f = open(newFileName, 'wb')
112 | dump_plist(newPlist, f)
113 | f.close()
114 | else:
115 | if not args.printername:
116 | print(os.path.basename(sys.argv[0]) + ': error: argument --printername is required', file=sys.stderr)
117 | parser.print_usage()
118 | sys.exit(1)
119 | if not args.driver:
120 | print(os.path.basename(sys.argv[0]) + ': error: argument --driver is required', file=sys.stderr)
121 | parser.print_usage()
122 | sys.exit(1)
123 | if not args.address:
124 | print(os.path.basename(sys.argv[0]) + ': error: argument --address is required', file=sys.stderr)
125 | parser.print_usage()
126 | sys.exit(1)
127 |
128 | if re.search(r"[\s#/]", args.printername):
129 | # printernames can't contain spaces, tabs, # or /. See lpadmin manpage for details.
130 | print("ERROR: Printernames can't contain spaces, tabs, # or /.", file=sys.stderr)
131 | sys.exit(1)
132 |
133 | if args.desc:
134 | description = args.desc
135 | else:
136 | description = ""
137 |
138 | if args.displayname:
139 | displayName = args.displayname
140 | else:
141 | displayName = str(args.printername)
142 |
143 | if args.location:
144 | location = args.location
145 | else:
146 | location = args.printername
147 |
148 | if args.version:
149 | version = str(args.version)
150 | else:
151 | version = "1.0"
152 |
153 | if args.requires:
154 | requires = args.requires
155 | else:
156 | requires = ""
157 |
158 | if args.icon:
159 | icon = args.icon
160 | else:
161 | icon = ""
162 |
163 | if args.options:
164 | optionsString = str(args.options[0]).split(' ')
165 | optionsString = getOptionsString(optionsString)
166 | else:
167 | optionsString = ''
168 |
169 | if args.driver.startswith('/Library'):
170 | # Assume the user passed in a full path rather than a relative filename
171 | driver = args.driver
172 | else:
173 | # Assume only a relative filename
174 | driver = os.path.join('/Library/Printers/PPDs/Contents/Resources', args.driver)
175 |
176 | if '://' in args.address:
177 | # Assume the user passed in a full address and protocol
178 | address = args.address
179 | else:
180 | # Assume the user wants to use the default, lpd://
181 | address = 'lpd://' + args.address
182 |
183 | newPlist = dict(templatePlist)
184 | # root pkginfo variable replacement
185 | newPlist['description'] = description
186 | newPlist['display_name'] = displayName
187 | newPlist['name'] = "Printer_" + args.printername
188 | newPlist['version'] = version
189 | newPlist['icon_name'] = icon
190 | # installcheck_script variable replacement
191 | newPlist['installcheck_script'] = templatePlist['installcheck_script'].replace("PRINTERNAME", args.printername)
192 | newPlist['installcheck_script'] = newPlist['installcheck_script'].replace("ADDRESS", address)
193 | newPlist['installcheck_script'] = newPlist['installcheck_script'].replace("DISPLAY_NAME", displayName)
194 | newPlist['installcheck_script'] = newPlist['installcheck_script'].replace("LOCATION", location.replace('"', ''))
195 | newPlist['installcheck_script'] = newPlist['installcheck_script'].replace("OPTIONS", optionsString)
196 | # postinstall_script variable replacement
197 | newPlist['postinstall_script'] = templatePlist['postinstall_script'].replace("PRINTERNAME", args.printername)
198 | newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("ADDRESS", address)
199 | newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("DISPLAY_NAME", displayName)
200 | newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("LOCATION", location.replace('"', ''))
201 | newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("DRIVER", driver.replace('"', ''))
202 | newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("OPTIONS", optionsString)
203 | # uninstall_script variable replacement
204 | newPlist['uninstall_script'] = templatePlist['uninstall_script'].replace("PRINTERNAME", args.printername)
205 | # required packages
206 | if requires != "":
207 | newPlist['requires'] = [r.replace('\\', '') for r in re.split(r"(?