Autorun shell: Добавить приложение для автоматического запуска при начальной загрузке Windows 10

Всё как у больших. Автозагрузка приложений в оконных менеджерах linux / Хабр

Вывод systemd-analyze dot —user ‘i3.service’ | dot -Tpng | imv —

Как-то раз, листая сообщения в профильном systemd чате, в телеграм, я наткнулся на следующий кусок man systemd.special

xdg-desktop-autostart.target
   The XDG specification defines a way to autostart applications using XDG desktop files.
systemd ships systemd-xdg-autostart-generator(8) for the XDG desktop files in autostart
directories. Desktop Environments can opt-in to use this service by adding a Wants=dependency
on xdg-desktop-autostart.target.

О как интересно, подумалось мне. Можно реализовать функционал полноценныхDesktop Environments, по автоматическому запуску приложений, при старте. А у меня как раз i3wm, который таковым не является и которому такой функционал не помешал бы. Надо это дело исследовать. Тогда я ещё не знал во что ввязался. Как оказалось, не всё так просто.



Переменные XDG, freedesktop.org, desktop-файлы и autostart

Пользователям полноценных линуксовых графических окружений (KDE, Gnome, Mate etc) прекрасно известна возможность автозапуска приложений при логине пользователя в систему, разработанную инициативной группой Freedesktop.org (ранее X Desktop Group, или XDG), подобная той, что существует, например, в Windows. Данный функционал обеспечивается обычными *.desktop файлами, но лежащими по определённым путям:


  • $XDG_CONFIG_DIRS/autostart/ (/etc/xdg/autostart/ по умолчанию) — общесистемная директория, для всех пользователей. Туда, обычно, попадают десктоп файлы при установке софта пакетным менеджером.
  • $XDG_CONFIG_HOME/autostart/ ($HOME/.config/autostart/ по умолчанию) — Пользовательская директория, имеющая больший приоритет, нежели общесистемная, то есть если в пользовательской лежит десктоп файл с таким же именем, что и в общесистемной, будет использован именно пользовательский файл.

Если в этих переменных семейства XDG directories не указано иное, или эти переменные отсутствуют (так происходит в большинстве классических дистрибутивов, привет NixOS!), будут использованы значения по умолчанию.

Итак, с директориями определились. Файлы в них можно:


  • Симлинкнуть из стандартных путей: $XDG_DATA_DIRS/applications/ (/usr/share/applications/ по умолчанию) или из пользовательского $XDG_DATA_HOME/applications/ (~/.local/share/applications по умолчанию), куда, кстати, любят класть свои файлы Steam, Itch.io или Wine.
  • Можно создать самому, написав десктоп файлы руками.
  • Можно нажать галочку «Запускать при старте системы», в каком-нибудь софте, например, в телеграм клиенте и тогда уже софт сам создаст в $XDG_CONFIG_HOME/autostart/ свой файл.

Всё хорошо. Одно плохо. Это не работает, как минимум, в Leftwm, Spectrwm, xmonad, bspwm, dwm (без патчей точно) и, разумеется, в любимом i3wm. Просто потому, что у них отсутствует session manager. И вот тут мы переходим к самому интересному. Встречайте! systemd!


Systemd как спасательный круг тайловых (и не очень) оконных менеджеров

Эта глава будет самой объёмной. Тут мы разберёмся кто и как может помочь разобрать залежи desktop файлов, кто, как и когда их запустит, и при чём тут вообще systemd. Поехали!


Developers, developers, developers! Генераторы, генераторы, генераторы!

Systemd, как известно, это не только система инициализации, логгирования событий, но и набор готовых дополнительных утилит, готовых сервисов с их юнитами, система управления сетью, and more… Среди прочего systemd может выступать в качестве системного менеджера для пользовательских сервисов — юнитов, работающих в пространстве пользователя. То есть после логина пользователя в систему запускается ещё один экземпляр /usr/lib/systemd только уже от пользователя и позволяет запускать юниты в пространстве пользователя, с наследованием его окружения и правами.

Среди других интересных и полезных вещей в systemd есть такая штука, как генераторы. Маленькие утилиты запускаемые на раннем этапе загрузки системы или сразу после логина пользователя и выполняющие динамическую генерацию юнитов и/или их конфигов. Например, есть генератор, который читает /etc/fstab и на его основе генерирует *.mount юниты. Или генератор, который вычитывает файлы *.conf из /etc/environment.d/ и $HOME/.config/environment.d/ и на их основе собирает переменные которые пользователь видит набирая команду env и которые наследуются всеми пользовательскими юнитами. Среди прочего есть и генератор, который пробегает по $XDG_CONFIG_DIRS/autostart и $XDG_CONFIG_HOME/autostart, вычитывает *.desktop файлы, генерирует пользовательские

*.service юниты и кладёт их в /run/user/<UID>/systemd/generator.late.

Всё хорошо и замечательно, но есть одно но. Если есть сервисы, их должен кто-то вовремя запустить. То есть запустить ровно тогда, когда будет запущена графическая оболочка… Если посмотреть, произвольный такой юнит, мы увидим там упоминание target-а graphical-session.target (Юнит на основе десктоп файла апплета управления Bluetooth cat /run/user/1000/systemd/generator.late/[email protected]):

# Automatically generated by systemd-xdg-autostart-generator
[Unit]
Documentation=man:systemd-xdg-autostart-generator(8)
SourcePath=/etc/xdg/autostart/blueman.desktop
PartOf=graphical-session.target
Description=Blueman Applet
After=graphical-session.target
[Service]
Type=exec
ExecStart=:/usr/bin/blueman-applet
Restart=no
TimeoutSec=5s
Slice=app.slice

Хорошо, но что это за graphical-session.target? В выводе systemctl --user --type=target, если выполнить команду из-под i3wm никакого такого таргета не наблюдается. А вот если запустить из-под, например, Gnome, то вполне:


Многабукв и ничего интересного 😉

  UNIT                                                LOAD   ACTIVE SUB     DESCRIPTION                                                                       
  basic. target                                        loaded active active  Basic System                                                                      
  default.target                                      loaded active active  Main User Target                                                                  
  gnome-session-initialized.target                    loaded active active  GNOME Session is initialized                                                      
  gnome-session-manager.target                        loaded active active  GNOME Session Manager is ready                                                    
  gnome-session-pre.target                            loaded active active  Tasks to be run before GNOME Session starts                                       
  gnome-session-x11-services.target                   loaded active active  GNOME session X11 services                                                        
  gnome-session-x11.target                            loaded active active  GNOME X11 Session                                                                 
  gnome-session-x11@zorin.
target loaded active active GNOME X11 Session (session: gnome) gnome-session.target loaded active active GNOME Session [email protected] loaded active active GNOME Session (session: gnome) graphical-session-pre.target loaded active active Session services which should run early before the graphical session is brought up graphical-session.target loaded active active Current graphical user session org.gnome.SettingsDaemon.A11ySettings.target loaded active active GNOME accessibility target org.gnome.SettingsDaemon.Color.target loaded active active GNOME color management target org.
gnome.SettingsDaemon.Datetime.target loaded active active GNOME date & time target org.gnome.SettingsDaemon.Housekeeping.target loaded active active GNOME maintenance of expirable data target org.gnome.SettingsDaemon.Keyboard.target loaded active active GNOME keyboard configuration target org.gnome.SettingsDaemon.MediaKeys.target loaded active active GNOME keyboard shortcuts target org.gnome.SettingsDaemon.Power.target loaded active active GNOME power management target org.gnome.SettingsDaemon.PrintNotifications.target loaded active active GNOME printer notifications target org.gnome.SettingsDaemon.Rfkill.target loaded active active GNOME RFKill support target org.
gnome.SettingsDaemon.ScreensaverProxy.target loaded active active GNOME FreeDesktop screensaver target org.gnome.SettingsDaemon.Sharing.target loaded active active GNOME file sharing target org.gnome.SettingsDaemon.Smartcard.target loaded active active GNOME smartcard target org.gnome.SettingsDaemon.Sound.target loaded active active GNOME sound sample caching target org.gnome.SettingsDaemon.Wacom.target loaded active active GNOME Wacom tablet support target org.gnome.SettingsDaemon.XSettings.target loaded active active GNOME XSettings target org.gnome.Shell.target loaded active active GNOME Shell paths.
target loaded active active Paths sockets.target loaded active active Sockets timers.target loaded active active Timers LOAD = Reflects whether the unit definition was properly loaded. ACTIVE = The high-level unit activation state, i.e. generalization of SUB. SUB = The low-level unit activation state, values depend on unit type. 31 loaded units listed. Pass --all to see loaded but inactive units, too. To show all installed unit files use 'systemctl list-unit-files'.

И что же со всем этим делать и как быть? Как получить заветный target?


▍ Графическая оболочка тоже сервис. Подсматриваем в Gnome

Если в Gnome запустить systemctl --user --type=service можно заметить интересный сервис:

  UNIT                                                LOAD   ACTIVE SUB     DESCRIPTION
  at-spi-dbus-bus. service                             loaded active running Accessibility services bus
  dbus.service                                        loaded active running D-Bus User Message Bus
...
  gnome-shell-x11.service                             loaded active running GNOME Shell on X11
...

Становится всё интереснее. Значит Gnome запускается как systemd сервис (gnome-shell-x11.service). Ну а уж из сервиса можно реализовывать любые зависимости. В принципе ожидаемо. Но как реализовывать такое для произвольной графической оболочки, которая не заточена под такие тонкие извращения? Надеемся на то не должно быть сложно… Перво-наперво смотрим в юнит (systemctl cat --user gnome-shell-x11.service) и понимаем, что ничего не понимаем и что мы немножко попали…

# /usr/lib/systemd/user/gnome-shell-x11.service
[Unit]
Description=GNOME Shell on X11
# On X11, try to show the GNOME Session Failed screen
OnFailure=gnome-shell-disable-extensions.service gnome-session-failed. target
OnFailureJobMode=replace
CollectMode=inactive-or-failed
RefuseManualStart=on
RefuseManualStop=on
After=gnome-session-manager.target
Requisite=gnome-session-initialized.target
PartOf=gnome-session-initialized.target
Before=gnome-session-initialized.target
# The units already conflict because they use the same BusName
#Conflicts=gnome-shell-wayland.service
# Limit startup frequency more than the default
StartLimitIntervalSec=15s
StartLimitBurst=3
[Service]
Type=notify
ExecStart=/usr/bin/gnome-shell
# Exit code 1 means we are probably *not* dealing with an extension failure
SuccessExitStatus=1
# On X11 we want to restart on-success (Alt+F2 + r) and on-failure.
Restart=always

Ладно, чёрт с ним, идём смотреть в *.desktop файл xsessions(cat /usr/share/xsessions/gnome.desktop)…

[Desktop Entry]
Name=GNOME
Comment=This session logs you into GNOME
Exec=env GNOME_SHELL_SESSION_MODE=gnome /usr/bin/gnome-session --systemd --session=gnome
TryExec=/usr/bin/gnome-shell
Type=Application
DesktopNames=GNOME
X-GDM-SessionRegisters=true
X-Ubuntu-Gettext-Domain=gnome-session-3. 0

… и понимаем, что попали несколько серьёзнее чем хотелось бы и что гном, в данном случае, нам мало чем поможет. Он изначально заточен под работу с systemd. Идём в эти наши интернеты.


▍ Выходим на финишную прямую. Пишем враппер, юнит и наконец удачно стартуем

Не буду затягивать и утомлять читателя подробностями того, как и где приходилось выуживать информацию по крупицам. Это были и маны и ArchWiki и чёрт его знает что ещё. Лучше сразу приведу готовые, в меру откомментированные файлы.

Итак, копируем дефолтный /usr/share/xsessions/i3.desktop в /usr/share/xsessions/i3-systemd.desktop и немного модифицируем.

[Desktop Entry]
### Было: ###
# Name=i3
### Стало: ###
Name=i3 via systemd
Comment=improved dynamic tiling window manager
### Было: ###
# Exec=i3
# TryExec=i3
### Стало: ###
Exec=i3-service
TryExec=i3-service
Type=Application
X-LightDM-DesktopName=i3
DesktopNames=i3
Keywords=tiling;wm;windowmanager;window;manager;

Теперь нам нужно написать враппер i3-service который будет подготавливать окружение и запускать i3wm в качестве сервиса. Ну и, разумеется, сам i3.service файл тоже должен быть написан. Итак враппер /usr/local/bin/i3-service:

#!/usr/bin/env sh
# Импортируем и загружаем в d-bus сессию переменные из логин менеджера.
/etc/X11/xinit/xinitrc.d/50-systemd-user.sh
systemctl --user import-environment XDG_SEAT XDG_VTNR XDG_SESSION_ID XDG_SESSION_TYPE XDG_SESSION_CLASS
if command -v dbus-update-activation-environment >/dev/null 2>&1; then
    dbus-update-activation-environment XDG_SEAT XDG_VTNR XDG_SESSION_ID XDG_SESSION_TYPE XDG_SESSION_CLASS
fi
# Загружаем иксовые ресурсы.
userresources=$HOME/.Xresources
usermodmap=$HOME/.Xmodmap
sysresources=/etc/X11/xinit/.Xresources
sysmodmap=/etc/X11/xinit/.Xmodmap
if [ -f $sysresources ]; then
    xrdb -merge $sysresources
fi
if [ -f $sysmodmap ]; then
    xmodmap $sysmodmap
fi
if [ -f "$userresources" ]; then
    xrdb -merge "$userresources"
fi
if [ -f "$usermodmap" ]; then
    xmodmap "$usermodmap"
fi
# Запускаем xinitrc* скрипты. 
if [ -d /etc/X11/xinit/xinitrc.d ] ; then
    for f in /etc/X11/xinit/xinitrc.d/?*.sh ; do
        [ -x "$f" ] && . "$f"
    done
    unset f
fi
# И собственно запускаем сервис.
exec systemctl --wait --user start i3.service

Ну и наконец вишенка на нашем торте, сам /etc/systemd/user/i3.service:

[Unit]
Description=i3wm tiling window manager for X
Documentation=man:i3(5)
Wants=graphical-session-pre.target
After=graphical-session-pre.target
# Самое главное, биндимся к таргету графической сессии..
BindsTo=graphical-session.target
PartOf=graphical-session.target
# ... и не забываем включить таргет, ради которого всё затевалось.
Before=xdg-desktop-autostart.target
Wants=xdg-desktop-autostart.target
[Service]
Type=simple
# Запускаем i3 через d-bus launcher. Мы же хотим, чтоб у нас работал d-bus?
ExecStart=/usr/bin/dbus-launch --sh-syntax --exit-with-session i3 --shmlog-size 0
Restart=on-failure
RestartSec=5
TimeoutStopSec=10

  • Записываемся.
  • Для проверки добавляем в автозагрузку, например, тот же клиент телеграма.
  • Идём на перезагрузку и в дисплейном менеджере при старте системы, выбираем пункт «i3 via systemd»

Что в итоге?


  • Работает автозагрузка, прямо как в каком-нить гноме.
  • Бонусом получили graphical-session.target, к которому можно биндить сервисы, зависящие от запущенной графической оболочки. Например, до этого у меня падал, при загрузке юнит clipboard manager-а, в результате приходилось костылять таймаут… Теперь не падает.
  • Можно выкинуть из конфига i3 всё, что запускается при старте (Директива exec --no-startup-id и это вот всё) и упаковать в отдельные аккуратные пользовательские *.service и по-человечески рулить ими в процессе работы. Например, отключать и включать lockscreen простым systemctl --user start/stop
  • Для автозагружаемых юнитов, сгенерённых из *.desktop файлов, в самих этих файлах их можно отключать, добавив строчку Hidden=true

Ну и вообще, приятно быть первооткрывателем. Ибо в процессе гугления и чтения манов, готового рецепта обнаружено не было. Так что любители wm, не относящиеся к systemd хейтерам. Пробуйте. За месяц использования был замечен ровно один косяк. Не работает gvgs-* функционал в pcman-fm, если его запустить хоткеем из i3 Но если запустить из rofi, волшебным образом всё начинает работать. Возможно я забыл импортировать какую-то переменную в d-bus Ну и, чтоб не копипастить, ссылка на гитхаб.


AutoRun Application

  • Overview
  • Creating AutoRun application
  • Specifying basic AutoRun options
    • [Main] section
    • [Language] section
    • [Element] section
  • Adding languages
  • Adding sublists
  • Starting AutoRun automatically
  • SetupV8 application (predefined installation settings)
    • [Platform] section
    • [CFG] section
    • [Language] section

Download AutoRun templates

Overview

If your 1C:Enterprise applied solutions are delivered on a CD or DVD media, you might want to create the AutoRun application. The application is started automatically when you mount the CD or DVD. It offers end users to install both the platform and the applied solutions.

Both the settings and the interface of the AutoRun application are simple. The AutoRun application displays a dialog box with the following elements:

  1. Title
  2. Background
  3. List of available actions with their descriptions
  4. Exit button

All of these elements are customizable. The list of available actions can include installing applied solutions, viewing documentation, and so on.

You can add the following optional features:

  1. Localization and language selection
  2. Sublists to the main menu, which form a multilevel menu
  3. Predefined installation settings for the 1C:Enterprise platform and for the applied solutions (available only for Windows)

The AutoRun application is available for Windows (autorun. exe) and Linux (autorun) operating systems. The Linux application can run on both 32-bit and 64-bit operating systems.

Creating AutoRun application

You can create the AutoRun application using a free template.

To create the AutoRun application:

  1. Download the AutoRun template.
    It includes the following files and directories:

    platform
    solution
    autorun
    autorun.exe
    autorun.ico
    autorun.inf
    autorun.lst 
    autorun_en.bmp 
    autorun_ru.bmp
    autorunfull.lst
    gdiplus.dll
    guidelines.htm
    SetupV8.cfg
    SetupV8.exe
    setupv8.sh

  2. Edit the file autorun.lst as described in section Specifying AutoRun options.
  3. Edit the file SetupV8.cfg as described in section SetupV8 application (predefined installation settings) (on Windows), or replace the file setupv8.sh with a shell script that installs the platform and the applied solution (on Linux).
  4. Run autorun.exe (on Windows) or autorun (on Linux) to verify the result; debug it if necessary.
  5. Record the AutoRun files to the root directory of your CD or DVD.

The file gdiplus.dll is only required for pre-Windows Vista operating systems.

The directories platform and solution are intended for storing the installation files for the 1C:Enterprise platform and for the applied solution.

Specifying basic AutoRun options

The AutoRun dialog box settings are stored in the file autorun. lst. Its format is similar to that of .ini files, and it is UTF-8 encoded.

This file contains the following sections that you can edit:

[Main] section

This mandatory section describes global dialog box elements.

  • Caption. The dialog box title.
  • Picture. The path to the background image in .bmp format, relative to the directory where autorun.lst is located. The dialog box is auto-sized according to the image size.
  • WarningMsg. The text for the UAC warning. It might be displayed on Windows Vista or later operating systems when you start the AutoRun application.
  • ExitText. The exit button caption.
Example:

[Main]
Caption = 1C:Enterprise 8.3. Training Version
Picture = Picture\autorun.bmp
Exit = Exit

[Language] section

This optional section describes languages available in the AutoRun dialog box. Create a separate section for each language.

  • Locale. The language ID (a string). You will use this ID to mark interface texts written in this language.
  • Name. The language name, as it appears in the list of available languages.

If you specify multiple [Language] sections, the AutoRun dialog box will include a language selection drop-down list.

Example:

[Language]
Name=English
Locale=en

[Language]
Name=Russian
Locale=ru

To learn how to add interface texts in each language, see Adding languages section.

[Element] section

This mandatory section describes the list of actions available in AutoRun, with their descriptions.

  • Name. The action name.
  • Description. The action description.
  • Command. The path to the file that is opened when the user clicks this menu item. For example, you can specify the .exe file that starts the installation, or the .htm file that contains instructions. When the user clicks the command, AutoRun looks for the file using the following algorithm:
    • Add the current disk name to the path.
    • Add the current disk name with a path to autorun.lst directory to the path.
    • Use the path «as is».
  • CommandWindows. The path to the file that is opened when the user clicks this menu item on Windows, relative to the directory where autorun.lst is located.
  • CommandLinux. The path to the file that is opened when the user clicks this menu item on Linux, relative to the directory where autorun.lst is located. 
  • RunAsRoot. The flag that shows whether the file is run as root. If running the file requires superuser rights, set the parameter to 1, otherwise set it to 0. The default value is 0.
  • Marker. The icon to the left of the list entry. It can have one of the following values: Primary (blue icon) or Secondary (yellow icon).

If the Command parameter is not specified and a single operating system-specific command parameter is specified (either CommandWindows or CommandLinux), the element is only available on the specified operating system.

If the Command parameter is specified and no operating system-specific command parameters are specified, the element is available on all operating systems.

If the Command parameter is specified and one or both operating system-specific command parameters are specified (CommandWindows and/or CommandLinux), the element is available on all operating systems and the path to the file is taken from the operating system-specific command parameter (or from the Command parameter, if the operating system-specific parameter is not specified).

Example:

[Element]
Name = Installation instructions
Description = Click here to view installation instructions.
CommandWindows = readme.htm

CommandLinux = xdg-open readme.htm
Marker = Primary

[Element]
Name = Install application
Description = Click here to install the application.
CommandWindows = SetupV8.exe @SetupV8.cfg
CommandLinux = InstallationScript.sh
RunAsRoot = 1
Marker = Primary

The first element opens the file readme.htm. The second element runs the platform installer on Windows, and runs the installation script from the file InstallationScript.sh on Linux (requires root rights).

Adding languages

You can add language selection and then specify translated versions for almost all items in autorun.lst. This includes translation of all texts and specifying different background pictures for different languages.

Each translated item is represented as a separate line in autorun.lst. Its syntax is similar to that of the original item, with the addition of the locale name (except the Locale, Command, CommandWindows, CommandLinux, RunAsRoot, and Marker items, which are locale-independent).

Example:

[Main]
Caption = 1C:Enterprise 8.3. Training Version
Caption_ru = 1С:Предприятие 8.3. Учебная версия
Picture = Pictures/autorun_en.bmp
Picture_ru = Pictures/autorun_ru.bmp
ExitText = Exit
ExitText_ru = Выход

[Language]
Name=English
Name_ru=Английский
Locale=en

[Language]
Name=Russian
Name_ru=Русский
Locale=ru

[Element]
Name = Automatic installation (recommended)
Name_ru = Автоматическая установка (рекомендуется)
Description = This is the recommended installation type.
Description_ru = Это рекомендованный режим установки
Command = install.bat
Marker = Primary

The following languages are available:

  • Azerbaijani (az)
  • Bulgarian (bg)
  • Chinese (zh)
  • English (en)
  • French (fr)
  • Georgian (ka)
  • German (de)
  • Latvian (lv)
  • Lithuanian (lt)
  • Kazakh (kk)
  • Polish (pl)
  • Romanian (ro)
  • Russian (ru)
  • Ukrainian (uk)
  • Vietnamese (vi)

Any item that does not have a locale suffix is treated as default text, which is displayed when translated text is missing. In the example above English texts are treated as default texts.

The default language is determined as follows:

  • If the language matching the locale is defined in autorun. lst, it is the default language.
  • If the language matching the locale is not defined in autorun.lst but English is defined, English is the default language.

We recommend that you always define the English language in autorun.lst.

Adding sublists

You can create multilevel menus in the AutoRun dialog box. Menu items that open menu sublevels are represented as elements in the autorun.lst file.

Example:

[Element]
Name = More options…
Description = Click this item to open a submenu.
Marker = Primary
Command = autorunfull.lst

In this example the file autorunfull.lst contains settings for another AutoRun dialog box with its own set of elements.

The depth of nesting in the AutoRun menu is not limited. In this example, for returning to the top menu level, you have to create an element in the autorunfull.lst file that points to the autorun.lst file (which describes the top menu level).

Example:

[Element]
Name = Back…
Description = Return to the previous menu.
Marker = Secondary
Command = autorun.lst

Starting AutoRun automatically

On Windows, to have AutoRun started automatically when you mount the CD or DVD, the root directory of the disc must contain the autorun.inf file. For a detailed description of the file format, see http://msdn.microsoft.com/en-us/library/windows/desktop/cc144202.>

The following example of the autorun.inf file describes a scenario where the AutoRun file name is autorun.exe and the file is located in the root directory of the disc.

Example:

[autorun]
OPEN=autorun. exe
ICON=autorun.ico

On Linux, to have AutoRun started automatically when you mount the CD or DVD, the root directory of the disc must contain the executable file autorun.sh, a shell script that starts the autorun program.

The following example of the autorun.sh file describes a scenario where the AutoRun file name is autorun and the file is located in the root directory of the disc.

Example:

#!/bin/bash
./autorun 

SetupV8 application (predefined installation settings)

On Windows, you can use the SetupV8.exe application, which is included in the AutoRun template, to perform any of the following actions:

  • Install the 1C:Enterprise 8 platform
  • Install the applied solution Infobase template
  • Create an infobase from the template
  • Run the 1C:Enterprise 8 platform

The setup configuration is stored in a configuration file. In this example, it is the file SetupV8.cfg. To run the setup with the configuration settings described in this file, use the following command:

SetupV8.exe @<path to SetupV8.cfg relative to SetupV8.exe directory>

If the path is not specified, AutoRun looks for SetupV8.cfg file in the directory where SetupV8.exe is located.

The format of the configuration file is similar to that of .ini files, and it is UTF-8 encoded. The number sign # comments out the line, any text following it is ignored.

This file contains the following sections that you can edit:

[Platform] section

This mandatory section describes the installation settings for the 1C:Enterprise platform package.

  • MsgBeforePlatform. If this line is present, a message is displayed before platform installation. The message text is specified in <Language> sections.
  • Location. The path to the installation file, relative to SetupV8.exe directory.
  • CmdLine. Command-line parameters for the installer:
    • DEFLANGUAGE. The default platform language.
    • REINSTALL. Describes the list of features that are to be reinstalled. For details, see http://msdn.microsoft.com/en-us/library/aa371175(v=vs.85).aspx.
    • REINSTALLMODE. Describes the type of reinstall to perform. For details, see http://msdn.microsoft.com/en-us/library/aa371182(v=vs.85).aspx.
    • HASPInstall. Defines whether HASP key installation is used. The HASP key installation can only be performed if you run the installation application with the full interface (UI = 5).
    • Any of the parameters available in the InstallComponents entry of the 1CEStart.cfg file: DESIGNERALLCLIENTS, THINCLIENT, THINCLIENTFILE, SERVER, WEBSERVEREXT, CONFREPOSSERVER, and SERVERCLIENT.
  • UI. Defines the verbosity level of the installation application GUI:
    • 3. Progress bar only.
    • 5. Regular (full) interface of the installation application.
  • PackageName. The installation file name (with the .msi extension).
  • MsiVersion. The minimum version of the Windows Installer component required to install the 1C:Enterprise platform.
  • MsiW. The path to the executable file of the Windows Installer component that will be used if the local Windows Installer version does not meet the requirement specified in MsiVersion, relative to the directory where SetupV8.cfg is located.
  • MsgAfterPlatform. If this line is present, a message is displayed after platform installation. The message text is specified in the <Language> sections.
Example:

[Platform]
MsgBeforePlatform
Location = 1CV8
CmdLine = REINSTALLMODE=vomus REINSTALL=ALL HASPInstall=no DEFLANGUAGE=EN
UI = 5
PackageName = 1CEnterprise 8. msi
MsiVersion = 2.0.2600.2
MsiW = WindowsInstaller-KB893803-x86.exe
MsgAfterPlatform

[CFG] section

This mandatory section describes installation settings for the 1C:Enterprise platform package.

  • Location. The path to the distribution package, relative to the directory where SetupV8.exe is located.
  • CfgDestination. The applied solution template installation directory, relative to the directory where SetupV8.exe is located. It must match the applied solution template installation foder that you specified during the creation of the application distribution kit. 
  • Version. The applied solution version.
  • Config1. Shows whether the applied solution Infobase is created after template installation.
    • 0. Do not create the Infobase.
    • 1. Create the Infobase.
  • Config2. Shows whether the applied solution demo Infobase is created after template installation.
    • 0. Do not create the Infobase.
    • 1. Create the Infobase.
  • MsgBeforeCFG. If this line is present, a message is displayed before the applied solution installation. The message text is specified in <Language> sections.
  • MsgAfterCFG. If this line is present, a message is displayed after the applied solution installation. The message text is specified in <Language> sections.
  • CFGLoad. If this line is present, a message is displayed while the applied solution template is being loaded. The message text is specified in <Language> sections.
  • CFGError. If this line is present, a message is displayed if an error occurs while loading the applied solution template. The message text is specified in <Language> sections.
  • MsgBeforeIB. If this line is present, a message is displayed before Infobase creation. The message text is specified in <Language> sections.
  • IBCreate. If this line is present, a message is displayed during Infobase creation. The message text is specified in <Language> sections.
  • MsgAfterIB. If this line is present, a message is displayed after Infobase creation. The message text is specified in <Language> sections.
  • AppLaunch. If this line is present, a message is displayed before the applied solution is started. The message text is specified in <Language> sections.
Example:

[CFG]
Location=configs\smallbusiness
CfgDestination=1C\smallbusiness
version=1.0.0.0
Config1=1
Config2=1
MsgBeforeCFG
MsgAfterCFG
CFGLoad
CFGError
MsgBeforeIB
IBCreate
MsgAfterIB
AppLaunch

[<Language>] section

This mandatory section contains the localized text strings. Create multiple sections of this type, one for each installer language.

Use the language names from the following list as section names: Azerbaijani, Bulgarian, Chinese, English, French, Georgian, German, Kazakh, Latvian, Lithuanian, Polish, Romanian, Russian, Turkish, Ukrainian, and Vietnamese.

  • Title. The setup window title.
  • IBCreate. The message displayed during Infobase creation. The variable %1 represents the Infobase name.
  • AppLaunch. The message displayed before the applied solution is started.
  • CFGLoad. The message displayed while the applied solution template is being loaded.
  • CFGError. The message displayed if an error occurs while loading the applied solution template.
  • MsgBeforePlatform. The message displayed before platform installation.
  • MsgAfterPlatform. The message displayed after platform installation.
  • MsgBeforeCFG. The message displayed before the applied solution installation.
  • MsgAfterCFG. The message displayed after the applied solution installation.
  • MsgBeforeIB. The message displayed before Infobase creation.
  • MsgAfterIB. The message displayed after Infobase creation.
Example:

[English]
Title = Setup
IBCreate = Creating the %1 infobase. This process can take a few minutes.
AppLaunch = Starting 1C:Enterprise…
CFGLoad = Preparing to install the applied solution…
CFGError = Error writing to the templates directory. Probably you have no rights to write there.
MsgBeforePlatform = Installing 1C:Enterprise…
MsgAfterPlatform = 1C:Enterprise installation complete.
MsgBeforeCFG = Installing the applied solution…
MsgAfterCFG = Applied solution installation complete.
MsgBeforeIB = Creating the infobase…
MsgAfterIB= The installation is complete. Click OK to start 1C:Enterprise.

Next page: System requirements

Get more details: Downloads

linux — Как запустить сценарий оболочки при запуске

спросил

Изменено 4 месяца назад

Просмотрено 1,3 млн раз

В экземпляре Amazon S3 Linux у меня есть два сценария с именами start_my_app и stop_my_app , которые запускаются и останавливаются навсегда (что, в свою очередь, запускает мое приложение Node.js). Я использую эти сценарии для ручного запуска и остановки моего приложения Node.js. Все идет нормально.

Моя проблема: я также хочу настроить его таким образом, чтобы start_my_app запускался при каждой загрузке системы. Я знаю, что мне нужно добавить файл внутри init.d , и я знаю, как связать его с нужным каталогом в rc.d , но я не могу понять, что на самом деле нужно сделать внутри файла, который я место в инит.д . Я думаю, что это должна быть всего одна строка, например, start_my_app , но у меня это не сработало.

  • Linux
  • node.js
  • init.d
  • навсегда

3

Сначала создайте сценарий запуска @ /home/user/startup.sh и сделайте его исполняемым

 chmod +x /home/user/startup.sh
 

Затем установите для него crontab:

 $ crontab -e
@reboot /home/user/startup.sh
 

Теперь ваш скрипт startup.sh будет запускаться при каждом запуске.

14

Файл, который вы поместили в /etc/init.d/ , должен быть установлен как исполняемый с помощью:

 chmod +x /etc/init. d/start_my_app
 

Как указал @meetamit, если он по-прежнему не запускается, вам может потребоваться создать символическую ссылку на файл в /etc/rc.d/

 ln -s /etc/init.d/start_my_app/ и т.д./rc.d/
 

Обратите внимание, что в последних версиях Debian это не будет работать, так как ваш сценарий должен быть совместим с LSB (предусмотрите как минимум следующие действия: запуск, остановка, перезапуск, принудительная перезагрузка и состояние): https://wiki.debian.org/LSBInitScripts

Обратите внимание: вы всегда должны использовать абсолютный путь к файлам в своих скриптах вместо относительного, это может решить непредвиденные проблемы:

 /var/myscripts/start_my_app
 

Наконец, убедитесь, что вы включили шебанг поверх файла:

 #!/bin/sh
 

13

Простой подход — добавить строку в /etc/rc.local :

 /PATH/TO/MY_APP &
 

или если вы хотите запустить команду от имени специального пользователя:

 su - USER_FOOBAR -c /PATH/TO/MY_APP &
 

(амперсанд в конце запускает процесс и позволяет продолжить выполнение rc. local)

Если вам нужен полный сценарий инициализации, в дистрибутиве Debian есть файл шаблона, поэтому:

 cp /etc/init.d/skeleton/ и т.д./init.d/ваше_приложение
 

и немного его адаптируем.

6

Так я делаю в системах Red Hat Linux.

Поместите свой сценарий в /etc/init.d , принадлежащий пользователю root и исполняемый файл. В верхней части скрипта можно указать директиву для chkconfig . Например, следующий сценарий используется для запуска приложения Java в качестве пользовательского оракула.

Имя сценария /etc/init.d/apex

 #!/bin/bash
# chkconfig: 345 99 10
# Описание: автозапуск apex listener
#
случай "$1" в
 'Начало')
   su - oracle -c "cd /opt/apex; java -jar apex.war > logs/apex.log 2>logs/apex_error.log &";;
 'остановка')
   echo "поставьте что-нибудь, чтобы остановить или убить процесс здесь";;
эсак
 

Это говорит о том, что сценарий должен выполняться на уровнях 3, 4 и 5, а приоритет для запуска/остановки равен 99 и 10.

Затем, как пользователь root , вы можете использовать скрипт при запуске:

 chkconfig --list apex
chkconfig --добавить вершину
 

И вы можете использовать сервис запуска/остановки вершины .

2

Введите cron , используя sudo :

sudo crontab -e

Добавить команду для запуска при запуске, в данном случае сценарий:

@reboot sh /home/user/test.sh

Сохранить:

5 Нажмите ESC затем :x, чтобы сохранить и выйти, или нажмите ESC, затем ZZ (это Shift+zz)

Test Test Test :

  1. Запустите тестовый скрипт без cron, чтобы убедиться, что он действительно работает.

  2. Убедитесь, что вы сохранили свою команду в cron, используйте судокронтаб -е

  3. Перезагрузите сервер, чтобы убедиться, что все работает sudo @reboot

4

Просто добавьте строку в ваш crontab. .

Убедитесь, что файл является исполняемым:

 chmod +x /path_to_you_file/your_file
 

Для редактирования файла crontab:

 crontab -e
 

Строка, которую нужно добавить:

 @reboot /path_to_you_file/your_file
 

Это просто!

2

Другим вариантом является наличие команды @reboot в вашем crontab.

Не каждая версия cron поддерживает это, но если ваш экземпляр основан на Amazon Linux AMI, он будет работать.

Отредактируйте файл rc.local с помощью редактора nano или gedit и добавьте в него свои сценарии. Путь к файлу может быть /etc/rc.local или /etc/rc.d/rc.local .

 судо нано /etc/rc.local
 

Это редактирование:

 #!/bin/sh
/путь-к-вашему-сценарию/имя-вашего-сценария.sh
 

после завершения нажмите ctrl+o для обновления, нажмите Введите затем ctrl+x .

Сделать файл исполняемым.

 судо chmod 755 /etc/rc.local
 

Затем инициируйте службу rc-local для запуска сценария во время загрузки.

 sudo systemctl запустить rc-local
 

0

Вы можете сделать это:

 chmod +x PATH_TO_YOUR_SCRIPT/start_my_app
 

затем используйте эту команду

 update-rc.d start_my_app по умолчанию 100
 

См. эту страницу на Cyberciti.

1

Много ответов о запуске чего-то при загрузке, но часто вы хотите запустить это немного позже, потому что ваш скрипт зависит, например, от. сети. Используйте на , чтобы просто добавить эту задержку, например:

 сейчас + 1 мин -f /path/yourscript
 

Вы можете добавить это в /etc/rc.local, а также в cron , например:

 # crontab -e
@reboot сейчас + 1 мин -f /path/yourscript
 

Разве не забавно совмещать cron и at? Информация находится на справочной странице man at .

Что касается комментариев о том, что @reboot может не поддерживаться широко, просто попробуйте. Я обнаружил, что /etc/rc.local устарел в дистрибутивах, поддерживающих systemd, таких как ubuntu и raspbian.

1

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

просто перейдите к нужному сценарию и готово. (сделать скрипт исполняемым)

2

Это простое решение сработало для меня на экземпляре Amazon Linux под управлением CentOS. Отредактируйте свой /etc/rc.d/rc.local и поместите туда команду. В этом файле упоминается, что он будет выполнен после всех остальных сценариев инициализации. Так что будьте осторожны в этом плане. Вот как файл выглядит для меня в настоящее время. Последняя строка — это имя моего скрипта.

0

Создайте свой собственный исполняемый файл /init

Это не то, что вам нужно, но это весело!

Просто выберите произвольный исполняемый файл, даже сценарий оболочки, и загрузите ядро ​​с параметром командной строки:

 init=/путь/к/myinit
 

В конце загрузки ядро ​​Linux запускает первый исполняемый файл пользовательского пространства по заданному пути.

Несколько проектов предоставляют популярные исполняемые файлы init , используемые основными дистрибутивами, например. systemd, и в большинстве дистрибутивов init создаст множество процессов, используемых при нормальной работе системы.

Но мы можем взломать /init , чтобы запустить наши собственные минимальные сценарии, чтобы лучше понять нашу систему.

Вот минимальная воспроизводимая установка: https://github.com/cirosantilli/linux-kernel-module-cheat/tree/f96d4d55c9caa7c0862991025e1291c48c33e3d9/README. md#custom-init

Я ссылался на этот блог, всегда хороший выбор

https://blog.xyzio.com/2016/06/14/setting-up-a-golang-website- to-autorun-on-ubuntu-using-systemd/

vim /lib/systemd/system/gosite.service

 Description=Простой веб-сайт
ConditionPathExists=/home/user/bin/gosite
[Обслуживание]
Перезапустить = всегда
Рестартсек=3
ExecStart=/home/user/bin/gosite
[Установить]
WantedBy=многопользовательская.цель
 
 systemctl включить gosite.service
 

несколько способов закончить это:

  1. crontab
  2. rc.local
  3. иници.д
  4. системад

1

Для Debian 9 см. https://askubuntu.com/questions/228304/how-do-i-run-a-script-at-start-up. Мне помогло. Краткая версия для Debian 9: добавить команды (как root) в /etc/rc.local

 /path_to_file/filename.sh || выход 1 # Добавлено мной
выход 0
 

Вероятно, /path_to_file/filename. sh должен быть исполняемым (я так думаю).

В Lubuntu мне пришлось столкнуться с противоположной ситуацией. Skype запускается после загрузки, и я нашел в ~/.config/autostart/ файл skypeforlinux.desktop . Содержимое файла выглядит следующим образом:

 [Desktop Entry]
Имя=Скайп для Linux
Комментарий=Skype Интернет-телефония
Exec=/usr/bin/skypeforlinux
Значок = скайпфорлинукс
Терминал=ложь
Тип = Приложение
StartupNotify=ложь
X-GNOME-Autostart-enabled=true
 

Мне помогло удаление этого файла.

Вот более простой способ!

Сначала: напишите сценарий оболочки и сохраните его в формате .sh вот пример

 #!/bin/bash
icoff='/home/akbar/keyboardONOFF/icon/Dt6hQ.png'
идентификатор = 13
fconfig=".клавиатура"
эхо "отключено" > $fconfig
xinput $id с плавающей запятой
notify-send -i $Icoff "Внутренняя клавиатура отключена";
 

этот скрипт отключит внутреннюю клавиатуру при запуске.

Второй: Откройте приложение «Настройки запуска приложения»

введите здесь описание изображения

введите здесь описание изображения

Третье: нажмите Добавить. четвертое: в разделе ИМЯ дайте имя. пятое: в разделе команд перейдите к вашему .sh . шестое: отредактируйте свой раздел команд следующим образом:

 bash <пробел> путь/к/файлу/<имя файла>.sh <пробел> --start
 

седьмой: нажмите кнопку Добавить. Вот и все! Законченный!

Теперь подтвердите, перезагрузив компьютер.

ура!

1

  • Добавьте свой скрипт в каталог /etc/init.d/
  • Обновите уровни запуска rc: $ update-rc.d myScript.sh по умолчанию NN , где NN — это порядок, в котором он должен выполняться. Например, 99 будет означать, что он будет запускаться после 98 и до 100.

0

Безболезненный, самый простой и универсальный метод просто выполнение с ~.bash_profile или ~.profile (если у вас нет файла bash_profile) .

Просто добавьте команду выполнения внизу этого файла, и она будет выполнена при запуске системы.

У меня это внизу пример; ~\Рабочий стол\sound_fixer.sh

1

Работа с микросервисами или оболочкой Python 3; используя Ubuntu Server 18.04 (Bionic Beaver), Ubuntu 19.10 (Eoan Ermine) или Ubuntu 18.10 (Cosmic Cuttlefish).0015 всегда тоже:

  1. Создание микросервиса с именем p пример «brain_microservice1.service» в моем случае:

     $ нано /lib/systemd/system/brain_microservice1.service
     
  2. Внутри этой новой службы, в которой вы находитесь:

     [Единица измерения]
    Описание=brain_microservice_1
    After=multi-user.target
    [Обслуживание]
    Тип=простой
    ExecStart=/usr/bin/python3.7/root/scriptsPython/RUN_SERVICES/microservices/microservice_1.py -k start -DFOREGROUND
    ExecStop=/usr/bin/python3.7/root/scriptsPython/RUN_SERVICES/microservices/microservice_1.py -k грациозно-стоп
    ExecReload=/usr/bin/python3.7 /root/scriptsPython/RUN_SERVICES/microservices/microservice_1. py -k изящный
    PrivateTmp=истина
    LimitNOFILE=бесконечность
    KillMode=смешанный
    Перезапуск = при сбое
    Рестартсек=5с
    [Установить]
    WantedBy=многопользовательская.цель
     
  3. Дайте разрешения:

     $ chmod -X /lib/systemd/system/brain_microservice*
    $ chmod -R 775 /lib/systemd/system/brain_microservice*
     
  4. Затем дайте разрешение на выполнение:

     $ системная перезагрузка демона
     
  5. Включите, это заставит всегда запускаться при запуске

     $ systemctl включить brain_microservice1.service
     
  6. Тогда вы можете проверить это;

    $ sudo перезагрузить сейчас

  7. Готово = УСПЕХ!!

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

Для некоторых людей, это будет работать:

Вы можете просто добавить следующую команду в System Preferences Startup Applications :

 bash /full/path/to/your/script. sh
 

3

linux — скрипт bash для автоматического запуска при загрузке, создания экрана, выполнения команды и отсоединения

спросил

Изменено 3 года, 1 месяц назад

Просмотрено 302 раза

Я использую Centos 7 и при загрузке хочу:

  • Сделать скрин
  • Выполнить команду: osrm-routed —algorithm=MLD ~/osrm-backend/profiles/australia-latest.osrm
  • Отсоединить от экрана (возможно, не нужно, пока я могу доступ к нему сам после его запуска в будущем)

Вот кое-что, о чем я подумал, хотя это неправильно и не будет работать

имя файла: mapstart.sh Содержимое файла:

 #!/bin/bash
/usr/bin/экран -dmS mapapi osrm-routed --algorithm=MLD ~/osrm-backend/profiles/australia-latest. osrm
 

С вашей помощью со скриптом. Я не уверен, что это лучший способ запустить это при загрузке с Centos 7.

Благодарим вас за помощь и вклад.

  • Linux
  • сервер
  • centos7

3

Для тех, кто хотел бы знать. Проблема была с OSRM и Centos. Я смог запустить его, используя полные пути всего и следующее в crontab -e

Чтобы получить полный путь к osrm-backend, я выполнил команду:

 который osrm-маршрутизируется
 

Он вернул результат:

 /usr/local/bin/osrm-routed
 

Это позволило мне добавить полный путь к команде, которую я пытался запустить из crontab -e, что необходимо. Оттуда он работал, запустив ниже в crontab -e

 @reboot /usr/bin/screen -dm -S pistartup /usr/local/bin/osrm-routed --algorithm=MLD ~/osrm-backend/profiles/australia -последний.osrm
 

разбивка всего вышеперечисленного:

запускает команду только при перезагрузке:

 @перезагрузка
 

полный путь к экранной команде:

 /usr/bin/screen
 

создать экран с именем pistartup и отсоединить:

 -dm -S pistartup
 

моя конкретная команда, которую я хотел запустить внутри экрана:

 /usr/local/bin/osrm-routed --algorithm=MLD ~/osrm-backend/profiles/australia-latest.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *