Сервер печати linux windows

В офисной сети вы можете печатать напрямую с Linux устройств на общие сетевые принтеры, подключенные к Windows компьютерами. В этой статье мы покажем, как настроить печать из Linux на сетевой принтер, опубликованный на компьютере с Windows 10/11.

  1. Начнем с настройки Windows компьютера, к которому подключен принтер.Опубликуйте общий сетевой принтер в Windows. Откройте консоль управления принтерами (
    printmanagement.msc
    ), откройте свойства принтера, перейдите на вкладку Sharing, включите опцию Share this printer и задайте сетевое имя принтера (имя не должно содержать пробелы или спец символы);
  2. Создайте отдельного локального пользователя winusr1 с известным паролем. Можно удалить пользователя из локальной группы Users, сделать срок действия пароля не ограниченным и запретить менять пароль.

    Можно с помощью PowerShell создать локального пользователя с указанными настройками:
    $pass = ConvertTo-SecureString "p-0m-2024" -AsPlainText -Force
    New-LocalUser -Name winusr1 -Password $pass -PasswordNeverExpires -UserMayNotChangePassword
    Remove-LocalGroupMember -Group Users -Member winusr1

По умолчанию в Windows сетевые принтеры доступны по протоколу SMB. Чтобы проверить доступ к принтеру из Linux, установите smbclient:

В Ubuntu/Debian выполните команду:

$ sudo apt install smbclient

Чтобы вывести список SMB ресурсов на удаленном компьютере

$ smbclient -L \\192.168.31.94 -U winusr1

Где:

  • 192.168.31.94 – IP адрес или имя компьютера с Windows
  • winusr1 – имя пользователя Windows

Команда выведет список опубликованных сетевых папок (в том числе общих административных папок) и принтеров.

Из консоли вы можете проверить доступность SMB принтера и отправить файл на печать:

$ smbclient -W DOMAIN -U winusr1//192.168.31.94/HPM1530

Распечатать указанный файл:
smb: \> print /home/sysops/test.txt

printing file test.txt as test.txt (196,6 kb/s) (average 196,6 kb/s)

smb: \> quit

Для удобного доступа к сетевым принтерам и их управлением проще всего воспользоваться встроенным сервером печати для Linux – CUPS (Common UNIX Printing System). Для управления CUPS используется веб интерфейс system-config-printer.

В большинстве десктопных дистрибутивов Linux пакет CUPS и system-config-printer установлены по умолчанию. Проверьте это (если нужно, установите):
$ dpkg -l cups
$ dpkg -l system-config-printer
$ systemctl status cups

Теперь можно подключить сетевой принтер в Linux:

  1. Откройте веб-интерфейс CUPS, перейдя в браузере по URL
    localhost:631
    ;
  2. Перейдите в Administration -> Add printer -> Other network printers -> Windows Printer via SAMBA;
  3. Укажите параметры подключения к принтеру в формате
    smb://winusr1:[email protected]/HPM1530
    (строка содержит имя пользователя и пароль, имя/IP удаленного Windows хоста и имя принтера);

    Подключение SMB принтера с Windows компьютера в Linux

  4. Затем задайте имя и описание принтера;
  5. На следующем шаге CUPS предложит выбрать производителя принтера и модель (для установки соответствующего драйвера). Список драйверов может быть довольно большим. Для быстрого поиска названия драйвера по модели принтера воспользуйтесь командой:
    $ lpinfo -m| grep 1536

    lpinfo - список доступных драйверов cups

    Выберите найденный драйвер в CUPS.

  6. Установка принтера завершена.

Где найти драйвера для CUPS под Linux. Например, в случае с принтерами HP, в большинстве десктопных дистрибутивов Linux предустановлен пакет HP Linux Printing and Imaging System (HPLIP). В нем содержится драйвера для подавляющего большинства принтеров.

$ dpkg -l hplip

HP Linux Printing and Imaging System (HPLIP)

Можно установить пакет HPLIP вручную:

$ sudo apt install hplip hplip-gui

Аналогичные пакеты с драйверами выпускают и другие вендоры, либо вы можете самостоятельно найти готовый PPD файл для конкретного принтера. Также вы можете использовать огромную библиотеку PPD драйверов печати foomatic (автоматически устанавливается для ubuntu-desktop):

$ apt install foomatic-db-compressed-ppds

Первая попытка отправить документ из Linux на печать в Windows завершилась с ошибкой. Информация об ошибке печати есть логе /var/log/cups/error_log:

E [22/Jan/2024:11:38:35 +0400] [Job 13] SMB connection failed!
E [22/Jan/2024:11:38:35 +0400] [Job 13] Unable to connect to CIFS host:

CUPS: SMB connection failed

Эта ошибка указывает на то, что CUPS не может подключиться к SMB папке принтера на Linux. Причина в том, что по умолчанию для доступа к сетевой папке smbclient Linux использует протокол SMB 1.0, который по умолчанию отключен в Windows 10 и 11.

Чтобы клиент SMB в Linux использовал более безопасный SMB 2 или 3 для подключения, отредактируйте файл /etc/samba/smb.conf. Добавьте в секцию [global] строки:

client min protocol = SMB2
client max protocol = SMB3

Перезапустите CUPS:

$ sudo systemctl restart cups

Теперь клиент Linux сможет успешно отправить задание на общий принтер в Windows.

Также вы можете добавить принтер Windows из командной строки из командой строки CUPS:

Сначала нужно получить название драйвера для вашей модели принтера:

$ lpinfo --make-and-model '1536' -m

Скопируйте полное название драйвера и можете подключить SMB принтер:

$ sudo lpadmin -p HP1536mfp -v smb://winusr1:[email protected]/HPM1536 -m postscript-hp:0/ppd/hplip/HP/hp-laserjet_m1530_mfp_series-ps.ppd

Включить принтер:

$ cupsenable HP1536mfp

Вывести список принтеров:

$ lpsatat -v
$ lpstat -p

Список подключенных SMB принтеров содержимся в файле /etc/cups/printers.conf. Обратите внимание, что в файле в открытом виде содержатся пароль Windows пользователя, который вы используете для подключения к принтеру (поэтому не нужно назначать никаких прав этому пользователю на Window машине).

/etc/cups/printers.conf

В данной статье я хотел поселиться опытом по созданию принт-сервера на базе linux с интеграцией в AD. Под интеграцией понимается ввод linux сервера в домен Windows и расшаривание Cups принтеров через Samba, включая драйвера принтеров. Возможно коряво выразился, но если проще, то это выглядит так — для того, чтобы установить принтер пользователю Windows, достаточно нажать«установить новый принтер», вывести список принтеров в AD и клацнуть на нужный принтер — принтер установится автоматически с установкой всех необходимых драйверов. При этом, все права на управление, доступ, печать подтянутся из AD.

Часть 1. Тонкости настроек

Исходные данные

  • Домен контроллер — Windows Server 2008 R2 (AD, DNS, DHCP) IP — 10.10.15.31
  • Имя домена — INITIAL
  • Принт сервер — ОС linux (я использую OpenSUSE 13.2 x64, kernel 3.16.7-42-default) IP — 10.10.15.11
  • kerberos 1.12.2-24.1
  • winbind 4.2.4-40.1
  • LDAP 2.4.39-8.9.1
  • Samba 4.2.4-40.1
  • CUPS 1.5.4-21.9.1

Предположим, что ОС linux уже установлена и установлены все необходимые пакеты.
На вводе linux в домен Winodws не буду заострять много внимания, тем более, что статей на эту тему предостаточно. Приведу ссылку на довольно неплохую статью — https://habrahabr.ru/post/143190/

Остановлюсь лишь на важных моментах.

Так же, ниже выложу все свои рабочие конфиги вышеуказанных сервисов. Настраивал по разным статьям и мануалам.

Синхронизация времени

Время на linux сервере должно быть идентичным с домен контроллером, иначе в домен не вогнать.
Для этого есть несколько вариантов: на домен контроллере и нашем принт сервере указать одни и те же ntp сервера синхронизации времени или на принт сервере указать IP домен контроллера в качестве ntp сервера. Я настроил по второму варианту.

/etc/ntp.conf
server 10.10.15.31 iburst

Проверить синхронизацию можно так:

print-01:~ # ntpq -p
     remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
*10.10.15.31     85.236.191.80    3 u  888 1024  377    0.698    6.690   7.232

Winbind

/etc/nsswitch.conf
passwd: files winbind
group: files winbind
shadow: files winbind
hosts:	files [dns] wins

Многие утверждают, что данные настройки вообще не нужны для samba, как и kerberos и LDAP, но я люблю все по феншую ))). Ранее я настраивал samba в качестве PDC (Primary Domain Controller) без kerberos и LDAP и все это работало с WinXP клиентами, подтверждаю.

/etc/samba/smb.conf
winbind separator = /
winbind enum users = Yes
winbind enum groups = Yes
winbind use default domain = Yes
winbind nss info = rfc2307
winbind refresh tickets = Yes

Samba

/etc/samba/smb.conf
idmap uid = 500-10000000
idmap gid = 500-10000000
idmap backend = ldap:ldap://10.10.15.31

Данные настройки не рекомендуются самой samba, начиная с каких то версий 3.Х, но во многих статьях они указываются. Если указать данные параметры в новых версиях самбы, то testparm выдаст:

print-01:/etc/samba # testparm -v
Load smb config files from /etc/samba/smb.conf
WARNING: The "idmap backend" option is deprecated
WARNING: The "idmap gid" option is deprecated
WARNING: The "idmap uid" option is deprecated

параметр realm — имя домена должно быть указано заглавными буквами!

realm = DOMAIN.COM

Kerberos

Секция realms — имя домена должно быть указано заглавными буквами!

/etc/krb5.conf
[realms]
DOMAIN.COM = {...

Иначе, можно получить такую ошибку при проверке kerberos

kinit username@DOMAIN.COM
kinit(v5): KDC reply did not match expectations while getting initial credentials

Предположим, что вы настроили необходимые сервисы и успешно ввели linux машину в домен Windows. Перейдем к настройкам CUPS.

CUPS

/etc/cups/cupsd.conf
# Изменим уровень логирования на период отладки
LogLevel debug 

# Системная группа (добавлять, удалять принтеры, менять их конфигурацию может только root)
SystemGroup root

# Слушаем соединения на порту 631 / Listen for connections on Port 631.
Port 631
Listen /run/cups/cups.sock
BrowseLocalProtocols CUPS
BrowseRemoteProtocols CUPS

# Расшариваем принтеры в локальной сети / Show shared printers on the local network.
Browsing On
BrowseOrder allow,deny
BrowseAllow all
BrowseAddress 10.10.15.0/24
BrowseAddress 172.19.2.0/24
BrowseAddress 172.19.3.0/24
BrowseAddress 172.19.4.0/24
# Default authentication type, when authentication is required...
DefaultAuthType Basic
WebInterface Yes

Здесь поясню.

BrowseOrder allow,deny — порядок рассмотрения системой разрешающих и запрещающих директив: все что не разрешено — запрещено.
BrowseAllow all — отображения всех доступных принтеров локальной сети
BrowseAddress — указываем все подсети, из которых нужен доступ к принтерам
DefaultAuthType — тип аутентификации. По умолчанию — Basic.

На счет последнего. Заметил в логох следующее:

/var/log/cups/error_log
cupsdAuthorize: No authentication data provided.

Рекомендации на эту тему нашел две:

— отключить шаринг принтеров в самбе полностью (очень полезно, особенно для сервера печати)
— заменить Basic на None везде, где есть данная опция в cupsd.conf (не почувствовал разницы)

На cups.org вычитал, что значений данной опции может быть 2 — Basic и Negotiate, последняя для аутентификации с использованием kerberos.

В любом случае, данная ошибка никак не влияет на работу cups’a.

# Разрешаем доступ к серверу печати со всех машин локальной сети.
<Location />
  # Allow remote access...
  Order allow,deny
  Allow all
</Location>

Я указал доступ для всех локальных подсетей. В принципе в директиве Allow можно указать разные подсети, так же, как я делал это в BrowseAddress.

Далее настраиваем доступ к административной панели и конфигурационным файлам. Здесь можно так же прописать директиву Allow (в каждую секцию) с указанием подсетей или отдельного IP адреса, с которого/которых можно будет администрировать принтеры. Если не добавлять эту директиву — админить можно будет с любой подсети локалки — равнозначно Allow all.

<Location /admin>
 Order allow,deny
</Location>
<Location /admin/conf>
  AuthType Default
  Require user @SYSTEM
</Location>

На этом настройка cups закончена. Рестартим его. В OpenSUSE это делается через systemctl

systemctl restart cups.service

Теперь можно приступить к настройке принтеров через web интерфейс cups’a. Есть небольшая тонкость — для изменения, добавления, удаления принтеров необходимо заходить в web интерфейс cups по ssl (https), т.е. в веб браузере открываем

https://10.10.15.11:631/ 

Иначе получим такую ошибку:

Добавлять принтеры в cups через web интерфейс задача — довольно тривиальная, поэтому описывать не буду. Единственное, рекомендую на вкладе «Администрирование» проверить включены ли опции:

— Разрешить совместный доступ к принтерам, подключенным к этой системе
— Разрешить печать из Интернета

И при установке принтера, не забывать включать опцию «Разрешить совместный доступ к этому принтеру».

Кто не хочет заморачиваться с samba, в cups есть возможность печати посредством протокола ipp (Internet Printing Protocol). В Windows принтер устанавливается так: панель управления → принтеры → установка принтера → сетевой принтер → подключиться к принтеру в интернете («выбрать общий принтер по имени» для Win7/8/10) в качестве url указываем полный путь:

Например http://10.10.15.11:631/printers/Kyocera_6525_PTO 
Или http://Print-01:631/printers/Kyocera_6525_PTO

Полный путь до принтера можно скопировать из адресной строки браузера в web интерфейсе cups.

Единственное, при данном способе система запросит драйвер принтера. Его нужно будет предварительно скачать и скормить ей при установке.

ГРАБЛЯ_№1: в WinXP протокол ipp включен по дефолту в сервис пак начиная с SP2, в Windows7/8/10 компонент «Интернет печать» может быть не включен.

Устанавливается через панель управления → программы и компоненты — включение и отключение компонентов Windows. В серверных Windows, данный протокол точно отключен по дефолту. Включаем через диспетчер сервера → компоненты → добавить компоненты → клиент печати через Интернет.

Я промучался с этой проблемой 2 дня. При попытке установки принтера данным способом вылезала ошибка — «Windows не удается подключиться к принтеру». При этом в логах cups и samba — ничего криминального нет. Это был мегатреш. Я дошел до разбора всего потока сетевого интерфейса с помощью tcpdump и wireshark, но ларчик то просто открывался. Проблема была на стороне винды.

Часть 2. Установка драйверов

Предположим, что принтеры в cups установлены, теперь приступим к копированию и регистрированию драйверов принтеров для Windows.

Можно вручную скопировать установленные драйверы в Windows — %WINDIR%\system32\spool\drivers\W32X86 и \x64 в папку с шарой для драйверов samba — /var/lib/samba/drivers/W32X86 и ./x64 и потом регистрировать их с помощью консольной утилиты rpcclient, но это нереальный квест и занятие не для слабонервных.

Мы пойдем более простым путем. Логинимся на виндовой машине с учеткой Domain Admin в наш домен. Буду показывать на примере WinXP (далее расскажу как действовать с Win7). Открываем проводник, в адресной строке вбиваем адрес принт сервера по IP или имени: \\Print-01\ или \\10.10.15.11\, переходим в папку Принтеры и факсы.

Клацаем правой кнопкой мыши на принтере → свойства.

На предложение установить драйвер, говорим Нет.

Идем во вкладку «дополнительно» → сменить.

Установить с диска и указываем папку с драйвером. Выбираем принтер в списке и нажимаем ОК.

ВАЖНО — в начале необходимо указать папу с 32-битными драйверами, даже, если система у вас 64-битная! 64-битные дрова установить можно будет после.

Идет копирование драйверов в расшаренную папку samba.

Переходим во вкладку «доступ» → отмечаем галочку «Внести в Active Diectory» → применить. Если нужны 64-битные драйвера, нажимаем Дополнительные драйвера»

И отмечаем галочку х64 → ОК. Система запросит папку с драйверами — аналогично скармливаем ей ее.

При желании, на вкладке «Общие», можно переименовать сетевой принтер. Эти названия будут отображаться при переходе в проводнике на принтсервер \\Print-01\ или \\10.10.15.11\.

В AD имена принтеров будут теми же, как вы называли их в cups.

Удаление принтеров из AD.

Диспетчер сервера → Доменные службы Active Directory → Active Directory пользователи и компьютеры → выбираем домен правой кнопкой мыши → найти → выбираем группу из ниспадающего списка «принтеры» → найти.

Находим в списке принтер, который хотим удалить → правой кнопкой мыши «удалить»

Установка драйверов в Windows 7/8/10.

В Windows 7/8/10 установить драйвера на принт-сервер можно из оснастки printmanagement.msc. Пуск → выполнить → printmanagement.msc

ПРИМЕЧАНИЕ В Home и Home Premium этой тулзы нет. Запускать эту оснастку нужно из под учетки Domain Admin. Сначала нужно добавить наш сервер печати по IP или имени.

Далее, здесь можно управлять принтерами сервера печати по аналогии c вышеуказанной инструкцией.

Так же здесь удобно управлять драйверами сервера печати — удалять/добавлять.

Что не удалось пока решить

В Windows Server 2012 R2 ну никак не хотят устанавливаться расшаренные принтеры. Ошибок в логах cups и samba нет. Принер начинает устанавливаться, драйвера копируются, но на этапе «завершение установки» выскакивает вышеуказанная ошибка «Windows не удается подключиться к принтеру». Думаю это какой-то косяк винды и скорее всего протокола ipp, хотя компонент «Клиент интернет печати» установлен.

В заключении, поделюсь секретом установки принтера Panasonic KX-FLB883RU в CUPS. Для данного принтера нет драйверов для linux, но чудесным образом подошел ljet2p.ppd (Panasonic KX-P4410 Foomatic/ljet2p), входящий в стандартный пакет OpenPrintingPPDs. Настройка принтера в CUPS через socket://IP_address/. Все работает без глюков. Надеюсь, кому-то пригодится.

Следующая моя статья будет посвящена удаленной автоматизированной системе установки принтеров пользователям домена. Или как то так)

Мои рабочие конфиги см. ниже.

/etc/krb5.conf

[libdefaults]
	ticket_lifetime = 24000
	default_realm = INITIAL.LOCAL
	dns_lookup_realm = false
	dns_lookup_kds = false
	clockskew = 300
# -------------------------------------
	kdc_timesync = 1
	ccache_type = 4
	forwardable = true
	proxiable = true

[realms]
INITIAL.LOCAL = {
	kdc = dc-01.initial.local
	default_domain = initial.local
#	admin_server = kerberos.initial.local:749
	admin_server = dc-01.initial.local
}

# EXAMPLE.COM = {
# 	kdc = kerberos.example.com
# 	admin_server = kerberos.example.com
# }

[logging]
	kdc = FILE:/var/log/krb5/krb5kdc.log
	admin_server = FILE:/var/log/krb5/kadmind.log
	default = SYSLOG:NOTICE:DAEMON
[domain_realm]
	.initial.local = INITIAL.LOCAL
	.INITIAL.local = INITIAL.LOCAL
	.INITIAL = INITIAL.LOCAL
	initial.local = INITIAL.LOCAL
[appdefaults]
pam = {
	debug = false
	ticket_lifetime = 1d
	renew_lifetime = 1d
	forwardable = true
	proxiable = false
	retain_after_close = false
	minimum_uid = 1
	use_shmem = sshd
	clockskew = 300
}

/etc/nsswitch.conf

# /etc/nsswitch.conf
#
# An example Name Service Switch config file. This file should be
# sorted with the most-used services at the beginning.
#
# The entry '[NOTFOUND=return]' means that the search for an
# entry should stop if the search in the previous entry turned
# up nothing. Note that if the search failed due to some other reason
# (like no NIS server responding) then the search continues with the
# next entry.
#
# Legal entries are:
#
#       compat                  Use compatibility setup
#       nisplus                 Use NIS+ (NIS version 3)
#       nis                     Use NIS (NIS version 2), also called YP
#       dns                     Use DNS (Domain Name Service)
#       files                   Use the local files
#       [NOTFOUND=return]       Stop searching if not found so far
#
# For more information, please read the nsswitch.conf.5 manual page.
#

# passwd: files nis
# shadow: files nis
# group:  files nis

# passwd:	compat winbind
# group:	compat winbind
# shadow:	compat winbind

passwd:	files winbind
group:	files winbind
shadow:	files winbind

# hosts:	files mdns4_minimal [NOTFOUND=return] dns wins
hosts:	files [dns] wins

networks:	files dns
services:	files
protocols:	files
rpc:	files
ethers:	files
netmasks:	files
netgroup:	files nis
publickey:	files

bootparams:	files
automount:	files nis
aliases:	files

/etc/openldap/ldap.conf

#
# LDAP Defaults
#

# See ldap.conf(5) for details
# This file should be world readable but not world writable.

#BASE	dc=example,dc=com
#URI	ldap://ldap.example.com ldap://ldap-master.example.com:666

#SIZELIMIT	12
#TIMELIMIT	15
#DEREF		never
URI	ldap://10.10.15.31
BASE	DC=initial,DC=local

/etc/samba/smb.conf

# smb.conf is the main Samba configuration file. You find a full commented
# version at /usr/share/doc/packages/samba/examples/smb.conf.SUSE if the
# samba-doc package is installed.
[global]
	workgroup = INITIAL
#	passdb backend = smbpasswd
	printing = cups
	printcap name = cups
	printcap cache time = 750
	cups options = raw
	map to guest = Bad User
	logon path = \\%L\profiles\.msprofile
	logon home = \\%L\%U\.9xprofile
	logon drive = P:
	usershare allow guests = Yes
	add machine script = /usr/sbin/useradd  -c Machine -d /var/lib/nobody -s /bin/false %m$
	domain logons = No
	domain master = No
	security = ADS
	encrypt passwords = yes
#	idmap backend = ldap:ldap://10.10.15.31
	ldap admin dn = admin@initial.local
	ldap group suffix = ou=Groups
	ldap idmap suffix = ou=Idmap
	ldap machine suffix = ou=Computers
	ldap passwd sync = Yes
	ldap suffix = DC=initial,DC=local
	ldap user suffix = ou=Users
	ldap ssl = Off
	ldapsam:trusted = yes
	ldapsam:editposix = yes
#	idmap gid = 500-10000000
#	idmap uid = 500-10000000
	netbios name = print-01
	name resolve order = lmhost wins host bcast
	wins server = 10.10.15.31
	wins support = No
	usershare max shares = 100
	kerberos method = system keytab
## --------------------------------------
	winbind separator = /
	winbind enum users = yes
	winbind enum groups = yes
	winbind nested groups = yes
	winbind use default domain = yes
	winbind nss info = rfc2307
	winbind uid = 10000-20000
	winbind gid = 10000-20000
	realm = INITIAL.LOCAL
	template homedir = /home/%D/%U
	winbind refresh tickets = yes
	template shell = /bin/bash

# [homes]
#	comment = Home Directories
#	valid users = %S, %D%w%S
#	browseable = No
#	read only = No
#	inherit acls = Yes

# [profiles]
#	comment = Network Profiles Service
#	path = %H
#	read only = No
#	store dos attributes = Yes
#	create mask = 0600
#	directory mask = 0700

# [users]
#	comment = All users
#	path = /home
#	read only = No
#	inherit acls = Yes
#	veto files = /aquota.user/groups/shares/
#	guest ok = No

# [groups]
#	comment = All groups
#	path = /home/groups
#	read only = No
#	inherit acls = Yes

[printers]
	comment = All Printers
	path = /var/spool/samba
	printable = Yes
	create mask = 0664
	browseable = Yes
	read only = No
	guest ok = Yes

[print$]
	comment = Printer Drivers
	path = /var/lib/samba/drivers
	write list = @ntadmin root
	force group = ntadmin
	create mask = 0664
	directory mask = 0700
	read only = No
	guest ok = Yes
	writable = yes
#	inherit permissions = yes
# --------------------------------
	use client driver = yes

# [netlogon]

/etc/cups/cupsd.conf

LogLevel debug
SystemGroup root
# Allow remote access
Port 631
Listen /run/cups/cups.sock
Browsing On
BrowseLocalProtocols CUPS
BrowseRemoteProtocols CUPS
BrowseOrder allow,deny
BrowseAllow all
BrowseAddress 10.10.15.0/24
BrowseAddress 172.19.2.0/24
BrowseAddress 172.19.3.0/24
BrowseAddress 172.19.4.0/24
DefaultAuthType Basic
WebInterface Yes
<Location />
  # Allow remote access...
  Order allow,deny
  Allow all
</Location>
<Location /admin>
  Order deny,allow
</Location>
<Location /admin/conf>
  AuthType Default
  Require user @SYSTEM
</Location>
<Policy default>
  JobPrivateAccess default
  JobPrivateValues default
  SubscriptionPrivateAccess default
  SubscriptionPrivateValues default
  <Limit Create-Job Print-Job Print-URI Validate-Job>
    Order deny,allow
  </Limit>
  <Limit Send-Document Send-URI Hold-Job Release-Job Restart-Job Purge-Jobs Set-Job-Attributes Create-Job-Subscription Renew-Subscription Cancel-Subscription Get-Notifications Reprocess-Job Cancel-Current-Job Suspend-Current-Job Resume-Job Cancel-My-Jobs Close-Job CUPS-Move-Job CUPS-Get-Document>
    Require user @OWNER @SYSTEM
    Order deny,allow
  </Limit>
  <Limit CUPS-Add-Modify-Printer CUPS-Delete-Printer CUPS-Add-Modify-Class CUPS-Delete-Class CUPS-Set-Default CUPS-Get-Devices>
    AuthType Default
    Require user @SYSTEM
    Order deny,allow
  </Limit>
  <Limit Pause-Printer Resume-Printer Enable-Printer Disable-Printer Pause-Printer-After-Current-Job Hold-New-Jobs Release-Held-New-Jobs Deactivate-Printer Activate-Printer Restart-Printer Shutdown-Printer Startup-Printer Promote-Job Schedule-Job-After Cancel-Jobs CUPS-Accept-Jobs CUPS-Reject-Jobs>
    AuthType Default
    Require user @SYSTEM
    Order deny,allow
  </Limit>
  <Limit Cancel-Job CUPS-Authenticate-Job>
    Require user @OWNER @SYSTEM
    Order deny,allow
  </Limit>
  <Limit All>
    Order deny,allow
  </Limit>
</Policy>
<Policy authenticated>
  JobPrivateAccess default
  JobPrivateValues default
  SubscriptionPrivateAccess default
  SubscriptionPrivateValues default
  <Limit Create-Job Print-Job Print-URI Validate-Job>
    AuthType Default
    Order deny,allow
  </Limit>
  <Limit Send-Document Send-URI Hold-Job Release-Job Restart-Job Purge-Jobs Set-Job-Attributes Create-Job-Subscription Renew-Subscription Cancel-Subscription Get-Notifications Reprocess-Job Cancel-Current-Job Suspend-Current-Job Resume-Job Cancel-My-Jobs Close-Job CUPS-Move-Job CUPS-Get-Document>
    AuthType Default
    Require user @OWNER @SYSTEM
    Order deny,allow
  </Limit>
  <Limit CUPS-Add-Modify-Printer CUPS-Delete-Printer CUPS-Add-Modify-Class CUPS-Delete-Class CUPS-Set-Default>
    AuthType Default
    Require user @SYSTEM
    Order deny,allow
  </Limit>
  <Limit Pause-Printer Resume-Printer Enable-Printer Disable-Printer Pause-Printer-After-Current-Job Hold-New-Jobs Release-Held-New-Jobs Deactivate-Printer Activate-Printer Restart-Printer Shutdown-Printer Startup-Printer Promote-Job Schedule-Job-After Cancel-Jobs CUPS-Accept-Jobs CUPS-Reject-Jobs>
    AuthType Default
    Require user @SYSTEM
    Order deny,allow
  </Limit>
  <Limit Cancel-Job CUPS-Authenticate-Job>
    AuthType Default
    Require user @OWNER @SYSTEM
    Order deny,allow
  </Limit>
  <Limit All>
    Order deny,allow
  </Limit>
</Policy>
<Policy allowallforanybody>
  JobPrivateAccess all
  JobPrivateValues none
  SubscriptionPrivateAccess all
  SubscriptionPrivateValues none
  <Limit All Validate-Job Cancel-Jobs Cancel-My-Jobs Close-Job CUPS-Get-Document>
    Order deny,allow
    Allow from all
  </Limit>
</Policy>
DefaultPolicy default

Спасибо за внимание!

This tutorial will be showing you how to share a printer attached to an Ubuntu computer with Windows, macOS, and iOS clients on the same network. CUPS (Common Unix Printing System) is the default printing system on Linux, FreeBSD, and macOS. Your Linux desktop environment may have a dedicated printer configuration utility, but they all use CUPS under the hood.

CUPS printer can be shared on the network using several protocols, including:

  • Bonjour + IPP: Bonjour, also known as mDNS/DNS-SD (multicast DNS/DNS service discovery), allows a computer to find services on the local network. IPP (Internet Printing Protocol) is the transport protocol.
  • SMB: aka Samba, mainly used to share files and printers with Windows clients.
  • AirPrint: Allows iPhone, iPad, and macOS clients to print over Wi-Fi.

Each protocol has its advantages and disadvantages. First, I will show you how to install and configure CUPS. Then we will learn how to share the CUPS printer via the above 3 protocols. I recommend using all 3 methods to share your printer, so users can find an available printer on the local network with minimal effort.

Set Up CUPS Print Server on Ubuntu

Step 1: Install and Configure CUPS on Ubuntu

Ubuntu desktop edition has CUPS pre-installed. If you use Ubuntu server edition, you need to run the following command to install CUPS from the default Ubuntu repository.

sudo apt install cups

Then start CUPS.

sudo systemctl start cups

Enable auto-start at boot time.

sudo systemctl enable cups

Check its status:

systemctl status cups

Sample output:

cups printing system ubuntu

Next, edit the CUPS main configuration file with a command-line text editor like Nano.

sudo nano /etc/cups/cupsd.conf

First, we need to show shared printers on the local network. Find the following line.

Browsing Off

Change it to

Browsing On

so other computers in the same network can see printers connected to your Ubuntu computer.

By default, the CUPS web interface is only available at localhost:631. If you are running Ubuntu server edition, you may also want to make CUPS listen on all available network interface, so that you will be able to access the CUPS web interface from other computers. Find the following line.

Listen localhost:631

Change it to

Port 631

So CUPS will listen on all network interfaces. Then find the following lines.

<Location />
  Order allow,deny
</Location>

The above configuration allows access to the CUPS web interface from localhost only. To allow access from other computers in the same network, add Allow @LOCAL to the configuration like below.

<Location />
  Order allow,deny
  Allow @LOCAL
</Location>

Also add it for the /admin directory to allow remote administration from local network.

<Location /admin>
  Order allow,deny
  Allow @LOCAL
</Location>

You can also allow a particular IP address like so:

<Location />
  Order allow,deny
  Allow 192.168.0.101
</Location>

Save and close the file. Then restart CUPS for the changes to take effect.

sudo systemctl restart cups

Note that if you have enabled the UFW firewall on Ubuntu, you need to allow clients in the same network to access port 631 on your Ubuntu box. For example, my private network is using the 192.168.0.0 ~192.168.0.255 network range, so I run the following command.

sudo ufw allow in from 192.168.0.0/24 to any port 631

The CUPS web interface is available at https://IP-address-of-Ubuntu-box:631. We don’t need to use the web interface in this article, but if you want to use it, then you need to add your user account to the lpadmin group in order to make changes in the CUPS web interface.

sudo adduser your_username lpadmin

Step 2: Install Driver for Your Printer on Ubuntu

You need to install driver on Ubuntu, so it can recognize and use the printer. If you have an HP printer, you can easily install the driver with the following command.

sudo apt install hplip

I also recommend installing the printer-driver-gutenprint package, which provides CUPS drivers for Canon, Epson, HP and compatible printers.

sudo apt install printer-driver-gutenprint

If you have other printers, you can find drivers on openprinting.org.

After installing the driver, you may need to re-connect the printer to the USB port of your Ubuntu computer. To test if the driver is working correctly, you can create a text file on Ubuntu:

echo "LinuxBabe is awesome!" > file.txt

Then run the following command to print this text file from the command line.

lp file.txt

This is a very rudimentary method, so don’t worry about printing quality now.

Step 3: Share CUPS Printer via Bonjour/IPP Protocol

Installing Avahi-daemon

CUPS can announce its presence on the network via mDNS (multicast DNS) and DNS-SD (DNS Service Discovery) protocol, which is also known as Bonjour. In order to do that, you need to install and run avahi-daemon, which is a service similiar to the Apple Bonjour service that allows computers to automatically discover shared devices and services on the local network.

sudo apt install avahi-daemon

Start avahi-daemon.

sudo systemctl start avahi-daemon

Enable auto-start at boot time.

sudo systemctl enable avahi-daemon

Avahi-daemon listens on UDP port 5353. Open it in the firewall.

sudo ufw allow 5353/udp

IPP Driverless Printing

Bonjour is used to advertise the printer on the local network. To make clients and the CUPS server communicate with each other, IPP (Internet Printing Protocol) is needed. The advantage of IPP is that clients can use the shared printer without installing any driver on their own devices. CUPS supports IPP out of the box, so you don’t need to do anything else to share CUPS printer via IPP.

Step 4: Add Printer on Client Computers

macOS and Linux Clients

Because macOS and most Linux desktop distributions have CUPS installed as the default printing system, once you have enabled printer sharing via Bonjour/IPP on the Ubuntu box, macOS and Linux users in the same network can automatically use the printer. When they click the print option in applications (word processors, email readers, photo editors, and web browsers), the printer will be automatically available. They don’t have to explicitly add the printer. It’s magic.

If your Linux computer can’t find the printer, it’s possible that your system doesn’t have the ippfind command. Run the following command to install it on Debian-based Linux distribution.

sudo apt install cups-ipp-utils

On CentOS 8, run the following command.

sudo dnf install cups-ipptool

Then restart CUPS on the client computer.

sudo systemctl restart cups

Windows

Windows 10 ships with an IPP client. Type in printer in the lower-left search bar and open Printers & Scanners. Then click the Add a printer or scanner button. It will scan available printers on the local network.

windows 10 printers & scanners

As you can see, it found my HP Deskjet printer. Select the found printer and click Add device. It will be added to the printer list in a few moments.

add-printers-scanners-windows10-ipp

If you are using a different version of Windows that can’t add printer this way, then you can install the Bonjour Print services. Once installed, launch the Bonjour printer wizard. It will automatically scan available printers on the local network. As you can see from the screenshot, it found my HP printer.

add-bonjour-shared-printer-on-windows

Click next, then you need to choose a driver for this printer. You can choose the Microsoft IPP class driver, which is installed on the system by default.

bonjour microsoft ipp class driver

Click Next, and the printer will be added to your Windows system.

Manually Adding Printer on Linux

If for any reason you don’t see the printer, you can manually add one. To add a Bonjour-shared printer on desktop Linux, search your system settings or the application menu for the printer configuration utility. Click the Add button to add a new printer.

add cups printer on linux

Then click Network Printer, and it would automatically scan available printers on the local network. As you can see, it found my HP Deskjet printer. Click the Forward button.

cups ubuntu dnssd

Then you can give the printer a name and description. I simply accept the default values. Click Apply and you are done.

ubuntu-cups-printer-mdns-dnssd

Manually Adding Printer on macOS

To add a Bonjour-shared printer on macOS, go to system preferences -> Printers & Scanners. Click the plus (+) button to add a printer.

add a bonjour printer on macOS

It would automatically scan available printers on the local network. As you can see, it found my HP Deskjet printer.

macos bonjour shared printer

Click the Add button and it will appear in the printer list.

macOS-printers-scanners-list

Step 5: Share CUPS Printer via Samba

Samba is a free and open-source SMB/CIFS protocol implementation for Unix and Linux that allows for file and print sharing between Unix/Linux and Windows machines in a local area network. It’s mainly used to share files and printer with Windows clients.

To install Samba on Ubuntu, simply run the following command in terminal.

sudo apt install samba samba-common-bin

To check if Samba service is running, issue the following commands.

systemctl status smbd

systemctl status nmbd

To start these two services, issue the following commands:

sudo systemctl start smbd

sudo systemctl start nmbd

Then edit the main configuration file.

sudo nano /etc/samba/smb.conf

It’s recommended to enable the spoolssd service when sharing printer. This will make Samba more efficient when there’s lots of printing jobs. Simply add the following two lines in the [global] section to enable the spoolssd service.

 rpc_server:spoolss = external
 rpc_daemon:spoolssd = fork

Next, go to the end of the file and you will see the [printers] section. In Nano text editor, you can jump to the end of a file by pressing Ctrl+W, then Pressing Ctrl+V. Find the following two lines.

browseable = no
guest ok = no

Change them to

browseable = yes
guest ok = yes

Save and close the file. Then restart Samba.

sudo systemctl restart smbd nmbd

Adding a Samba-shared Printer in Windows.

Open file explorer, enter the IP address of the Ubuntu computer in the address bar like \\192.168.0.110. The printer should now be listed.

add samba-shared printer on Windows 10

Double-click the printer to add it to your Windows system. Then click OK button to select a driver to install. After installing the driver, the printer will be added to your Windows system.

windows add printer wizard

Step 6: Share CUPS Printer with iOS Clients via AirPrint

AirPrint allows iPhone, iPad, and macOS clients to print over Wi-Fi without installing driver software on the client devices. CUPS supports AirPrint, but avahi-daemon by default doesn’t announce AirPrint service on the local network. We need to create a .service file in the /etc/avahi/services/ directory for the printer with a Python script with the following command. My printer’s model is DeskJet 2130 series. Replace it with your own model name.

sudo nano /etc/avahi/services/AirPrint-DeskJet-2130-series.service

Add the following lines in the file.

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE service-group SYSTEM "avahi-service.dtd">
<service-group>
  <name replace-wildcards="yes">AirPrint DeskJet-2130-series @ %h</name>
  <service>
    <type>_ipp._tcp</type>
    <subtype>_universal._sub._ipp._tcp</subtype>
    <port>631</port>
    <txt-record>txtvers=1</txt-record>
    <txt-record>qtotal=1</txt-record>
    <txt-record>Transparent=T</txt-record>
    <txt-record>URF=none</txt-record>
    <txt-record>rp=printers/DeskJet-2130-series</txt-record>
    <txt-record>note=HP DeskJet 2130 series</txt-record>
    <txt-record>product=(GPL Ghostscript)</txt-record>
    <txt-record>printer-state=3</txt-record>
    <txt-record>printer-type=0x2900c</txt-record>
    <txt-record>pdl=application/octet-stream,application/pdf,application/postscript,application/vnd.cups-raster,image/gif,image/jpeg,image/png,image/tiff,image/urf,text/html,text/plain,application/vnd.adobe-reader-postscript,application/vnd.cups-pdf</txt-record>
  </service>
</service-group>

Save and close the file. Restart Avahi-daemon.

sudo systemctl restart avahi-daemon

Now iOS and macOS clients in the same network should be able to use your printer. The following screenshot shows my iPhone successfully found an AirPrint Printer.

ubuntu-cups-airprint

Wrapping Up

I hope this tutorial helped you set up a CUPS print server on Ubuntu 20.04, 18.04 and 21.10. As always, if you found this post useful, then subscribe to our free newsletter to get more tips and tricks. And you may also want to read the following article to set up a Samba file share server.

  • Set Up Samba Server on Ubuntu for File Sharing

Contents

  1. Overview
  2. Background
  3. Ubuntu print server

    1. Ubuntu print server compatible with Windows (Samba)
  4. Printing from Ubuntu
  5. Printing from Windows
  6. Troubleshooting

Overview

Ubuntu supports printer sharing over networks, so you can print from your Ubuntu machine, your Windows machine, etc, to another Ubuntu or Windows machine that has a printer attached (ie a «Ubuntu print server» or «Windows print server»).

Background

printingScheme.png

Ubuntu uses the Common UNIX Printing System («CUPS») to handle printing. CUPS uses the Internet Printing Protocol («IPP») as the basis for managing print jobs and queues. Other protocols are also supported (LPD, SMB, AppSocket a.k.a. JetDirect), some with reduced functionality.

CUPS printer configuration and management is handled by the Printer Admin utility launched from the Gnome menu — System -> Administration -> Printing (If the menu item does not exist you need to add the command system-config-printer to the menu). Also IPP provides web services so after you have configured CUPS appropriately, you can access the printers and jobs via your web browser.

When a locally attached printer is defined, eg using the Printer Admin utility, that printer is automatically published from this «print server» host to the network, depending on the server directives in the CUPS configuration file. A remote Ubuntu «client» host can then be able to see and use the printer attached to the server. The network printer automatically appears in the client’s Printer Admin utility. It simply pops up if CUPS is up and configured correctly and disappears if you stop CUPS at either the Print Server or your local machine.

Ubuntu print server

The Print Server is the Ubuntu computer that is directly connected to the printers.

  1. On the server machine (the one the printer is attached to), open System -> Administration -> Printing (If the menu item does not exist you need to add system-config-printer to the menu). . This will open the Printer Configuration window.

    system-config-printer.png

  2. Select Server in the menu bar, and then Settings. This will open the Basic Server Settings window.

  3. Check the second box:

    Publish shared printers connected to this server If this computer acts as both a Print Server and a client (it does need access to a printer connected to another computer), select also the first box, «Show printers shared by other systems».

    Server-setting.png

  4. OK

  5. Right click the printer and check the Shared option, if not checked yet

  6. Check that users that you want to be able to use the printer are not excluded. See Properties>Access Control. The default settings may be set to «deny printing for everyone except …»

inkjet_settings1.png

.

But you might want to «allow printing for everyone».

access_control_allow_everyone.png

Ubuntu print server compatible with Windows (Samba)

If your Ubuntu print server shall be able to work also with Windows clients, you must first make sure that the SAMBA package is installed (e.g. using Synaptic package manager). Then, do a little configuration change to SAMBA. In brief, you must uncomment the following lines in /etc/samba/smb.conf — open terminal and run:

gksudo gedit /etc/samba/smb.conf

In the [printers] section:

   browseable = yes
   guest ok = yes

When done, restart Samba:

sudo service smbd restart
sudo service nmbd restart

There is a dedicated page in the official documentation which gives more details.

Also, one would want to allow the following ports through a firewall (ufw for example) via:

sudo ufw allow 139/tcp
sudo ufw allow 445/tcp
sudo ufw allow 137/udp
sudo ufw allow 138/udp

For more on this, please see here.

Printing from Ubuntu

Now let’s configure the client (the Ubuntu computer from where you want to print):

  1. System -> Administration -> Printing

  2. Add — Network printer

    • Click Find network printer

      • Specify the host IP address or name. (It may also work without, try) (IP address worked for me, hostname did not.)
      • Click Find

    • Printers on the target machine should be found, no matter whether they are connected using CUPS or SAMBA.
      • BUT if both protocols are available, e.g. because you have shared your printer on a Linux box both using CUPS and Samba, prefer CUPS (ipp://) over Samba (smb://), because you won’t be prompted to install a driver in general.

      findNetworkPrinterScreenshot.png

  3. You **may** be prompted to select a driver. Select your model in the list.
    • (to be done) What to do if driver is not in the list

Printing from Windows

Once your Ubuntu print server is set up using SAMBA as described above, you can add the printer in Windows as follows:

  1. Start
  2. Devices and Printers
  3. Add a printer
  4. Add a network, wireless or Bluetooth printer
  5. Click The printer that I want isn’t listed (unless a miracle happens)

  6. Enter the address manually (\\servername\MyPrinter). Be sure to respect uppercase/lowercase.

Step 1

Step 2

Note that searching or browsing for printers in Windows is notoriously unreliable, as it heavily depends on the network setup. Therefore, it is recommended to enter the printer address manually as shown.

Windows will then probably complain about a missing driver, and offer you to choose one manually. This is the easiest option, so select your printer manufacturer and model from the dialog box. (Alternatively, the Samba configuration could be improved so that the driver would be automatically downloaded.) If your printer model isn’t listed, you may try the «Generic» printer.

Tips: You can avoid intermediate SAMBA buffer using direct connection to CUPS/IPP Ubuntu server from Windows workstation. You should manually specify «http://hostname:631/printers/MyPrinter» IPP URL and select printer driver.

Windows print dialog window (Ctrl-P) can take long time (about 30 seconds) to appear. You can reduce the connection time to CUPS IPP printer by disabling option Automatically detect settings in «Control Panel/Internet Explorer -> Internet Options -> Connections -> LAN settings».

Troubleshooting

1. Bypassing firewall.

If there is an firewall either on print server or the client side, there might appear a communications problem. Use this command to update the firewall to get through.

iptables -A INPUT -p tcp —dport 631 -j ACCEPT

  • This rule is used for IPP only. If you’re using other protocol, such as SAMBA, you have to adapt.

    You might need to use this rule on both sides (server & client) if the firewall is being used on both of them. To apply this rule after each start/restart of the system, use /etc/rc.local .

2. Networking issues.

Be careful about using different network masks/subnets on your network where you would like to share the printer.

If the subnets differs, e.g. on the print server there would be a /24 (255.255.255.0) netwok mask configured, and e.g. on the clients there would be a /16 (255.255.0.0) network mask — perhaps provided by the DHCP server, this might cause a problem that clients won’t be able to detect any shared printer on the server, even if other communications between print server and clients would be possible (e.g. ICMP, ssh) and successful.

If such situation happens, you have to unify the network masks/subnets on all of your stations, e.g. use /24 (255.255.255.

3. IP address

Generally, it is a good idea to assign your print server a static IP address. Instead, using its host name is also possible, but functionality will then depend on proper configuration of your home router, name service, etc.

4. IPv6 Windows (since XP) can print over IPv6 to Ubuntu Linux (tested between Windows XP SP3 and Ubuntu Linux 8.10). Make sure both the Windows and Ubuntu have IPv6 connectivity. You should tick «Allow Printing from the Internet» on the Ubuntu machine. Then use the URL (which resolves to IPv6) of the Ubuntu machine as described above.

5. Mac OS X 10.5.

Will not find your network printer unless you go to the terminal and run cupsctl BrowseRemoteProtocols=cups (see the CUPS 1.4 documentation at http://www.cups.org/documentation.php/doc-1.4/sharing.html). After doing so, you may need to set the network printer as your default printer for it to show up in program «print» menus.


CategoryNetworking

Provide feedback

Saved searches

Use saved searches to filter your results more quickly

Sign up

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Microsoft store закрывается после запуска на windows 11
  • Просмотр корневых сертификатов windows
  • Как вернуть пользователя на windows 7
  • Autochk program not found skipping autocheck windows 10
  • Bonjour service что это такое windows 10