- Начальная настройка ИБП APC в Linux с точки зрения чайника
- Настройка APC Smart UPS 1000 в Ubuntu server 14.04 LTS и установка модуля Webmin
- Linux: Configure and Control APC SmartUPS During a Power Failure
- Step #1: Install Apcupsd
- Step 2: Connect UPS
- Step #3: Configure UPS
- Configuration parameters used during power failures
- Configuration apcupsd network information server
- Step #4: Test ups
- How do I start apcupsd server?
- How do I see current status of my UPS?
- How do I view ups events such as power failure?
- A note about desktop GUI monitoring tool
- A note about web based monitoring tool
- Check out related media
- Ubuntu Documentation
- Introduction
- Prerequisites
- Installation
- When using systemd
- apcupsd-cgi via Apache
- apcupsd-cgi via Webmin
- External links
Начальная настройка ИБП APC в Linux с точки зрения чайника
Купив источник бесперебойного питания от APC (а именно — APC Back-UPS ES 550VA ), я с удивленьем обнаружил, что «из коробки» он не может похвастаться тесной дружбою с Linux. Конечно, XFCE Power Manager, входящий в состав XFCE 4.6, подхватил и разпознал UPS, но всё, на что он оказался способен — отображение в трее уровня заряда. Какие-либо настройки отсутствовали начисто, нельзя было даже задать выключение ПК при достижении определённого уровня заряда.
Обратившись за консультацией в гугл, я узнал о существовании замечательного демона apcupsd, чья роль заключается в — никогда не поверите — управлении ИБП от APC. Но, как оказалось, практически все руководства по его начальной настройке были откровенно устаревшими — включая, как ни странно, официальный мануал. Споткнуться приходилось уже в самом начале о «cat /proc/bus/usb/devices». Поговорив с гуглом серьёзным и доверительным тоном, я добился от него ссылки на действующий мануал, художественным переводом коего с дополнениями из иных источников сия статья и является.
Итак, начнём с установки самого apcupsd:
sudo apt-get install apcupsd
Разумеется, вышесказанное справедливо для Debian и его производных, включая Ubuntu. Если в вашем дистрибутиве не используется apt-get — думаю, вы всё равно знаете, как поставить необходимый пакет. Надеюсь на это.
Теперь мы отредактируем конфигурационный файл apcupsd:
sudo gedit /etc/apcupsd/apcupsd.conf
В данном случае нас интересуют всего три параметра:
UPSCABLE — указываем тип кабеля, которым наш UPS подключён к ПК. В комментариях указаны возможные типы — simple, smart, ether, usb. Нынешние домашние модели подключаются через USB — следовательно, достаточно дописать usb
UPSTYPE — тип подключённого UPS. В комментариях перечислены возможные типы и соответствующие им значения параметра DEVICE, наш же выбор — тип usb
DEVICE — закомментируем данную строку, поставив перед ней знак # — для USB-устройств она не нужна
Сохраняем изменённый конфигурационный файл, открываем следующий:
sudo gedit /etc/default/apcupsd
Заменяем ISCONFIGURED=no на ISCONFIGURED=yes, сохраняем, закрываем. Отныне apcupsd будет знать, что мы не забыли его настроить.
Теперь достаточно запустить apcupsd:
sudo /etc/init.d/apcupsd start
Если он уже был запущен — вместо start нам, разумеется, надо будет писать restart.
Всё, ваш ПК теперь связан с новеньким ИБП прочными узами дружбы.
А теперь немножко о том, что мы можем настроить в обширном /etc/apcupsd/apcupsd.conf:
ONBATTERYDELAY — время (в секундах), определяющее задержку между обнаружением сбоя электропитания и отсылкой события onbattery. По умолчанию — 6
BATTERYLEVEL — уровень заряда батареи (в процентах), при котором инициируется выключение компьютера. По умолчанию — 5
MINUTES — расчётное время остаточной работы (в минутах), при достижении которого инициируется выключение компьютера. По умолчанию — 3
TIMEOUT — параметр актуален для старых ИБП, неспособных определять свой уровень заряда. Задаёт время (в секундах) между сбоем электропитания и отключением компьютера. Для современного ИБП параметр стоит оставить на 0, но выставление иного значения может быть удобно для тестирования работы ИБП. Например, если выставить 30 и выдернуть шнур из розетки, уже через полминуты apcupsd продемонстрирует своё умение выключать компьютер
Выполнения одного из условий (BATTERYLEVEL, MINUTES или TIMEOUT) достаточно для выключения компьютера. Более тонкая настройка не описывается, ибо её необходимость для домашнего пользователя весьма сомнительна.
Долго сказка сказывается, да недолго дело делается: полагаю, описанные действия пользователь произведёт за пару минут. Надеюсь, данная статья поможет кому-нибудь подружить его ИБП APC с Linux, сэкономив время и не завязнув в устаревших мануалах.
Источник
Настройка APC Smart UPS 1000 в Ubuntu server 14.04 LTS и установка модуля Webmin
Началось все с того, что у меня сгорел служивший верой и правдой много лет Back-UPS 500VA. Не беда, подумал я и заменил его на APC Smart UPS 1000, что для моего сервера оказалось гораздо лучше. Сразу скажу, изначально сервер работал на форточках и проблем с бесперебойником не было. После замены ИБП и окончательно-бесповоротном переходе на Ubuntu я задался вопросом: собственно, как мониторить состояние сети электропитания и состояние бесперебойника? Погуглив некоторое время, я наткнулся на несколько инструкций по подключению бесперебойников к никсовым машинам, но почему-то они все были про Back UPS и USB. В частности, меня натолкнуло на написание этой статьи аналогичная статься на Хабре «Начальная настройка ИБП APC в Linux с точки зрения чайника».
Но у меня же старенький тысячник с ком-портом и про USB он и слыхом не слыхивал.
Предупреждаю! Внимательно выбирайте кабель COM-COM. Например, стандартный кабель от свича DES3526 вызывает аварийное отключение бесперебойника. У меня подошел проводок от другого UPS (на сколько помню — Sven).
Как выяснилось, демон для мониторинга/управления все-таки есть, только все инструкции к нему безнадежно устарели (включая официальные!).
Установка демона APC:
После установки начался геморрой с настройкой. Наступая на все грабли по очереди я все же добился своего:
Для снижения количества неудачных настроек для начала найдем порт ttyS:
У меня активных портов оказалось всего 2:
В разделе UPSNAME я обозвал свой бесперебойник:
В разделе UPSCABLE был выбран тип Smart:
В разделе UPSTYPE выбран apcsmart и нужный порт:
Далее осталось только сообщить демону, что мы не забыли его настроить:
Меняем в строке ISCONFIGURED=no на ISCONFIGURED=yes
И напоследок запустить сие чудо:
Когда эта скотина все-таки запустилась без ошибок, я сильно обрадовался. Осталось только вывести данные бесперебойника на веб-морду серва. Тут кроется загвоздочка: веб-морда у меня Webmin, модуль для него есть, но идет он не настроенный.
Установка модуля Apcupsd в Webmin:
Для начала скачаем модуль на рабочую станцию отсюда.
Затем зайдем в модули Webmin и добавим скачанный модуль.
Все установилось, но модуль ничего не показывает и пишет что не настроен — ничего! Допиливаем до рабочего состояния:
На рабочей станции приводим пути в настройках модуля в порядок:
Жмем сохранить и — вуаля!
*В связи с безвременной кончиной фотохостинга savepic скриншоты с уже подключенным Apc Smart UPS 3000 RM
Статью написал для того, чтобы никто больше не наступал на те же грабли и не гуглил бесполезными запросами.
Источник
Linux: Configure and Control APC SmartUPS During a Power Failure
M y Linux nas server connected to APC SmartUPS using usb cable and I would like to detect a power failure. If power is not restored my server must shutdown when the battery is exhausted. How do I configure and use my APC SmartUPS under Debina / Ubuntu / RHEL / CentOS / Fedora / Scientific Linux operating system for power management?
Tutorial details | |
---|---|
Difficulty level | Intermediate |
Root privileges | Yes |
Requirements | APC ups with cable |
Est. reading time | N/A |
Linux comes with GPL licensed open source apcupsd server ( daemon ) that can be used for power mangement and controlling most of APC’s UPS models on Linux, BSD, Unix and MS-Windows operating systems. Apcupsd works with most of APC’s Smart-UPS models as well as most simple signalling models such a Back-UPS, and BackUPS-Office. During a power failure, apcupsd will inform the users about the power failure and that a shutdown may occur. If power is not restored, a system shutdown will follow when the battery is exhausted, a timeout (seconds) expires, or runtime expires based on internal APC calculations determined by power consumption rates.
Step #1: Install Apcupsd
Type the following apt-get command under Debian / Ubuntu Linux install apcupsd software:
# apt-get install apcupsd
Sample outputs:
Edit /etc/default/apcupsd, enter:
# vi /etc/default/apcupsd
Set ISCONFIGURED to yes:
ISCONFIGURED=yes
Save and close the file. If you are using RHEL / CentOS Linux use yum command as follows, enter:
# yum install apcupsd
Sample outputs:
Step 2: Connect UPS
You need to connect the UPS to your server using cable. You will see the following entry in /var/log/messages
Step #3: Configure UPS
Edit /etc/apcupsd/apcupsd.conf, enter:
# vi /etc/apcupsd/apcupsd.conf
First, give your UPS a name. This is particulary useful if you have multiple UPSes. This does not set the EEPROM. It should be 8 characters or less:
Next, defines the type of cable connecting the UPS to your Linux server. In this example, I’m connecting my UPS using usb:
Possible generic choices for cable are – simple, smart, ether, and usb. Or a specific cable model number may be used such as 940-0119A. For USB UPSes, please leave the DEVICE directive blank. For
other UPS types, you must specify an appropriate port or address (see config file):
Configuration parameters used during power failures
The ONBATTERYDELAY directive defined the time in seconds from when a power failure s detected until we react to it with an onbattery event:
If during a power failure, the remaining battery percentage (as reported by the UPS) is below or equal to BATTERYLEVEL, apcupsd will initiate a Linux system shutdown:
If during a power failure, the remaining runtime in minutes (as calculated internally by the UPS) is below or equal to MINUTES, apcupsd, will initiate a system shutdown.
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
If during a power failure, the UPS has run on batteries for TIMEOUT many seconds or longer, apcupsd will initiate a system shutdown. A value of 0 disables this timer:
Note: If you have an older dumb UPS, you will want to set this to less than the time you know you can run on batteries.
Configuration apcupsd network information server
You can use CGI or GUI programs from remote system to get information about your UPS. Turn on network information server:
Set IP address on which NIS server will listen for incoming connections. You need to configure this setting to any specific IP address of your server and NIS will listen for connections only on that interface. Use the loopback address (127.0.0.1) to accept connections only from the local machine (default).
The default port is set to 3551for sending STATUS and EVENTS data over the network:
Save and close the file.
Step #4: Test ups
Type the following command:
# apctest
Sample outputs:
You can test your ups or read test results.
How do I start apcupsd server?
Type the following command to start / stop / restart service:
# /etc/init.d/apcupsd start
# /etc/init.d/apcupsd stop
# /etc/init.d/apcupsd restart
RHEL / CentOS / Red Hat / Fedora Linux can use the same command. However, you need to turn on service on boot:
# chkconfig apcupsd on
How do I see current status of my UPS?
Type the following command:
# apcaccess
Sample outputs:
How do I view ups events such as power failure?
The UPS status is logged in /var/log/apcupsd.events file. To view this file, enter:
# tail -f /var/log/apcupsd.events
Sample outputs:
A note about desktop GUI monitoring tool
Gapcmon is a desktop monitor program for the apcupsd server. You can install it using the following command:
# apt-get install gapcmon
OR use yum command for RHEL / CentOS Linux:
# yum install apcupsd-gui
Run it as follows:
$ gapcmon
A note about web based monitoring tool
You can install a package called apcupsd-cgi so that you can monitor your UPS load, uptime, logs and other details using www. Type the following apt-get command to install the same:
# apt-get install apcupsd-cgi
OR use yum command for RHEL / CentOS Linux:
# yum install apcupsd-cgi
You need to configure Apache web server with cgi-bin or lighttpd server with cgi-bin server. Once configured, type the url as follows using any web-browser:
http://server-ip/cgi-bin/apcupsd/multimon.cgi
Sample outputs from both desktop and web-base gui monitor tools:
Check out related media
This tutorial also available in video format:
(Video.01: Installing apc usp under Debian / Ubuntu Linux. Can’t view video? Click here.)
References
- APCUPSD project.
- man page – apcupsd, apt-get, and yum command.
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
Ubuntu Documentation
Introduction
The package apcupsd provides a daemon which will monitor your APC UPS, and shutdown the system when power is no longer being supplied to the UPS.
Prerequisites
An APC UPS. The apcupsd daemon works with most APC Smart-UPS models, as well as most simple signaling models, such as Back-UPS, and BackUPS-Office.
Installation
When using systemd
This example assumes you are using a APC Smart-UPS 750 via USB.
First, install the apcupsd package via a terminal:
Next, backup the original configuration files:
Next, edit the configuration files:
Now one may check the status of the UPS via a terminal:
In order to run apctest, one must first stop apcupsd via a terminal:
Otherwise, one may see the following error:
Once done, start apcupsd:
apcupsd-cgi via Apache
The following changes to a Ubuntu system should allow APCUPSD-CGI web interface to be accessible. Note that for this to work you must have Apache2 installed and configured properly for your Ubuntu system.
Start by installing the apcupsd-cgi package:
This will drop several files into /usr/lib/cgi-bin/apcupsd. For this to work you must have CGI enabled in your Apache configuration and the CGI directory should be pointed at /usr/lib/cgi-bin/. The only thing left is to go to the web address: http://localhost/cgi-bin/apcupsd/multimon.cgi
apcupsd-cgi via Webmin
The following changes to a Ubuntu system will allow APCUPSD-CGI web interface to be accessible as a module using webmin. Note that for this to work you must have webmin installed and configured properly for your Ubuntu system. Note: To install webmin in under 2 minutes click http://www.webmin.com/deb.html and follow the instructions under Using the Webmin APT repository.
Start by installing the apcupsd-cgi package with:
This will drop several files into /usr/lib/cgi-bin/apcupsd. Then copy the contents of /usr/lib/cgi-bin/apcuspd/ to /etc/apcupsd/:
External links
apcupsd (последним исправлял пользователь penalvch 2017-07-19 04:06:32)
The material on this wiki is available under a free license, see Copyright / License for details
You can contribute to this wiki, see Wiki Guide for details
Источник