Linux добавить принтер через консоль

Command-Line Printer Administration

This help document describes how to configure and manage destinations with CUPS.

Introduction

Destinations are individual printers and classes (pools) of printers. Printers use a description file with one or more driver («filter») programs that communicate with the printer through a «backend» program. CUPS currently uses PPD (PostScript Printer Description) files to describe the printer and driver programs needed, some of which come with CUPS while others come with your operating system or Linux distribution. Backends are specified using a URI (Universal Resource Identifier) where the URI scheme is the backend name, e.g., «ipp://11.22.33.44/ipp/print» specifies the «ipp» backend — like PPD files, some backends come with CUPS while others come with your operating system.

Classes are associated with one or more printers and are typically used to distribute print jobs amongst a group of printers or provide redundancy or high availability when printing. Print jobs sent to a class are forwarded to the next available printer in the class.

The lpadmin(8) program is used to add, modify, or delete destinations, while the lpinfo(8) command is used to list the available printer drivers and backends. The cupsctl(8) program is used to manage the printing system as a whole, including things like debug logging and printer sharing. The CUPS web interface («http://localhost:631» or «https://servername:631») can also be used, and most operating systems provide their own GUI administration tools.

Managing Printers

The lpadmin command is used to create, modify, or delete a printer. The -p option specifies a printer to create or modify:

The lpadmin accepts several additional options after -p printername when adding or modifying a printer:

-D «description» Sets the description of the printer which is often shown instead of the printer name, for example «HP LaserJet». -E Enables the printer and accepts new print jobs. -L «location» Sets the location of the printer, for example «Conference Room». -m model Sets the printer driver using the model name. -o option=value Sets the named option. -v device-uri Sets the URI for the printer.

The -x option deletes the named printer:

Printer Drivers and PPDs

The -m option to lpadmin specifies the driver («model») to use for the printer. You can run the lpinfo -m command to list all of the available drivers («models») on your system:

Each line contains the driver name followed by its description, for example:

drv:///sample.drv/dymo.ppd Dymo Label Printer drv:///sample.drv/epson9.ppd Epson 9-Pin Series drv:///sample.drv/epson24.ppd Epson 24-Pin Series drv:///sample.drv/generpcl.ppd Generic PCL Laser Printer drv:///sample.drv/generic.ppd Generic PostScript Printer drv:///sample.drv/deskjet.ppd HP DeskJet Series drv:///sample.drv/laserjet.ppd HP LaserJet Series PCL 4/5 drv:///sample.drv/intelbar.ppd Intellitech IntelliBar Label Printer, 2.1 drv:///sample.drv/okidata9.ppd Oki 9-Pin Series drv:///sample.drv/okidat24.ppd Oki 24-Pin Series drv:///sample.drv/zebracpl.ppd Zebra CPCL Label Printer drv:///sample.drv/zebraep1.ppd Zebra EPL1 Label Printer drv:///sample.drv/zebraep2.ppd Zebra EPL2 Label Printer drv:///sample.drv/zebra.ppd Zebra ZPL Label Printer everywhere IPP Everywhere

The everywhere driver is used for nearly all modern networks printers sold since about 2009. For example, the following command creates a destination for a printer at IP address 11.22.33.44:

lpadmin -p printername -E -v ipp://11.22.33.44/ipp/print -m everywhere

The CUPS sample drivers (the «drv:///sample.drv/. » lines above) can be used for «legacy» printers. For example, the following command creates a destination for a HP LaserJet printer at IP address 11.22.33.44:

lpadmin -p printername -E -v socket://11.22.33.44 -m drv:///sample.drv/laserjet.ppd

Note: The CUPS sample drivers are designed to provide basic printing capabilities for the broadest range of printers possible, but generally do not exercise the full potential of the printers or CUPS. Other drivers (including the everywhere driver) provide greater printing capabilities and better print quality.

Device URIs (Backends)

CUPS comes with several standard backends that communicate with printers:

  1. dnssd : The Bonjour (DNS-SD) protocol.
  2. ipp : The Internet Printing Protocol (IPP) with optional encryption.
  3. ipps : The Internet Printing Protocol with mandatory encryption.
  4. lpd : The Line Printer Daemon protocol.
  5. socket : The AppSocket (JetDirect) protocol.
  6. usb : The Universal Serial Bus (USB) printer class.
Читайте также:  Foxit reader astra linux

Run the lpinfo -v command to list the available backends and printers:

Each line contains the backend «class» followed by the backend name or a full printer device URI, for example:

network lpd network ipps network ipp network socket network dnssd://Acme%20Laser%20Pro._ipp._tcp.local./?uuid=545253fb-1cb7-4d8d-98ed-ab6cd607cea7 network dnssd://Bar99._printer.tcp.local./?uuid=f9efff58-9086-4c95-accb-81dee876a475 network dnssd://Example%20EX-42._ipps._tcp.local./?uuid=4a0c67ad-2824-4ddf-9115-7d4226c5fe65 network dnssd://Foo%20Fighter-1969._pdl-datastream._tcp.local./?uuid=4e216bea-c3de-4f65-a710-c99e11c80d2b direct usb://ZP/LazerJet%20MFP?serial=42

The network class of backends is used for all network protocols. The Using Network Printers help document describes how to use the standard CUPS network backends. The direct class of backends is used for directly-connected printers such as USB and Bluetooth. Because these backends use a system-specific identifier, you should only use the reported device URIs.

Once you know the correct URI for the printer, set it using the lpadmin command’s -v option:

lpadmin -p printername -v device-uri

Printer Options

The lpadmin command allows you to set various options for a printer:

-o cupsIPPSupplies=false Turns off IPP supply level reporting for a printer. -o cupsSNMPSupplies=false Turns off SNMP supply level reporting for a printer. -o name=value Sets the default value for the named PPD option. For example, -o PageSize=Legal sets the default page size to US Legal. -o printer-error-policy=name Sets the policy for errors such as printers that cannot be found or accessed, don’t support the format being printed, fail during submission of the print data, or cause one or more filters to crash: abort-job Aborts the job on error. retry-job Retries the job at a future time. retry-current-job Retries the current job immediately. stop-printer Stops the printer on error. -o printer-is-shared=true/false Enables/disables per-printer sharing. See the section on Printer Sharing for more information. -o printer-op-policy=name Sets the operation policy associated with the printer. See the Managing Operation Policies help document for more information. -u allow:<,user|,@group>* -u allow:all -u deny:<,user|,@group>* -u deny:none Sets user-level access control for the printer. The allow: list defines a whitelist of users and groups while the deny: list defines a blacklist of users and groups.

Читайте также:  Linux find вложенные папки

Printer Sharing

CUPS supports sharing of printers with other computers and mobile devices. Two cupsctl options control the general printer sharing features:

—share-printers Enables sharing of printers with other computers and mobile devices on your local network. —remote-any Expands printer sharing to any network that can reach your server.

Once you have enabled printer sharing, you then must select which printers will be shared using the lpadmin command and the -o printer-is-shared=true option.

For example, to share two printers («foo» and «bar») on the local network, run the following commands:

cupsctl --share-printers lpadmin -p foo -o printer-is-shared=true lpadmin -p bar -o printer-is-shared=true

Managing Classes

The lpadmin command is used to create, modify, or delete a class. The -c option specifies a class to create or modify and is combined with the -p option:

lpadmin -p printername -c classname

The -r option specifies that the named printer is removed from the class:

lpadmin -p printername -r classname

The -x option deletes the named class:

Debug Logging and Troubleshooting

The printing system log files track the activity of the scheduler, printer drivers, and backends. If problems occur and the log files do not provide sufficient details to diagnose the problem, you can enable debug logging using the cupsctl command:

To disable debug logging, run the same command with the —no-debug-logging option:

Источник

создать принтер из командной строки

создать принтер (точнее, очередь печати) можно, например, с помощью встроенного в cups веб-интерфейса — http://localhost:631 (или каким-нибудь gui-конфигуратором). а как это сделать из командной строки? для автоматизации этого процесса, например.

1 ответ 1

«штатное» средство, идущее в комплекте с набором программ, именуемым для краткости cups, называется lpadmindebian-основных дистрибутивах входит в пакет cups-client).

для создания/модификации очереди печати служит такая форма запуска этой программы:

$ lpadmin -p имя_очереди [разные опции] 

(есть ещё две формы: удаления очереди — lpadmin -x имя_очереди , и назначение очереди по умолчанию — lpadmin -d имя_очереди ).

Читайте также:  Linux check what file system on

если указанной очереди ещё не было — она создаётся. если уже была, то этой командой можно изменить опции существующей очереди.

запускаться программа должна либо от имени пользователя, входящего в группу, которой разрешено администрирование cups-а (обычно — lpadmin ), тогда, вероятно, надо будет указать полный путь к ней — /usr/sbin/lpadmin , либо от имени пользователя root (т.е., например, с использованием sudo : sudo lpadmin . ).

«минимальный джентльменский набор» разных опций , пожалуй, можно свести к такому списку:

  • -E — сразу сделать очередь доступной (эта опция, если её употребить до опций -p / -d / -x означает совсем другое — «использовать шифрование при подлючении к cups-серверу». ну, такие вот выдумщики эти разработчики)
  • -v uri-принтера — uri, по которому доступен принтер. для «сетевых», поддерживающих спецификацию «hp jetdirect», это что-нибудь вроде socket://сетевое.имя:9100 (подробнее про «сетевые» uri)
  • -o media=A4 — iso-формат бумаги («европейский»). лучше указать явно, чтобы не нарваться на «североамериканский» (см. про letter и a4)
  • -m uri-фильтра или -P /путь/к/файлу/с/фильтром — см. примечание
$ lpadmin -p имя_очереди -E -v uri-принтера -o media=A4 -m uri-фильтра 
$ lpadmin -p имя_очереди -E -v uri-принтера -o media=A4 -P /путь/к/файлу/с/фильтром 

примечание про фильтры

cups позволяет, для адаптации задания печати под конкретную модель принтера, пропустить задание через фильтр — так называемый postscript printer description, сокращённо ppd (отсюда и знакомые многим суффиксы .ppd у файлов с такими фильтрами).

теоретически, если принтер достаточно «интеллектуален», в качестве uri-фильтра можно указать raw : -m raw . в документации по этому поводу написано так:

The model «raw» clears any existing PPD file and the model «everywhere» queries the printer referred to by the specified IPP device-uri.

но обычно фильтр (ppd) указывают явно, выбирая производителя, а затем модель принтера. это если очередь создаётся из веб-интерфейса или с помощью gui-конфигуратора. а в случае командной строки всё это разнообразие можно посмотреть командой:

программа lpinfo тоже может располагаться в /usr/sbin , тогда придётся указать к ней полный путь.

пример вывода для псевдо-модели HP LaserJet 6P :

$ lpinfo --make-and-model 'HP LaserJet 6P' -m gutenprint.5.2://hp-lj_6p/expert HP LaserJet 6P - CUPS+Gutenprint v5.2.9 foomatic:HP-LaserJet_6P-lj4dith.ppd HP LaserJet 6P Foomatic/lj4dith foomatic:HP-LaserJet_6P-ljet4.ppd HP LaserJet 6P Foomatic/ljet4 drv:///hpijs.drv/hp-laserjet_6p-hpijs.ppd HP LaserJet 6p hpijs, 3.12.6 drv:///hpcups.drv/hp-laserjet_6p.ppd HP LaserJet 6p, hpcups 3.12.6 postscript-hp:0/ppd/hplip/HP/hp-laserjet_6mp-ps.ppd HP LaserJet 6P/6MP - PostScript postscript-hp:1/ppd/hplip/HP/hp-laserjet_6mp-ps.ppd HP LaserJet 6P/6MP - PostScript 

из него можно взять, например, пятую строку и использовать в качестве uri-фильтра при вызове lpadmin: -m drv:///hpcups.drv/hp-laserjet_6p.ppd

также нередко случается, что нужно использовать уже «готовый» фильтр, хранящийся в файле с суффиксом .ppd . тогда и надо применять опцию -P /путь/к/файлу.ppd (вместо -m uri-фильтра ).

вышеописанное, в принципе, должно подойти не только к операционной системе gnu/linux, но и, например, к apple/macosx.

вероятно, стоит ещё упомянуть про то, как посмотреть список доступных очередей печати:

Источник

Оцените статью
Adblock
detector