- 1 year ago
How to open printer in network share or how to enumerate list of network share printer?
To open a printer in a network share or enumerate a list of network share printers, you can use the EnumPrinters
function in the Windows API. Here's an example of how to use this function in Python:
pythonimport win32print
import win32api
# Define the name of the print server and the share name
print_server = r'\\print_server'
share_name = 'Printers'
# Get a handle to the print server
printer_handle = win32print.OpenPrinter(print_server)
# Enumerate the list of printers on the server
printer_info = win32print.EnumPrinters(win32print.PRINTER_ENUM_NAME, print_server, 2)
# Loop through the list of printers and print the name of each printer
for printer in printer_info:
if printer['pShareName'].startswith(share_name):
# Get the printer handle for the current printer
printer_name = fr"{print_server}\{printer['pPrinterName']}"
printer_handle = win32print.OpenPrinter(printer_name)
# Do something with the printer handle, such as print a test page
win32api.ShellExecute(0, "print", r"C:\test_page.pdf", None, ".", 0)
# Close the printer handle
win32print.ClosePrinter(printer_handle)
In this example, we use the win32print
module to interact with the Windows API. We first define the name of the print server and the share name of the printers we want to enumerate. We then get a handle to the print server using the OpenPrinter
function, and enumerate the list of printers on the server using the EnumPrinters
function. We loop through the list of printers and print the name of each printer, and then open a printer handle for each printer using the OpenPrinter
function. Finally, we do something with the printer handle, such as print a test page, and then close the printer handle using the ClosePrinter
function.
Note that you may need to have administrative privileges on the print server in order to perform some of these operations.