Настройка debian после установки

10.6 Похоже, что Debian не использует для настройки процесса загрузки rc.local; как поддерживается эта функция?

Допустим, системе нужно выполнять сценарий foo при загрузке, или
при переключении в какой-либо уровень запуска (System V). В этом случае
действия системного администратора такие:

Поместить сценарий foo в каталог /etc/init.d/.

Запустить команду Debian update-rc.d с состветствующими
аргументами, чтобы установить связи между каталогами rc?.d и
/etc/init.d/foo. Здесь ‘?’ — это число от 0 до 6, соответсвующее
одному из уровней запуска System V.

Перегрузить систему.

Команда update-rc.d установит связи между каталогами rc?.d и
/etc/init.d. Имя каждой связи начинается с букв ‘S’ или ‘K’,
далее числа и имени сценария. Сценарии, начинающиеся с ‘S’ в каталоге
/etc/rcN.d/, выполняются при входе в уровень запуска
N. Сценарии, начинающиеся с ‘K’, выполняются при выходе с уровня
запуска N.

Например, можно выполнять сценарий foo при загрузке, поместив его
в /etc/init.d/ и установив необходимые связи командой
update-rc.d foo defaults 19. Аргумент ‘defaults’ относится к
уровням запуска со 2 по 5. Аргумент ’19’ позволяет запускать сценарий
foo до сценариев с номерами 20 и выше.

Quick Overview, Using Apt, Binary Only

NOTE Using a full mirror, or a mostly full mirror is best practice. You should only use a partial mirror if you absolutely must (e.g. due to disk constraints) and realize that it is unsupported.

Create a mirror of the Debian archive for Apt

Option 1: Using debmirror

Frans Pop has created a wrapper script for this which is available in Debian repositories. A README explains how to use it. This is the preferred approach.

Option 2: Create a partial mirror of the Debian archive

  • Download a DebianInstaller network install cd (netinst.iso) from here http://www.debian.org/CD/netinst/

  • Install Debian on a prototype system (Optional)

  • apt-get packages (or you may use Aptitude if you prefer) -> hint: you don’t have to install, just download to the apt cache, as long apt-move works.

  • AptMove to a directory of your choice (if you are using virtualbox as your prototype system, do not use a shared folder as apt-move mirror directory, vboxsf sometimes wrongly mistakes «rw» file system as «read-only»).

  • Create a pool directory on the filesystem where you will build your new cd.

  • Copy the pool directory from network install cd to the directory you just created.
  • Copy from the directory to which you sent the files using apt-move to the pool directory (you could just AptMove to the pool directory).

  • Get installer-i386 from a debian mirror which is from the same release of DebianInstaller as your network install cd (unless you also build the installer and associated packages).

  • Get overrides.<dist>. files from http://<mirror>/debian/indices

  • Place in your debian-dir (i.e. the same directory as the pool directory you created above).
  • gunzip the overrides in the indices directory (you should probably keep the original gzipped versions too)

  • Generate packages files.
    • generate DebianInstaller packages files:

      • DebianInstaller lives in <debian-dir>/dists/<dist>/main/debian-installer/binary-i386, therefore

        create the appropriate subdirectories (e.g. mkdir -p debian/dists/sarge/main/debian-installer/binary-i386).

      • in a directory for your scripts and configuration files for this project create an apt.conf such as the one at DebianCustomCD/PoolAptConf

      • create a file named yourcdname-di.conf (or anything else, just substitute your filename as appropriate), such as the one at DebianCustomCD/PoolDebianInstallerPackagesGzConf, creating the directories described therein

      • execute the command  apt-ftparchive -c apt.conf generate yourcdname-di.conf 

    • repeat for binary-i386:
      • create another file named yourcdname.conf (such as the one at DebianCustomCD/PoolPackagesGzConf)

      • execute the command  apt-ftparchive -c apt.conf generate yourcdname.conf 

Create the actual CD set

Note that you must have a mirror of the debian archive which is usable by ?AptGet and which has the DebianInstaller binaries.

  • Create the list of packages you want on the cd (probably just a list of files in your pool dir).
  • Assuming you have debian-cd installed, follow the directions in /usr/share/debian-cd.
  • If you find you are missing dependencies, download the packages into your pool dir to correct that, regenerate your packages files, and start the debian-cd instructions over again (you may need to exit the shell you started the procedure in because debian-cd alters the environment while it builds the cd ).
  • Assuming successful completion of the CD building procedure, burn your CD and test.


updates the System V style init script links
I /etc/rc runlevel .d/ NNname
whose target is the script
I /etc/init.d/ name .
These links are run by
when it changes runlevels; they are generally used to start and stop
system services such as daemons.
is one of the runlevels supported by
R init , namely, 0123456789S , and
is the two-digit sequence number that determines where in the sequence
will run the scripts.

This manpage documents only the usage and behaviour of
R update-rc.d .
For a discussion of the System V style init script arrangements please
and the
R Debian Policy Manual .

Please note that this program was designed for use
in package maintainer scripts and, accordingly,
has only the very limited functionality required by such scripts.
System administrators are not encouraged to use
R update-rc.d
to manage runlevels.
They should edit the links directly or
use runlevel editors such as

update-rc.d Cheat Sheet

Category : Cheat Sheets

Get Social!

Debian and Ubuntu use the service command to control services and update-rc.d for adding and removing services from start up. Using the service command we can start, stop, restart and display all available services. With update-rc.d we can add and remove services and add them to the Ubuntu/ Debian start up scripts. As Linux operating systems have multiple states, or runlevels, you need to make sure you add any new services to the correct runlevels. For example, you would not want to start a web service application before starting networking.

See my post on runlevels for more information about runlevels in Linux..

What services are available for startup?

Use the status-all switch to list all services which are registered with the OS and issues them a status command. You will then get one of the following displayed next to each service:

  • – Services with this sign are currently running.
  • – Services with this sign are not currently running..
  • – Services that do not have a status switch.
service --status-all

Sample output:

service --status-all

Start a service

Starting a service is done using the command service followed by the service name and the command to start the service.

service apache2 start

Use the stop keyword with service to stop a service.

service apache2 stop

Check the status of a service

Each service has a status, usually running or not running. Some services, such as network, may have a different output and output more information on the service.

service apache2 status

Remove a service

Use the remove keyword with update-rc.d to remove the service start up command for an application. You will need to use the -f switch if the applications /etc/init.d start up file exists.

update-rc.d -f apache2 remove

 Add a service

Adding a service to Ubuntu or Debian is done with the update-rc.d command. You can specify which runlevels to start and stop the new service or accept the defaults. The init.d file will be added to the relevent rc.d startup folders.

 update-rc.d apache2 defaults

Setting Start and Kill priority

If you need more control over when your service is asked to start and stop, you may need to set the start and kill (S and K) values.

For a given runlevel, you may have several services starting. For example, you may have apache2 and mysql both starting on runlevel 3. Ideally, you’d want mysql to start before apache2 and shutdown after apache2. In this case we need to give mysql the priority in startup, but apache2 the priority in shutdown.

When starting, the lower the number, the earlier it will start. A start priority of 10 will start before a priority of 20. When killing, it’s the opposite. A higher number will be killed before a lower number.

To set the start and kill priority we simply add them to the above update-rc.d command with the start priority first, followed by the kill priority.

update-rc.d apache2 defaults  

The below command will start mysql first, then apache2. On shutdown, the kill will be the reverse of the start with apache2 being killed first and mysql second.

update-rc.d apache2 defaults 90 90
update-rc.d mysql defaults 10 10

Because, in our example, both start and kill priorities are the same we can shorted the command to just

update-rc.d apache2 defaults 90
update-rc.d mysql defaults 10

Manually set the RunLevel to Start and Kill a service

You can manually specify the Linux RunLevel that the system must be in to Start and Kill your service. See my other blog post for more information on RunLevels.

To extend the above example, we can specify exactly which RunLevel apache2 will be started and stopped.

update-rc.d apache2 start 10 2 3 4 5 . stop 90 0 1 6 .

apache2 will be started (as long as it isn’t already) when the system enters RunLevel 2, 3, 4 or 5 with a priority of 10. It will then be asked to stop when the system enters RunLevel , 1 or 6 with a priority of 90.

Example config files and recommended takeover methods




disabled by




dpkg-divert and bind-mount





































custom script

existence of file









echo searchline > /etc/resolvconf/run/interface/zzzinterface








~3-download without -d flag. Other options as necessary.












unmanaged after install


apt-setup base-installer


preseed file



custom script

/etc/profile.d/_fixprofile.sh /etc/profile.d/_fixprofile.csh

Alternatives to config packages

Any alternative configuration file handling method still has to inform the native Debian/Ubuntu configuration handling systems that the native system (dpkg) should leave the new files alone and ignore changes to them. Most documentation on the web does not mention this. The problems arise later when there are updates to the packaged systems.

  • slack — A simple packaging system published by Google to drop configuration files on systems. Unaware of native package configuration handling, no removal capability. slack roles need to divert or otherwise wedge native configuration methods as described above.
  • cfengine2 — Like slack, configuration rules must still use dpkg-divert to cleanly handle configuration files.
  • puppet — A configuration management tool that hides the details of implementation so that you can easily describe policy. Has no understanding of Debian’s conffiles system.
  • FAI — An installer. Configurations are changed by reinstalling the system with the new configurations. Could avoid using its native configuration file system and use as a transport for configuration packages to install systems that don’t require reinstall to reconfigure.
  • bcfg2 — A configuration management tool that can ‘bundle’ configuration files with their respective packages so that verification can succeed despite file changes from the default package installation. Uses debsums to verify installed package consistency.

10.7 Как система управления пакетами обрабатывает случаи, когда пакеты содержат настроечные файлы для других пакетов?

К примеру, некоторые пользователи хотят создать новый сервер, устанавливая
группу пакетов Debian и собственный пакет, состоящий из настроечных файлов.
Вообще, это не очень хорошо, поскольку не будет знать о
файлах настроек, если они находятся в другом пакете, и может затереть эти файлы
при обновлении другого пакета.

Вместо этого создайте собственный пакет, который правит настроечные файлы
«группы» пакетов Debian, как вам необходимо. В последствии
и лругие утилиты системы управления пакетов увидят, что файлы
были отредактированы местным «сисадмином» и не станут трогать
настройки при обновлении этих пакетов.


Roughly 20% of the packages in Debian and Ubuntu ship default configuration files. If these are simply replaced, an upstream update later that modifies the same configuration file will throw dpkg into an interactive conflict resolution system. This is best avoided to make updates non-interactive. To avoid dpkg handling, the upstream package is diverted to a non-active file, and restored on removal of the config package. Placing this diversion and replacement package in its own config package allows the package to be installed by debian-installer before first boot.

The replacement file is best provided as a regular package file (not a conffile) somewhere other than the original location, and symlinked from /etc. This avoids making the replacement file also a conffile. There are complex interaction cases where a package may be removed but its configuration files remain on the system. If the replacements are also configuration files, there are twice as many cases of package installation states to deal with, and no preinst or postrm scripts to execute any logic to handle the additional cases. conffiles are listed in /var/lib/dpkg/info/*.conffiles for each package.

The recommended method to assemble -config packages is to divert and symlink in the postinst, and remove symlinks and diversions in the prerm script. The symlinks are only created if the path is either not present or is already a symlink, and only removed if the path is a symlink. One suggested location is /etc/site/. This requires a purge of the conffiles in the package build, and will generate a linitian error.

The config-package-dev package provides CDBS rules files that help automate much of the work of creating Debian configuration packages using the divert-and-symlink technique with careful error checking and support for apply simple modifications to a Debian upstream configuration file in a way that is easy to maintain over time. It is available in Debian lenny or later. You can read the config-package-dev documentation at http://debathena.mit.edu/config-package-dev for details on how to use it.

Another option is to replace both the file and the checksum so dpkg is unaware of a change, though this would result in new upstream configuration files replacing the locally customized one.


set -e
if  ; then
        for f in auto.master gssapi_mech.conf
                dpkg-divert --add --package ${PKG} --rename \
                        --divert /etc/$f.distrib /etc/$f
                [ \! -e /etc/$f -o -L /etc/$f ] && ln -sf /etc/site/$f /etc/$f
exit 0


set -e
if  ; then
        for f in gssapi_mech.conf auto.master
                [ -L /etc/$f ] && rm /etc/$f
                dpkg-divert --remove --package ${PKG} --rename \
                        --divert /etc/$f.distrib /etc/$f
exit 0

To prevent files in /etc/site in the -config package from becoming conffiles themselves, in the -config debian/rules file, remove or purge the automatically generated DEBIAN/conffiles file after dh_installdeb runs.


binary-arch: build install
        rm debian/company-service-config/DEBIAN/conffiles


Insert links using the defaults:

   update-rc.d foobar defaults

Equivalent command using explicit argument sets:

   update-rc.d foobar start 20 2 3 4 5 . stop 20 0 1 6 .

Insert links for a service that should be running during multi-user mode,
but that does not need to be explicitly stopped on shutdown:

   update-rc.d foobar multiuser

Equivalent command using explicit argument sets:

   update-rc.d foobar start 20 2 3 4 5 . stop 20 1 .

More typical command using explicit argument sets:

   update-rc.d foobar start 30 2 3 4 5 . stop 70 0 1 6 .

Remove all links for a script (assuming foobar has been deleted

   update-rc.d foobar remove

Example of disabling a service:

   update-rc.d -f foobar remove
   update-rc.d foobar stop 20 2 3 4 5 .

Example of a command for installing a system initialization-and-shutdown script:

   update-rc.d foobar start 45 S . start 31 0 6 .

Example of a command for disabling a system initialization-and-shutdown script:

   update-rc.d -f foobar remove
   update-rc.d foobar stop 45 S .


Apt accepts configuration files (without extension) in /etc/apt/apt.conf.d/. These are processed by Apt in numeric/alphabetical order. /etc/apt/apt.conf is also valid but deprecated.

These files contain directives used by all tools in the Apt suite, you can get a list of all current values with apt-config dump

  • Dpkg::Pre-Install-Pkgs {"mycommand";};: executes mycommand before package installation/unpacking by Dpkg.

  • Dpkg::Pre-Invoke {"mycommand";};: executes mycommand before apt calls dpkg

  • Dpkg::Post-Invoke {"mycommand";};: executes mycommand after apt calls dpkg

  • Acquire::http::Proxy "http://proxy:8080";: sets the proxy for HTTP downloads

  • Acquire::https::Proxy "https://proxy:8443";: sets the proxy for HTTPS downloads

  • Acquire::http::Timeout "2";: sets the timeout for HTTP downloads

  • Acquire::https::Timeout "2";: sets the timeout for HTTPS downloads

  • Acquire::ftp::Timeout "2";: sets the timeout for FTP downloads

If you really have to use FTP, this sets the FTP proxy:

   Proxy "ftp://proxy:2121/";
      "USER $(SITE_USER)@$(SITE)";
      "PASS $(SITE_PASS)";

CategoryPackageManagement | CategorySoftware | CategorySystemAdministration


The command accepts several optional flags:

  • —level levels: Specifies the run levels an operation should pertain to. It is given as a string of numbers from 0 to 7. For example, —level 35 specifies runlevels 3 and 5.
  • —add name: This option adds a new service for management by chkconfig. When a new service is added, chkconfig ensures that the service has either a start or a kill entry in every runlevel. If any runlevel is missing such an entry, chkconfig creates the appropriate entry as specified by the default values in the init script. Note that default entries in LSB-delimited ‘INIT INFO’ sections take precedence over the default runlevels in the initscript.
  • —del name: The service is removed from chkconfig management, and any symbolic links in /etc/rc.d which pertain to it are removed.
  • —list name: This option lists all of the services which chkconfig knows about, and whether they are stopped or started in each runlevel. If name is specified, information in only display about service name.


When run with either the
R defaults , multiuser , start , or stop
makes links
I /etc/rc runlevel .d/ NNname
that point to the script
R /etc/init.d/ name.

If any files
I /etc/rc runlevel .d/?? name
already exist then
does nothing.
The program was written this way so that it will never
change an existing configuration, which may have been
customized by the system administrator.
The program will only install links if none are present,
if it appears that the service has never been installed before.

A common system administration error is to delete the links
with the thought that this will «disable» the service, i.e.,
that this will prevent the service from being started.
However, if all links have been deleted then the next time
the package is upgraded, the package’s
script will run
again and this will reinstall links at their factory default locations.
The correct way to disable services is to configure the
service as stopped in all runlevels in which it is started by default.
In the System V init system this means renaming
the service’s symbolic links
R K .

is used then
will make links to start the service in runlevels
and to stop the service in runlevels
R 016 .
is used then
will make links to start the service in runlevels
and top stop the service in only runlevel
R 1 .
By default all the links will have sequence number 20, but
this can be overridden by supplying one
or two
arguments to either
R defaults or multiuser ;
a single argument overrides the sequence number
for both start and stop links
whereas a pair of arguments overrides the sequence numbers
for start and stop links, respectively.

As a rule of thumb, the sequence number of the stop link
should 100 minus the sequence number of the start link;
this causes services to be stopped in the opposite order
to that in which they are started.
Obviously, therefore, the default stop sequence number
should be 80.
Defaulting to 20, as
does, is an old bug that cannot be fixed because
of the risk of breaking things.

Instead of
R defaults or multiuser
one can give one or more sets of arguments specifying
particular runlevels in which to start or stop the service.
Each of these sets of arguments starts with the keyword
R start or stop
and a sequence number
R NN ,
followed by one or more runlevel numbers.
The set is terminated by a solitary full stop character.
When explicit specification, rather than
R defaults ,
is used there will usually be one
and one
set. If different sequence codes are required in different runlevels
then several
sets or several
sets may be specified.
If this is done and the same runlevel is named in multiple sets
then only the last one counts.
Therefore it is not possible to create multiple
or multiple
links for a service in a single runlevel directory.

The script
I /etc/init.d/ name
must exist before
is run to create the links.

Полезные опции запуска

По умолчанию программа не обновляет сторонние оверлеи. Для синхронизации всех подключённых оверлеев во время обновления используйте опцию . Пример:

cl-update -o

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

cl-update -p

Чтобы отобразить вывод списка просчитанных зависимостей с USE-флагами по аналогии с пакетным менеджером , используйте опцию , пример:

cl-update -e

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

cl-update -C

Весьма полезной могут оказаться опции обновления файла списка пакетов . Для того, чтобы привести список пакетов установленных в вашей системе к состоянию в текущей ночной сборке, достаточно выполнить:

cl-update —rebuild-world

Приведение списка пакетов может также разрешить блокировки, которые могут оказаться по причине перегруженности world-файла конфликтующими пакетами.

Другой полезной возможностью может оказаться дополнение world-файла списком пакетов профиля. К примеру, вы установили и настроили Calculate Linux Scratch, после этого захотели попробовать переключиться на профиль . Чтобы установить после этого MATE со всеми зависимостями, можно выполнить:

cl-update —merge-world

Для сокращения места на жестком диске вы можете использовать две опции: для очистки истории изменений локальной копии Git-репозитория и —clean-pkg для удаления скачанных и устаревших архивов программ. Пример:

cl-update -1 —clean-pkg

Runlevel Files

Each service which should be manageable by chkconfig needs two or more commented lines added to its init.d script. The first line tells chkconfig what runlevels the service should be started in by default, as well as the start and stop priority levels. If the service should not, by default, be started in any runlevels, a hyphen should be used in place of the runlevels list. The second line contains a description for the service and may be extended across multiple lines with backslash continuation.

For example, random.init has these three lines:

# chkconfig: 2345 20 80# description: Saves and restores system entropy pool for \# higher quality random number generation.

This file says that the random script should be started in levels 2, 3, 4, and 5, that its start priority should be 20, and that its stop priority should be 80.

Setup basic package

  1. mkdir _packagename_-1
  2. cd _packagename_-1
  3. dh_make —native
    1. s
  4. debian/changelog
    1. unstable -> company

  5. debian/control
    1. Maintainer: _x_-team@company.com

    2. Section: _same as package it configures_
    3. Depend: on the package and versions appropriate
    4. Section and Priority to match upstream package
    5. Description: fill in both single line and longer description. List files being configured.
  6. Makefile
    1. debian/rules calls this without args to «build». Do nothing on the first target (eg. all:)
    2. calls clean. Do nothing here either.
    3. calls install. cp and mkdir relative to $(DESTDIR) to put files in the package.
Добавить комментарий

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