«Windows terminal server» и «Почтовый сервер на Debian 9 полная установка: dbmail & postgresql & postfix & stunnel & postgrey& spamassassin»: разница между страницами

Материал из support.qbpro.ru
(Различия между страницами)
imported>Vix
Нет описания правки
 
imported>Vix
Нет описания правки
 
Строка 1: Строка 1:
== Оптимизация Windows terminal server ==
'''Порядок установки:'''
'''В данной статье рассматривается возможность оптимизации работы терминального сервера на платформе Windows. Данные рекомендации использовались на версиях Windows XP и Windows 2003. Возможно будут работать на Windows 7.'''  
* '''''Система Debian Stretch {9}'''''
*подразумевается, что вы уже установили сервер терминалов, он у вас работает и все дальнейшие действия выполняются на рабочем сервере. При этом категорически рекомендуем делать bakup изменений реестра или изменяемых системных файлов.
* Используемый source.list
#
deb http://mirror.mephi.ru/debian/ stretch main
deb-src http://mirror.mephi.ru/debian/ stretch main
deb http://security.debian.org/debian-security stretch/updates main
deb-src http://security.debian.org/debian-security stretch/updates main
# stretch-updates, previously known as 'volatile'
deb http://mirror.mephi.ru/debian/ stretch-updates main
deb-src http://mirror.mephi.ru/debian/ stretch-updates main
###### Debian Main Repos
deb http://deb.debian.org/debian/ stable main contrib non-free
deb-src http://deb.debian.org/debian/ stable main contrib non-free
deb http://deb.debian.org/debian/ stable-updates main contrib non-free
deb-src http://deb.debian.org/debian/ stable-updates main contrib non-free
deb http://deb.debian.org/debian-security stable/updates main contrib non-free
deb-src http://deb.debian.org/debian-security stable/updates main contrib non-free
deb http://ftp.debian.org/debian stretch-backports main contrib non-free
deb-src http://ftp.debian.org/debian stretch-backports main contrib non-free
1. ''Устанавливаем необходимые пакеты:''
apt-get install pkg-config libglib2.0-dev libgmime-2.6-dev libmhash-dev libevent-dev libssl1.0-dev libzdb-dev
autoconf automake libtool autotools-dev dpkg-dev fakeroot


*Рекомендация для правильной работы спулера принтеров сервера, данная операция производится после установки всех необходимых драйверов принтеров.
2. ''Скачиваем с [http://www.dbmail.org/index.php?page=download dbmail.org] исходники:''
Сообщения об ошибках из-за проблем с монитором локального порта
  wget -c -t 0 -T 8 http://www.dbmail.org/download/3.1/dbmail-3.1.17.tar.gz
После перезагрузки компьютера или после перезапуска службы «Диспетчер очереди печати» появляется следующее сообщение об ошибке:  
Сбой при запуске Spoolsv.exe
Если открыть окно свойств принтера, появляется следующее сообщение об ошибке:
Недостаточно ресурсов
При попытке печати документа появляется сообщение об ошибке «Нарушение прав доступа» (программа Dr. Watson). В журнале программы
Dr. Watson присутствует запись об ошибке в программе Spoolsv.exe с кодом ошибки C0000005.
Появляется следующее сообщение об ошибке и диспетчер очереди печати останавливается:  
Инструкция по адресу 'адрес' обратилась к памяти по адресу 'адрес'. Память не может быть «read».
  Такое же сообщение появляется при попытке перезапуска службы «Диспетчер очереди печати» и при открытии папки «Принтеры».  
Причиной проблемы может являться то, что используемый по умолчанию монитор локального порта заменен программой независимого
производителя. Чтобы устранить ошибку, необходимо внести изменения в системный реестр.  
*Для этого выполните следующие действия.
Откройте редактор реестра.
2. Найдите параметр Local Port в следующем разделе реестра.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Print\Monitors\Local Port
3. Дважды щелкните параметр Driver и измените его значение. Введите строковое значение Localspl.dll и нажмите кнопку ОК.
4. Проверьте, присутствуют ли мониторы независимых производителей в следующем разделе реестра. Удалите все мониторы,
кроме используемых по умолчанию.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Print\Monitors
По умолчанию используются следующие мониторы.  
AppleTalk Printing Devices (присутствует, если установлены службы для Macintosh)
BJ Language Monitor
Local Port
PJL Language Monitor
Standard TCP/IP Port
USB Monitor
Windows NT Fax Monitor


** LPR Port
3. ''Распаковываем и компилируем:''
Примечание. Удаление монитора LPR Port должно выполняться только по рекомендации специалиста службы технической поддержки
  cp dbmail-3.1.17.tar.gz /usr/local/src
  корпорации Майкрософт.  
  tar -xf dbmail-3.1.17.tar.gz /usr/local/src.dbmail-3.1.17
5. Проверьте, присутствуют ли службы печати сторонних производителей в следующем разделе реестра. Удалите все службы печати,
  cp dbmail-3.1.17.tar.gz /usr/local/src/dbmail_3.0.2.orig.tar.gz
кроме используемых по умолчанию.
  HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Print\Providers
По умолчанию используется следующие службы печати.  
Internet Print Provider
LanMan Print Services
6. Проверьте, присутствуют ли обработчики печати сторонних производителей в следующем разделе реестра. Удалите все обработчики
печати, кроме используемых по умолчанию.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Print\Environments\Windows NT x86\Print Processors
По умолчанию используется следующий обработчик печати
WinPrint
Чтобы определить обработчик печати, используемый принтером, с помощью средства MPS_REPORTS (Microsoft Product Support Reporting Tool)
откройте файл MachineName_PRINTDRIVERS.TXT и найдите в нем нужный обработчик печати независимого производителя и очереди, которые
его используют.  
7. Замените обработчик печати независимого производителя обработчиком WinPrint.
  8. Нажмите кнопку Пуск и выберите в меню Настройка пункт Панель управления.
9. Дважды щелкните значок Принтеры, щелкните правой кнопкой мыши нужный принтер и выберите команду Свойства.
10. Перейдите на вкладку Дополнительно и нажмите кнопку Обработчик печати.
11. В списке Обработчик печати выберите WinPrint.
12. Дважды нажмите кнопку ОК.
13. Закройте редактор реестра.


  После внесения изменений в реестр перезапустите диспетчер очереди печати. Для этого запустите консоль управления (MMC)
''Готовим пакет к сборке:''
  и добавьте оснастки «Управление компьютером» или «Службы». Щелкните правой кнопкой мыши службу Диспетчер очереди печати
  cd /usr/local/src/dbmail-3.2.3
  и выберите команду Пуск.
  ./configure --with-pgsql --prefix=/usr
 
  dpkg-source --commit
даем имя, что-то pgsql.commit


*При переполнении за сутки очереди печати чистим батником:
cd /usr/local/src/
dpkg-source -b dbmail-3.2.3


  @echo off
  cd /usr/local/src/dbmail-3.2.3
  net stop spooler
  dpkg-buildpackage -d
echo y|del C:\WINDOWS\system32\spool\PRINTERS\*
net start spooler


*При печати клиента из терминального режима на локальный принтер в системном логе сервера появляется сообщение об ошибке:
* после того как соберется пакет, копируем себе в архив и ставим.
Event ID: 1103 Description: An internal communication error occurred. Решение проблемы:
  dpkg -i dbmail_3.2.3-1_amd64.deb
Это происходит, если имя принтера на рабочей станции не совпадает с именем
принтера на терминал-сервере. Как правило, это бывает, если в качестве клиента
используются компьютеры под управлением Windows 95/98/Me. Запишите название
принтера на рабочей станции в локальном режиме, затем начните установку этого
принтера на терминал-сервере и снова запишите его название. Затем откройте
файл %systemroot%\system32\Wtsuprn.txt и добавьте в него свой принтер. Уберите
  значек комментария перед вносимой строкой, а полученный файл сохраните под
именем %systemroot%\system32\Wtsuprn.inf.
('''или скачайте этот файл тут:''' http://nixtech.ru/datatrans/win32/term-prn/wtsuprn.txt)
('''или тут:''' http://support.citrix.com/article/CTX626451)
log on на терминал-сервере. Затем подключитесь с клиентской рабочей станции. Ваш принтер
должен автоматически появится в папке Printers терминальной сессии.
('''Инструкция от Microsoft по установке''' http://support.microsoft.com/kb/214593)


*Полезные ссылки по решению проблем печати на терминальном сервере
* правим файл конфигурации:
('''Решение проблем печати в терминальных сетях и терминальных службах.''' http://admin-dm.livejournal.com/67401.html)
editor /etc/dbmail/dbmail.conf


('''Совместимость имен принтеров при работе с терминальным сервером''' http://support.citrix.com/article/CTX626451)
* пример рабочего конфигурационного файла:


('''Terminal Server Printer Redirection Wizard Tool''' http://www.microsoft.com/download/en/details.aspx?DisplayLang=en&id=5640)
# (c) 2000-2006 IC&S, The Netherlands
#
# Configuration file for DBMAIL
[DBMAIL]
#
# Database settings
#
# database connection URI
#dburi                = sqlite:///var/tmp/dbmail.db
#
# Supported drivers are sql, ldap.
#
authdriver          = sql
#
#
# following fields are now DEPRECATED!
driver              = postgresql
host                = 10.0.5.2
sqlport              = 5432
#sqlsocket            =             
user                = dbmail
pass                = dbmailpass
db                  = mailbasename
#
# Number of database connections per threaded daemon
# This also determines the size of the worker threadpool
#
# Do NOT increase this without proper consideration. A
# very large database/worker pool will not only increase
# the connection pressure on the database, but will more
# significantly cause unnecessary context-switching in
# your CPUs.
#
#max_db_connections  = 10
#
# Table prefix. Defaults to "dbmail_" if not specified.
#
table_prefix        = dbmail_ 
#
# encoding must match the database/table encoding.
# i.e. latin1, utf8
encoding            = utf8
#
# messages with unknown encoding will be assumed to have
# default_msg_encoding
# i.e. iso8859-1, utf8
default_msg_encoding = utf8
#
# Postmaster's email address for use in bounce messages.
#
#postmaster          = DBMAIL-MAILER     
#
# Sendmail executable for forwards, replies, notifies, vacations.
# You may use pipes (|) in this command, for example:
# dos2unix|/usr/sbin/sendmail  works well with Qmail.
# You may use quotes (") for executables with unusual names.
#
sendmail              = /usr/sbin/sendmail   
#
#
# The following items can be overridden in the service-specific sections.
#
#
#
# Logging via stderr/log file and syslog
#
# Logging is broken up into 8 logging levels and each level can be indivually turned on or off.
# The Stderr/log file logs all entries to stderr or the log file.
# Syslog logging uses the facility mail and the logging level of the event for logging.
# Syslog can then be configured to log data according to the levels.
#
# Set the log level to the sum of the values next to the levels you want to record.
#  1 = Emergency
#  2 = Alert
#  4 = Critical
#  8 = Error
#  16 = Warning
#  32 = Notice
#  64 = Info
# 128 = Debug
# 256 = Database -> Logs at debug level
#
# Examples:  0 = Nothing
#            31 = Emergency + Alert + Critical + Error + Warning
#          511 = Everything
#
file_logging_levels      = 7
#
syslog_logging_levels    = 31
#
# Generate a log entry for database queries for the log level at number of seconds of query execution time.
#
query_time_info      = 10
query_time_notice    = 20
query_time_warning    = 30
#
# Throw an exception is the query takes longer than query_timeout seconds
query_timeout        = 300
#
# Root privs are used to open a port, then privs
# are dropped down to the user/group specified here.
#
effective_user        = dbmail
effective_group      = mail
#
# The IPv4 and/or IPv6 addresses the services will bind to.
# Use * for all local interfaces.
# Use 127.0.0.1 for localhost only.
# Separate multiple entries with spaces ( ) or commas (,).
#
bindip                = 0.0.0.0        # IPv4 only - all IP's
#bindip                = ::            # IPv4 and IPv6 - all IP's (linux)
#bindip                = ::            # IPv6 only - all IP's (BSD)
#bindip                = 0.0.0.0,::    # IPv4 and IPv6 - all IP's (BSD)
#
# The maximum length of the queue of pending connections. See
# listen(2) for more information
#
# backlog              = 128
#
# Idle time allowed before a connection is shut off.
#
timeout              = 300           
#
# Idle time allowed before a connection is shut off if you have not logged in yet.
#
login_timeout        = 60
#
# If yes, resolves IP addresses to DNS names when logging.
#
resolve_ip            = yes
#
# If yes, keep statistics in the authlog table for connecting users
#
authlog              = no
#
# logfile for stdout messages
#
logfile              = /var/log/dbmail.log       
#
# logfile for stderr messages
#
errorlog              = /var/log/dbmail.err       
#
# directory for storing PID files
#
pid_directory        = /var/run/dbmail
#
# directory for locating libraries (normally has a sane default compiled-in)
#
library_directory      = /usr/lib/dbmail
#
# SSL/TLS certificates
#
# A file containing a list of CAs in PEM format
tls_cafile            =
# A file containing a PEM format certificate
tls_cert              =
# A file containing a PEM format RSA or DSA key
tls_key              =
# A cipher list string in the format given in ciphers(1)
tls_ciphers          =
# hashing algorithm. You can select your favorite hash type
# for generating unique ids for message parts.
#
# for valid values check mhash(3) but minus the MHASH_ prefix.
# if you ever change this value run 'dbmail-util --rehash' to
# update the hash for all mimeparts.
#
# examples: MD5, SHA1, SHA256, SHA512, TIGER, WHIRLPOOL
#
# hash_algorithm = SHA1
# header_cache tuning
#
# set header_cache_readonly to 'yes' to prevent new
# unknown header-names from being cached.
#
# header_cache_readonly = yes
[LMTP]
bindip = 127.0.0.1
port                  = 24               
#tls_port              =
[POP]
port                  = 110
#tls_port              = 995
# You can set an alternate banner to display when connecting to the service
# banner = DBMAIL pop3 server ready to rock
#
# If yes, allows SMTP access from the host IP connecting by POP3.
# This requires addition configuration of your MTA
#
pop_before_smtp      = no     
[HTTP]
port                  = 41380
#
# the httpd daemon provides full access to all users, mailboxes
# and messages. Be very careful with this one!
bindip                = 127.0.0.1
admin                = admin:secret
[IMAP]
# You can set an alternate banner to display when connecting to the service
# banner = imap 4r1 server (dbmail 2.3.x)
#
# Port to bind to.
#
port                  = 143               
##tls_port              = 993
#
# IMAP prefers a longer timeout than other services.
#
timeout              = 4000           
#
# If yes, allows SMTP access from the host IP connecting by IMAP.
# This requires addition configuration of your MTA
#
imap_before_smtp      = no
#
# during IDLE, how many seconds between checking the mailbox
# status (default: 30)
#
# idle_timeout          = 30
# during IDLE, how often should the server send an '* OK' still
# here message (default: 10)
#
# the time between such a message is idle_timeout * idle_interval
# seconds
#
# idle_interval        = 10
#
# If TLS is enabled, login before starttls is normally
# not allowed. Use login_disabled=no to change this
#
# login_disabled        = yes
#
# Provide a CAPABILITY to override the default
#
# capability            = IMAP4 IMAP4rev1 AUTH=LOGIN ACL RIGHTS=texk NAMESPACE CHILDREN SORT QUOTA THREAD=ORDEREDSUBJECT UNSELECT IDLE
# max message size. You can specify the maximum message size
# accepted by the IMAP daemon during APPEND commands.
#
# Supported formats:
#  decimal: 1000000   
#  octal:  03777777
#  hex:    0xfffff
#
# max_message_size      =
[SIEVE]
#
# Port to bind to.
#
port                  = 2000             
tls_port              =
[LDAP]
port                  = 389
version              = 3
hostname              = ldap
base_dn              = ou=People,dc=mydomain,dc=com
#
# If your LDAP library supports ldap_initialize(), then you can use the
# alternative LDAP server DSN like following.
#
# URI                = ldap://127.0.0.1:389
# URI                = ldapi://%2fvar%2frun%2fopenldap%2fldapi/
#
# Leave blank for anonymous bind.
# example: cn=admin,dc=mydomain,dc=com    
#
bind_dn              =
#
# Leave blank for anonymous bind.
#
bind_pw              =
scope                = SubTree
# AD users may want to set this to 'no' to disable
# ldap referrals if you are seeing 'Operations errors'
# in your logs
#
referrals            = yes
user_objectclass      = top,account,dbmailUser
forw_objectclass      = top,account,dbmailForwardingAddress
cn_string            = uid
field_passwd          = userPassword
field_uid            = uid
field_nid            = uidNumber
min_nid              = 10000
max_nid              = 15000
field_cid            = gidNumber
min_cid              = 10000
max_cid              = 15000
# a comma-separated list of attributes to match when searching
# for users or forwards that match a delivery address. A match
# on any of them is a hit.
field_mail            = mail
# field that holds the mail-quota size for a user.
field_quota          = mailQuota
# field that holds the forwarding address.
field_fwdtarget      = mailForwardingAddress
# override the query string used to search for users
# or forwards with a delivery address.
# query_string          = (mail=%s)
[DELIVERY]
#
# Run Sieve scripts as messages are delivered.
#
SIEVE                = yes             
#
# Use 'user+mailbox@domain' format to deliver to a mailbox.
#
SUBADDRESS            = yes         
#
# Turn on/off the Sieve Vacation extension.
#
SIEVE_VACATION        = yes     
#
# Turn on/off the Sieve Notify extension
#
SIEVE_NOTIFY          = yes
#
# Turn on/off additional Sieve debugging.
#
SIEVE_DEBUG          = no         
# Use the auto_notify table to send email notifications.
#
AUTO_NOTIFY          = no
#
# Use the auto_reply table to send away messages.
#
AUTO_REPLY            = no
#
# Defaults to "NEW MAIL NOTIFICATION"
#
#AUTO_NOTIFY_SUBJECT        =   
#
# Defaults to POSTMASTER from the DBMAIL section.
#
#AUTO_NOTIFY_SENDER        = 
# If you set this to 'yes' dbmail will check for duplicate
# messages in the relevant mailbox during delivery using
# the Message-ID header
#
suppress_duplicates    = no
#
# Soft or hard bounce on over-quota delivery
#
quota_failure          = hard
# end of configuration file
* перезапуск службы:
systemctl restart dbmail


*Патч для увеличения максимального количества полуоткрытых соединений
* ''проверка работы с базой'':
Впервые данное ограничение было введено компанией Microsoft в SP2 (Service Pack 2) для Windows XP и присутствует в последующих
  dbmail-util -av
версиях Windows.
 
Это было сделано в попытке замедлить распространение вирусов с зараженного компьютера, а также ограничить возможности участия
* С установкой '''dbmail''' пока окончено, следующий этап установка '''postgesql''' и настройка для будущей работы.
  компьютера в DoS-атаках (от англ. Denial of Service, отказ в обслуживании).
Ограничение заключается в том, что компьютеру не разрешается иметь более 10 одновременных полуоткрытых исходящих соединений.
При достижении предела новые попытки подключений ставятся в очередь. Таким образом, фактически ограничена скорость подключения
к другим компьютерам.
('''Патч Half-open limit fix''' http://half-open.com/download_ru.htm) позволяет убрать это ограничение, то есть увеличить
максимальный предел полуоткрытых соединений. Для подавляющего большинства пользователей будет достаточным предел, равный 100


*Оптимизация работы клиента на медленном канале:
4. ''[[Настройка PostgreSQL]]''
'''Цельный курсор'''
Установка курсора немигающим очень эффективно в низкоскоростных соединениях. Мерцающий курсор посылает несколько байт
данных при каждом мерцании, и запрет мерцания экономит немного полосы пропускания.
HKEY_USERS/.default/Control Panel/Desktop
Установите значение CursorBlinkRate Reg_SZ -1 (1200)
'''Скорость обновления меню Start'''
Вы можете увеличить скорость обновления, чтобы уменьшить время ответа в меню.
"HKEY_USERS\DEFAULT\Control Panel\Desktop"
Добавьте значение: MenuShowDelay REG_DWORD: 10 (400)


*Полезные советы и ссылки:
5. После того как мы настроили базу данных '''postgresql''', создаем пользователя '''dbmail''' и базу '''dbmail'''<br>
('''Решение проблем с терминальным сервером и не только''' http://adsh.ukrweb.net/win2k/fido_faq_10.html)
* Создаем пользователя для работы с почтовой базой
createuser -U postgres -P dbmail


*Без перезагрузки компьютера средствами командной строки, как правило, не обходится ни один диск автоматической установки Windows - это завершающая процедура, после которой компьютер уже готов к использованию. Перезагрузить компьютер можно различными способами.
* Создаем базу
Команда shutdown
createdb -U postgres --owner dbmail dbmail


    shutdown.exe -r -f -t 20 -c "Don`t panic. The system will reboot in 20 seconds."
* Вместе с dbmail идут заготовки базы, распаковываем и заливаем:
 
bunzip2 /usr/share/doc/dbmail-2.2.10/create_tables.pgsql.bz2
Справка: shutdown /?
psql -U dbmail -d dbmail < /usr/share/doc/dbmail-2.2.10/create_tables.pgsql
 
* управление screensaver в терминальном сервере
[http://amaksimov.wordpress.com/2011/10/15/computer-block-lock-out-via-screen-saver-timeout-and-password-protect-with-gpp-group-policy-preferences/ screensaver в терминальном сервере]
 
'''944984 - на сервере стоит SP2 который уже идет с User Profile Hive Cleanup'''
  Service (UPHClean).
  906952 -  на сервере отключен мап любых принтеров и остального,
  кроме дисков (флешки и флопы мапить), там отмечено, что эта проблема была учтена в SP2. Также
  там написано, что ее включить надо, так вот этот момент немного не понятен:
 
  To enable this hotfix, you must create the PrinterMaskKey registry subkey. To do
  this, follow these steps:
 
  1. Click Start, click Run, type regedit, and then click OK.
  2. Locate the following registry subkey:
  HKEY_USERS\.default\printers
  3. Right-click the registry subkey that you located in step 2, point to New,
  click Key, type PrinterMaskKey, and then press ENTER.
  4. Exit Registry Editor.
  Что конкретно нужно создать в ветке HKEY_USERS\.default\printers, если не
  трудно, поясните?
  '''''--В локаликозованной версии regedit Key = Раздел Т.е. надо создать подраздел
  PrinterMaskKey внутри HKEY_USERS\.default\printers'''''
 
[[Hotfix - terminal server win]]
 
== Настройка меню пользователя в Win2003 ==
*как скрыть пункт в меню Пуск - Администрирование, от терминальных пользователей?
 
В групповых политиках, конфигурации пользователя, административных шаблонах, в настройках меню "Пуск" отключите необходимые элементы.
 
Пример:
 
Конфигурация пользователя -> Настройка -> Параметры панели управления -> Главное меню
 
[[Файл:Win2008adm.jpg]]
 
== Решение проблем по принтерам фирмы Canon ==
 
* [https://forum.sysadmins.su/index.php?showtopic=40251246 падения спула печати]
* [http://www.it-ho.ru/page_story.php?id=79 программное решение проблемы печати]
* [http://forum.infostart.ru/forum73/topic53155/ еще описание настроек программно]
 
==Удаленный сеанс отключен из-за отсутствия доступных лицензий клиента сервера терминалов для этого компьютера. Обратитесь к администратору сервера.==
 
При попытке подключиться к удалённому рабочему столу, выдаёт ошибку "Удаленный сеанс отключен из-за отсутствия доступных лицензий клиента сервера терминалов для этого компьютера. Обратитесь к администратору сервера", что делать? Как исправить проблему?


* В этом дампе нету таблицы для работы с виртуальными доменами, создадим ее:
  CREATE TYPE dtype AS ENUM (
  'LOCAL',
  'VIRTUAL',
  'RELAY'
);
ALTER TYPE public.dtype OWNER TO dbmail;
SET default_with_oids = true;
CREATE TABLE dbmail_domains (
  uid integer NOT NULL,
  domain character varying(128) NOT NULL,
  type dtype NOT NULL
);
   
   
INSERT INTO dbmail_domains (uid, domain, type) VALUES (1, 'example.com', 'LOCAL');


Решение:
'''База готова.'''
 
Необходимо удалить раздел реестра MSLicensing. Для этого проделайте следующие действия:
 
    На клиенте перейдите в следующий подраздел реестра: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSLicensing.
    Выберите пункт MSLicensing.
    В меню Правка выберите команду Удалить, а затем нажмите кнопку Да, чтобы подтвердить удаление подраздела реестра MSLicensing.
    Закройте редактор реестра и пробуйте снова подключиться к удалённому компьютеру.
 
Исхода возможно два:
 
1) всё запустится и будет работать.
 
2) не запустится, но выдаст уже другую ошибку "Удаленный компьютер отключил сеанс из-за ошибки в протоколе лицензирования. Попытайтесь подключиться к удаленному компьютеру снова или обратитесь к администратору сервера".
 
Если вы получили второй исход, это означает, что раздел MSLicensing не смог создаться заново, чтобы он создался необходимо попробовать подключиться к удалённому компьютеру из под учётной записи обладающей правами администратора на данном компьютере. После этого под всеми остальными пользователями всё снова начнёт работать нормально.
 
[http://nopcproblem.ru/index.php/articles/1-articles/70-udalseansotklyuchen взято тут]
 
или
 
При подключении к удалённому рабочему столу возникает следующая ошибка: "Удаленный сеанс отключен из-за отсутствия доступных лицензий клиента сервера терминалов для этого компьютера".
 
Данная проблема решается двумя способами:
 
Если нет возможности изменить настройки сервера, то используем способ 1, иначе способ 2.
 
Способ 1. На стороне клиента
 
Необходимо удалить раздел "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSLicensing\Store\LICENSE000". Сделать это можно, например, выполнив следующую команду:
 
reg delete "HKLM\SOFTWARE\Microsoft\MSLicensing\Store\LICENSE000" /f
 
или тоже самое, но руками:
 
    "Пуск" > "Выполнить..." > Набираем "regedit.exe" и жмём OK.
    Слева в дереве выбираем ветку " HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSLicensing\Store\LICENSE000".
    Правой кнопкой мыши жмём по элементу " LICENSE000" и выбираем "Удалить".
 
Примечание 1. Можно встретить рекомендацию удалить ветку всю ветку "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSLicensing". Можно, но не нужно. Достаточно удалить подветку Store\LICENSE000.
Примечание 2. Говорят (я не проверял), что на Windows Vista следует запустить "Подключение к удалённому рабочему столу" (mstsc.exe) от имени администратора.
Примечание 3. Когда вообще ничего не помогает, то подключаемся к удалённому рабочему столу с Windows XP, а затем переносим ветку "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSLicensing" на машину с Windows Vista/7.
 
Способ 2. На стороне сервера
 
Понятно, что на каждом клиенте решать проблему неправильно и неудобно. Такая ошибка возникает, когда режим лицензирования сервера терминалов на сервере терминалов настроен как "На устройство", а на сервере лицензий имеются только клиентские лицензии доступа "На пользователя".  В статье KB822134 показано, как решить эту проблему:
 
    Нажмите кнопку "Пуск" и выберите последовательно пункты "Администрирование" и "Настройка служб терминалов".
    Выберите узел "Параметры сервера" и дважды щелкните элемент "Лицензирование".
    Установите для параметра "Режим лицензирования" значение "На пользователя" и нажмите кнопку "ОК".


[http://kaktusenok.blogspot.ru/2012/01/blog-post_28.html от сюда...]


==Сопоставление принтеров в терминальном подключении Win2003 R2==
<hr>
Решение проблемы: Сопоставление драйверов от клиента к серверу
Для решения этой проблемы можно сопоставить имена драйверов принтеров на сервере с именами драйверов на клиентах. Например, вы можете сказать серверу, что драйвер клиентского принтера с именем “Hewlett Packard LaserJet 5P” является тем же драйвером, что и драйвер на сервере “HP LaserJet 5P.”
Учтите, что это вам нужно, если (1) вы используете отображение клиентских принтеров и (2) используете клиентов, отличных от Windows 2000 или Windows XP.
Чтобы разрешить сопоставление драйверов, разместите на терминальном сервере файл, который содержит пары имен драйверов на стороне клиента и на стороне сервера. В ранних версиях сервера терминалов это делалось с помощью файла “wtsuprn.inf”, находящегося в каталоге %systemroot%\system32\. Однако, в Windows Server 2003 этого файла нет и он не ищется.
Для создания файла сопоставления в Windows 2003 вам нужно добавить в реестр два значения:
Key: HKLM\SYSTEM\CurrentControlSet\
Control\Terminal Server\Wds\rdpwd
Type: REG_SZ
Value: PrinterMappingINFName
Data: Имя файла .INF, содержащего сопоставление имен драйверов - например, c:\winnt\inf\printsubs.inf
Key: HKLM\SYSTEM\CurrentControlSet\
Control\Terminal Server\Wds\rdpwd
Type: REG_SZ
Value: PrinterMappingINFSection
Data: Наименование раздела в файле .INF, содержащего собственно сопоставление (Например, Printers)
После внесения изменений реестр перезапустите службу спулера или перезагрузите сервер терминалов, чтобы изменения вступили в силу. После изменения реестра вам следует создать файл .INF, включающий имена драйверов. Этот файл должен выглядеть так:
;PRINTSUBS.INF
;This file contains Mappings for Client driver to Server driver printer connections
[Printers]
;"Client Printer Driver Name" = "Server Printer Drive Name"
"Hewlett Packard LaserJet 5P" = "HP LaserJet 5P"
Вы можете создать этот файл в Notepad и сохранить его с расширением .INF в каталоге %SystemRoot%\System32\.
Имена драйверов в этом файле чувствительны к реестру и пробелам. Все, что находится внутри кавычек, должно точно соответствовать имени драйвера. Как и в большинстве файлов .INF лидирующий символ точка-с-запятой ( означает комментарий и такая строка игнорируется. При использовании этого файла вы можете включить в него несколько сопоставлений имен драйверов.
Создание карты сопоставления - больше искусство, чем наука. К счастью, есть замечательный сайт www.printingsupport.com. На нем вы найдете файлы сопоставления имен драйверов, которые можете использовать в своей среде.
Создав файл сопоставления, вы должны разместить его на всех терминальных серверах, где применяется отображение клиентских принтеров. Учтите, этот файл указывает на драйверы, которые должны быть инсталлированы на терминальном сервере.
Если ваш файл .INF содержит синтаксические ошибки (кроме неверного указания имени драйвера внутри кавычек), вы можете получить в журнале событий следующее сообщение:
Event 1110: "Error processing ntprint.inf. If the file on the system is corrupt, you can restore it from the installation media.
Это сообщение сбивает с толку, поскольку ссылается на файл “ntprint.inf ”, а не на указанное вами имя файла. Эта ошибка обычно означает, что ваш файл .INF содержит ошибку. Чаще всего это бывает, когда в файле не содержится записей. Ваш новый файл .INF должен содержать минимум одно сопоставление и минимум одно сопоставление не должно начинаться с символа комментария. Если ваш файл .INF содержит пустое имя секции, вы также получите ошибку 1110.


* [http://winitpro.ru/index.php/2013/03/12/masshtabirovanie-ekrana-v-rdp-sessii/ Масштабирование экрана в RDP сессии]
Источники:
* [http://samag.ru/archive/article/1850 Настраиваем подключения к удаленному рабочему столу]
<hr>
* [https://www.atraining.ru/windows-rdp-tuning/ Защищаем и оптимизируем RDP ]
* [https://habrahabr.ru/post/37195/ Настройка exim+postgresql+dbmail+spamassassin...]
* [http://www.oszone.net/10156/Windows-Remote-Desktop Запуск Windows Remote Desktop Connection из командной строки]
* [https://www.opennet.ru/docs/RUS/dbmail/#dbmail_fs Создание почтовой системы на базе exim, dbmail, amavisd-new и postgresql]
* [http://cmd4win.ru/upravlenie-serverom/132-komanda-mstsc Команда Mstsc - подключение по RDP]
* [https://www.opennet.ru/docs/RUS/dbmail_postfix/ Почтовый сервер на основе реляционной СУБД]
* [http://ab57.ru/cmdlist/mstsc.html Параметры RDP]
* [https://habrahabr.ru/post/211078/ Почтовый сервер с хранением данных в PostgreSQL]
* [https://habr.com/post/147273/ удаленное управление]
* [https://www.opennet.ru/base/net/exim_intro.txt.html  Exim (exim mail mta virtual spam virus clamav freebsd imap postgresql)]
* [http://www.linuxcenter.ru/lib/articles/soft/ezh_mailsystem.phtml?style=print Создание почтовой системы на базе exim, dbmail, amavisd-new и postgresql]
* [https://www.lissyara.su/archive/exim+dbmail/ Exim и dbmail]

Версия от 17:39, 31 октября 2017

Порядок установки:

  • Система Debian Stretch {9}
  • Используемый source.list
# 
deb http://mirror.mephi.ru/debian/ stretch main
deb-src http://mirror.mephi.ru/debian/ stretch main

deb http://security.debian.org/debian-security stretch/updates main
deb-src http://security.debian.org/debian-security stretch/updates main 

# stretch-updates, previously known as 'volatile'
deb http://mirror.mephi.ru/debian/ stretch-updates main
deb-src http://mirror.mephi.ru/debian/ stretch-updates main

###### Debian Main Repos
deb http://deb.debian.org/debian/ stable main contrib non-free
deb-src http://deb.debian.org/debian/ stable main contrib non-free

deb http://deb.debian.org/debian/ stable-updates main contrib non-free
deb-src http://deb.debian.org/debian/ stable-updates main contrib non-free

deb http://deb.debian.org/debian-security stable/updates main contrib non-free
deb-src http://deb.debian.org/debian-security stable/updates main contrib non-free

deb http://ftp.debian.org/debian stretch-backports main contrib non-free
deb-src http://ftp.debian.org/debian stretch-backports main contrib non-free

1. Устанавливаем необходимые пакеты:

apt-get install pkg-config libglib2.0-dev libgmime-2.6-dev libmhash-dev libevent-dev libssl1.0-dev libzdb-dev
autoconf automake libtool autotools-dev dpkg-dev fakeroot

2. Скачиваем с dbmail.org исходники:

wget -c -t 0 -T 8 http://www.dbmail.org/download/3.1/dbmail-3.1.17.tar.gz

3. Распаковываем и компилируем:

cp dbmail-3.1.17.tar.gz /usr/local/src
tar -xf dbmail-3.1.17.tar.gz /usr/local/src.dbmail-3.1.17
cp dbmail-3.1.17.tar.gz /usr/local/src/dbmail_3.0.2.orig.tar.gz

Готовим пакет к сборке:

cd /usr/local/src/dbmail-3.2.3
./configure --with-pgsql --prefix=/usr
 
dpkg-source --commit

даем имя, что-то pgsql.commit

cd /usr/local/src/
dpkg-source -b dbmail-3.2.3
cd /usr/local/src/dbmail-3.2.3
dpkg-buildpackage -d
  • после того как соберется пакет, копируем себе в архив и ставим.
dpkg -i dbmail_3.2.3-1_amd64.deb
  • правим файл конфигурации:
editor /etc/dbmail/dbmail.conf
  • пример рабочего конфигурационного файла:
	# (c) 2000-2006 IC&S, The Netherlands 

# # Configuration file for DBMAIL

[DBMAIL] # # Database settings # # database connection URI

#dburi = sqlite:///var/tmp/dbmail.db

# # Supported drivers are sql, ldap. # authdriver = sql

# # # following fields are now DEPRECATED! driver = postgresql host = 10.0.5.2 sqlport = 5432 #sqlsocket = user = dbmail pass = dbmailpass db = mailbasename

# # Number of database connections per threaded daemon # This also determines the size of the worker threadpool # # Do NOT increase this without proper consideration. A # very large database/worker pool will not only increase # the connection pressure on the database, but will more # significantly cause unnecessary context-switching in # your CPUs. # #max_db_connections = 10

# # Table prefix. Defaults to "dbmail_" if not specified. # table_prefix = dbmail_

# # encoding must match the database/table encoding. # i.e. latin1, utf8 encoding = utf8

# # messages with unknown encoding will be assumed to have # default_msg_encoding # i.e. iso8859-1, utf8 default_msg_encoding = utf8

# # Postmaster's email address for use in bounce messages. # #postmaster = DBMAIL-MAILER

# # Sendmail executable for forwards, replies, notifies, vacations. # You may use pipes (|) in this command, for example: # dos2unix|/usr/sbin/sendmail works well with Qmail. # You may use quotes (") for executables with unusual names. # sendmail = /usr/sbin/sendmail

# # # The following items can be overridden in the service-specific sections. # #

# # Logging via stderr/log file and syslog # # Logging is broken up into 8 logging levels and each level can be indivually turned on or off. # The Stderr/log file logs all entries to stderr or the log file. # Syslog logging uses the facility mail and the logging level of the event for logging. # Syslog can then be configured to log data according to the levels. # # Set the log level to the sum of the values next to the levels you want to record. # 1 = Emergency # 2 = Alert # 4 = Critical # 8 = Error # 16 = Warning # 32 = Notice # 64 = Info # 128 = Debug # 256 = Database -> Logs at debug level # # Examples: 0 = Nothing # 31 = Emergency + Alert + Critical + Error + Warning # 511 = Everything # file_logging_levels = 7 # syslog_logging_levels = 31

# # Generate a log entry for database queries for the log level at number of seconds of query execution time. # query_time_info = 10 query_time_notice = 20 query_time_warning = 30

# # Throw an exception is the query takes longer than query_timeout seconds query_timeout = 300

# # Root privs are used to open a port, then privs # are dropped down to the user/group specified here. # effective_user = dbmail effective_group = mail

# # The IPv4 and/or IPv6 addresses the services will bind to. # Use * for all local interfaces. # Use 127.0.0.1 for localhost only. # Separate multiple entries with spaces ( ) or commas (,). # bindip = 0.0.0.0 # IPv4 only - all IP's #bindip = :: # IPv4 and IPv6 - all IP's (linux) #bindip = :: # IPv6 only - all IP's (BSD) #bindip = 0.0.0.0,:: # IPv4 and IPv6 - all IP's (BSD)


# # The maximum length of the queue of pending connections. See # listen(2) for more information # # backlog = 128

# # Idle time allowed before a connection is shut off. # timeout = 300

# # Idle time allowed before a connection is shut off if you have not logged in yet. # login_timeout = 60

# # If yes, resolves IP addresses to DNS names when logging. # resolve_ip = yes

# # If yes, keep statistics in the authlog table for connecting users # authlog = no

# # logfile for stdout messages # logfile = /var/log/dbmail.log

# # logfile for stderr messages # errorlog = /var/log/dbmail.err

# # directory for storing PID files # pid_directory = /var/run/dbmail

# # directory for locating libraries (normally has a sane default compiled-in) # library_directory = /usr/lib/dbmail

# # SSL/TLS certificates # # A file containing a list of CAs in PEM format tls_cafile =

# A file containing a PEM format certificate tls_cert =

# A file containing a PEM format RSA or DSA key tls_key =

# A cipher list string in the format given in ciphers(1) tls_ciphers =


# hashing algorithm. You can select your favorite hash type # for generating unique ids for message parts. # # for valid values check mhash(3) but minus the MHASH_ prefix. # # if you ever change this value run 'dbmail-util --rehash' to # update the hash for all mimeparts. # # examples: MD5, SHA1, SHA256, SHA512, TIGER, WHIRLPOOL # # hash_algorithm = SHA1


# header_cache tuning # # set header_cache_readonly to 'yes' to prevent new # unknown header-names from being cached. # # header_cache_readonly = yes


[LMTP] bindip = 127.0.0.1 port = 24 #tls_port =


[POP] port = 110 #tls_port = 995

# You can set an alternate banner to display when connecting to the service # banner = DBMAIL pop3 server ready to rock

# # If yes, allows SMTP access from the host IP connecting by POP3. # This requires addition configuration of your MTA # pop_before_smtp = no

[HTTP] port = 41380 # # the httpd daemon provides full access to all users, mailboxes # and messages. Be very careful with this one! bindip = 127.0.0.1 admin = admin:secret

[IMAP] # You can set an alternate banner to display when connecting to the service # banner = imap 4r1 server (dbmail 2.3.x)

# # Port to bind to. # port = 143 ##tls_port = 993

# # IMAP prefers a longer timeout than other services. # timeout = 4000

# # If yes, allows SMTP access from the host IP connecting by IMAP. # This requires addition configuration of your MTA # imap_before_smtp = no

# # during IDLE, how many seconds between checking the mailbox # status (default: 30) # # idle_timeout = 30

# during IDLE, how often should the server send an '* OK' still # here message (default: 10) # # the time between such a message is idle_timeout * idle_interval # seconds # # idle_interval = 10

# # If TLS is enabled, login before starttls is normally # not allowed. Use login_disabled=no to change this # # login_disabled = yes

# # Provide a CAPABILITY to override the default # # capability = IMAP4 IMAP4rev1 AUTH=LOGIN ACL RIGHTS=texk NAMESPACE CHILDREN SORT QUOTA THREAD=ORDEREDSUBJECT UNSELECT IDLE

# max message size. You can specify the maximum message size # accepted by the IMAP daemon during APPEND commands. # # Supported formats: # decimal: 1000000 # octal: 03777777 # hex: 0xfffff # # max_message_size =


[SIEVE] # # Port to bind to. # port = 2000 tls_port =


[LDAP] port = 389 version = 3 hostname = ldap base_dn = ou=People,dc=mydomain,dc=com

# # If your LDAP library supports ldap_initialize(), then you can use the # alternative LDAP server DSN like following. # # URI = ldap://127.0.0.1:389 # URI = ldapi://%2fvar%2frun%2fopenldap%2fldapi/

# # Leave blank for anonymous bind. # example: cn=admin,dc=mydomain,dc=com # bind_dn =

# # Leave blank for anonymous bind. # bind_pw = scope = SubTree

# AD users may want to set this to 'no' to disable # ldap referrals if you are seeing 'Operations errors' # in your logs # referrals = yes

user_objectclass = top,account,dbmailUser forw_objectclass = top,account,dbmailForwardingAddress cn_string = uid field_passwd = userPassword field_uid = uid field_nid = uidNumber min_nid = 10000 max_nid = 15000 field_cid = gidNumber min_cid = 10000 max_cid = 15000

# a comma-separated list of attributes to match when searching # for users or forwards that match a delivery address. A match # on any of them is a hit. field_mail = mail

# field that holds the mail-quota size for a user. field_quota = mailQuota

# field that holds the forwarding address. field_fwdtarget = mailForwardingAddress

# override the query string used to search for users # or forwards with a delivery address. # query_string = (mail=%s)

[DELIVERY] # # Run Sieve scripts as messages are delivered. # SIEVE = yes

# # Use 'user+mailbox@domain' format to deliver to a mailbox. # SUBADDRESS = yes

# # Turn on/off the Sieve Vacation extension. # SIEVE_VACATION = yes

# # Turn on/off the Sieve Notify extension # SIEVE_NOTIFY = yes

# # Turn on/off additional Sieve debugging. # SIEVE_DEBUG = no


# Use the auto_notify table to send email notifications. # AUTO_NOTIFY = no

# # Use the auto_reply table to send away messages. # AUTO_REPLY = no

# # Defaults to "NEW MAIL NOTIFICATION" # #AUTO_NOTIFY_SUBJECT =

# # Defaults to POSTMASTER from the DBMAIL section. # #AUTO_NOTIFY_SENDER =


# If you set this to 'yes' dbmail will check for duplicate # messages in the relevant mailbox during delivery using # the Message-ID header # suppress_duplicates = no

# # Soft or hard bounce on over-quota delivery # quota_failure = hard


# end of configuration file

  • перезапуск службы:
systemctl restart dbmail
  • проверка работы с базой:
dbmail-util -av
 
  • С установкой dbmail пока окончено, следующий этап установка postgesql и настройка для будущей работы.

4. Настройка PostgreSQL

5. После того как мы настроили базу данных postgresql, создаем пользователя dbmail и базу dbmail

  • Создаем пользователя для работы с почтовой базой
createuser -U postgres -P dbmail
  • Создаем базу
createdb -U postgres --owner dbmail dbmail
  • Вместе с dbmail идут заготовки базы, распаковываем и заливаем:
bunzip2 /usr/share/doc/dbmail-2.2.10/create_tables.pgsql.bz2
psql -U dbmail -d dbmail < /usr/share/doc/dbmail-2.2.10/create_tables.pgsql
  • В этом дампе нету таблицы для работы с виртуальными доменами, создадим ее:
 CREATE TYPE dtype AS ENUM ( 
 'LOCAL', 
 'VIRTUAL', 
 'RELAY' 
); 

ALTER TYPE public.dtype OWNER TO dbmail; 

SET default_with_oids = true; 

CREATE TABLE dbmail_domains ( 
 uid integer NOT NULL, 
 domain character varying(128) NOT NULL, 
 type dtype NOT NULL 
);

INSERT INTO dbmail_domains (uid, domain, type) VALUES (1, 'example.com', 'LOCAL');

База готова.



Источники: