Автозапуск linux init d

How can I configure a service to run at startup

but it’s not configured to auto start when the PC reboots. How can I configure it to start automatically, even if no one is logged into the PC?

@user154721 What arguments did you give update-rc.d to make autostart work? I’ve tried various options but haven’t had any luck.

Auto-start programs are configured in autostart manifests or in *.service files in several locations, as well as in init.d or crontab . See: unix.stackexchange.com/a/525845/43233

5 Answers 5

sudo update-rc.d minidlna defaults 

This should add the service to the automatic startup system. But if you get:

System start/stop links for /etc/init.d/minidlna already exist. 
sudo update-rc.d minidlna enable 

P.S.: For further detail look at the man page for update-rc.d by typing the command man update-rc.d

thanks, but what if I get this output when running that command?: System start/stop links for /etc/init.d/minidlna already exist.

if minidlna doesnt write to any logfile you won’t find it any where. Does it maybe fail because there is no network connection when it is started? Try to look at the configuration if it is possible turn on debugging and/or logging to find out whats wrong.

I am also, got the same error update-rc.d: /etc/init.d/mongod: file does not exist . Then, sudo systemctl enable mongod.service worked for me.

Since Ubuntu 15.10 and newer (resp. Debian 8 «jessie» and newer), you have to use the following command to configure your service minidlna to run at startup:

sudo systemctl enable minidlna.service 

And to disable it again from starting at boot time:

sudo systemctl disable minidlna.service 

This works with all service names available on your system. To find out available service names, just list the filenames of the service files:

ls /lib/systemd/system/*.service ls /etc/systemd/system/*.service 

As for sudo, I recieve Unknown operation enable. If I discard sudo it will ask me which user I would like to choose. Pick your root user and you will be able to set the desired value.

@tanius I have followe the procedure of adding new services to /etc/systemd/system/*.service. I would like to know why no one suggested creating or editing these files as it seems to provide mode options (Restart, RestartSec, ExecStop, etc. )

@tiagoams Creating a service file was just not the question here, since the OP states that a service minidlna already exists but does not autostart. But thanks for the pointer to service files under /etc , I added that to the answer now.

update-rc.d service_name defaults 
update-rc.d -f service_name remove 

defaults => default run levels 2,3,4 and 5

update-rc.d tomcat7 defaults 

When I do this command, I get «System start/stop links for /etc/init.d/tomcat7 already exist». however, when I reboot, it does not start tomcat, I always have to do «service tomcat7 start».

Читайте также:  Контрольная сумма папки linux

in my case sudo update-rc.d myservice default always completes with no output and the service won’t start on boot-up or with sudo service myservice start which also completes silently. sudo /etc/init.d/myservice start works however

Sometimes you need to run a script on boot process, for example run an iptables config at boot process. So you don’t have to run the script manually every rebooting.

You can run your script on boot process in Ubuntu by adding it to /etc/init.d/rc.local file. Look the steps below.

    Open /etc/rc.local file with this command:

sh /home/ivan/iptables.sh echo 'Iptable Configured!' 

Comments of /etc/init.d/rc.local in Ubuntu 12.04 says «Short-Description: Run /etc/rc.local if it exist», so maybe adding the scripts to /etc/rc.local would be better idea?

Vadim, rc.local is just run at boot, nothing is achieved on shutdown. The process would most likely be killed by the OS on shutdown.

FYI: The difference between rc.local vs adding it to init, is that rc.local is executed at the end of the init startup sequence, rather than as part of it

In ubuntu version 18.04 TLS, I found that update-rc.d does not work fine if there is no specific comment block in the start script that looks like this:

### BEGIN INIT INFO # Provides: myprogram # Required-Start: $ local_fs $ remote_fs $ syslog $ network $ time # Required-Stop: $ local_fs $ remote_fs $ syslog $ network # Default-start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: myprogram some description ### END INIT INFO 

Источник

📑 Настройка автозапуска скриптов в Linux Ubuntu/Mint

Ubuntu

Здесь рассматриваются способы настройки автозапуска скриптов в Ubuntu/Mint только в консольном режиме.

Создание скрипта в init.d для запуска во время инициализации системы

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

$sudo chmod +x /etc/init.d/имя_скрипта

Теперь необходимо добавить его в автозагрузку:

$sudo update-rc.d имя_скрипта defaults

Скрипт запуститься во время инициализации системы.

Удалить из автозагрузки можно так:

$sudo update-rc.d -f имя_скрипта remove

Загрузка с помощью rc.local после загрузки системы

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

$sudo chmod +x /etc/init.d/имя_скрипта

Затем подправить файл rc.local любым редактором текста, например nano:

Читайте также:  File protection in linux

Изначально скрипт rc.local пустой и содержит только:

#!/bin/sh -e # # rc.local # # This script is executed at the end of each multiuser runlevel. # Make sure that the script will "exit 0" on success or any other # value on error. # # In order to enable or disable this script just change the execution # bits. # # By default this script does nothing. exit 0

Пропишите полный путь скрипта перед строчкой exit 0 и сохраните файл.

Как сказано в комментариях в эталонном rc.local делаем его исполняемым (хотя во многих дистрибутивах он изначально исполняемый):

Скрипт выполниться после загрузки системы .

Однако в последних версиях Ubuntu (например в Ubuntu 18.04) в директории /etc нет файла rc.local и его необходимо создать и сделать исполняемым:

$ sudo touch /etc/rc.local $ sudo chmod +x /etc/rc.local

Все, скрипт должен автоматически запускаться.

  • Настройка автозапуска скриптов в Linux Ubuntu/Mint
  • Устанавливаем оболочку bash про умолчанию
  • SOCS5 прокси сервер DANTE — установка и настройка
  • Работа с сервисами в Ubuntu 16.04
  • Установка сервера точного времени NTP в Ubuntu 16.04
  • Как протестировать скорость сетевого подключения VDS
  • Самоподписанные сертификаты, WP Multisite и cURL
  • Создание и подключение swap файла
  • Ошибка при обновлении ядра
  • Доступ к админке WP по SSL
  • Блокирование атак при помощи null route или blackhole
  • Добавление нового sudo пользователя
  • Блокирование ip адреса при помощи iptables
  • fail2ban для защиты WordPress
  • Ротация логов — logrotate
  • Простая защита в Apache от DOS атак
  • Защита сервера — Fail2Ban
  • Защита phpMyAdmin
  • Русская locale в Ubuntu Server

Источник

How to start an application automatically on boot

I am new to Linux & looking forward to start application (which toggles a led every 10 sec). I have written the application program & it is working fine but now I want to start it automatically on boot. The documentation here says to copy the startup script to the /etc/init.d directory and make a symbolic link to the copied script in the rc.d directory. What should be the extension and name of these script files? Can we manually add the symbolic link in rc.d or is there some specific procedure for this? Any suggestion how to achieve it?

The preferred way to add an init script to startup varies by distros. Some are even phasing them out in favor of upstart and systemd. I wouldn’t recommend simply using «&» to background, as something like Debian’s start-stop-daemon handles it better (although it preferable the program itself daemonizes). What distro are you using? Outside of desktop MIME types, file extensions are meaningless in *nix and its preferred that executables don’t have one.

Читайте также:  Net 6 winforms linux

If you are using petalogix, just follow that documentation — no special names required, just do as they say. Did you try it? What problems are you having? (If not, please specify your distro and explain what doesn’t work with what you tried.)

if you need to do it approximately every 10 seconds (i.e. not 10 seconds sharp), you might want to use cron instead.

@peterph: but it sounds like the program toggles the LED every 10 seconds, not a program that is executed every 10 seconds.

5 Answers 5

Here’s the excerpt from http://www.debian-administration.org/articles/28 which seems to answer your question.

Note: In the example script below just add a call to the » start) » section to actually launch your program. You can test the script’s functionality without rebooting the system: call it with the full path and giving it a parameter of » start » or » stop «

Debian uses a Sys-V like init system for executing commands when the system runlevel changes — for example at bootup and shutdown time.

If you wish to add a new service to start when the machine boots you should add the necessary script to the directory /etc/init.d/ . Many of the scripts already present in that directory will give you an example of the kind of things that you can do.

Here’s a very simple script which is divided into two parts, code which always runs, and code which runs when called with «start» or «stop».

#! /bin/sh # /etc/init.d/blah # # Some things that run always touch /var/lock/blah # Carry out specific functions when asked to by the system case "$1" in start) echo "Starting script blah " echo "Could do more here" ;; stop) echo "Stopping script blah" echo "Could do more here" ;; *) echo "Usage: /etc/init.d/blah " exit 1 ;; esac exit 0 

Once you’ve saved your file into the correct location make sure that it’s executable by running » chmod 755 /etc/init.d/blah «.

Then you need to add the appropriate symbolic links to cause the script to be executed when the system goes down, or comes up.

The simplest way of doing this is to use the Debian-specific command update-rc.d :

root@skx:~# update-rc.d blah defaults Adding system startup for /etc/init.d/blah . /etc/rc0.d/K20blah -> ../init.d/blah /etc/rc1.d/K20blah -> ../init.d/blah /etc/rc6.d/K20blah -> ../init.d/blah /etc/rc2.d/S20blah -> ../init.d/blah /etc/rc3.d/S20blah -> ../init.d/blah /etc/rc4.d/S20blah -> ../init.d/blah /etc/rc5.d/S20blah -> ../init.d/blah 

Источник

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