Linux find file package

Linux find file package

Find which package contains a file in Debian Linux

If you know you need to find a particular file to finish a compilation And you don’t know which package it is contained in.You have the following option in debian.

APT package searching utility — command-line interface

apt-file is a command line tool for searching packages for the APT packaging system.

Unlike apt-cache, you can search in which package a file is included or list the contents of a package without installing or fetching it.

Install apt-file in debian

#apt-get install apt-file

this will install the apt-file package now.

Once installed you’ll need to download the actual data which it uses to search. This can be accomplished with the following command otherwise apt-file search command won’t return any results.

Once you’ve downloaded data you can now proceed to searching for packages.

#apt-file [options] action [pattern]

Action:
update Fetch Contents files from apt-sources.
search

Search files in packages
list

List files in packages
purge Remove cache files

#apt-file search perl.pm

libapache-mod-perl: usr/lib/perl5/mod_perl.pm
libapache2-mod-perl2: usr/lib/perl5/Apache2/mod_perl .pm
libembperl-perl: usr/lib/perl5/Embperl.pm
libembperl-perl: usr/lib/perl5/Embperl/Recipe /Embperl.pm
libembperl-perl: usr/lib/perl5/Embperl/Syntax /Embperl.pm
libhtml-embperl-perl: usr/lib/perl5/HTML/Embperl.pm
liblog-log4perl-perl: usr/share/perl5/Log/Log4perl .pm
libsdl-perl: usr/lib/perl5/SDL_perl.pm
perl-modules: usr/share/perl/5.8.4/ExtUtils /Miniperl.pm

You can also use one of the following commands to Finding which package contains a file.

dlocate

fast alternative to dpkg -L and dpkg -S

uses GNU locate to greatly speed up finding out which package a file belongs to (i.e. a very fast dpkg -S). many other uses, including options to view all files in a package, calculate disk space used, view and check md5sums, list man pages, etc.

Install dlocate in debian

#apt-get install dlocate

Usage: dlocate [option] [string. ]

Options:
(no option) string list all records that match
-S string list records where files match
-L package list all files in package
-l package almost-emulation of ‘dpkg -l’
-s package print package’s status
-ls package ‘ls -ldF’ of all files in package
-du package ‘du -sck’ of all files in package
-conf package list conffiles in package
-lsconf package ‘ls -ldF’ of conffiles in package
-md5sum package list package’s md5sums (if any)
-md5check package check package’s md5sums (if any)
-man package list package’s man pages (if any)

The -L, -s, and -S commands are roughly analagous to the equivalent dpkg commands.

#dlocate -S /etc/bash_completion

bash: /etc/bash_completion.d
bash: /etc/bash_completion
ppp: /etc/bash_completion.d
ppp: /etc/bash_completion.d/pon
dpatch: /etc/bash_completion.d
dpatch: /etc/bash_completion.d/dpatch _edit_patch
module-assistant: /etc/bash_completion.d
module-assistant: /etc/bash_completion.d/m-a

wajig

simplified Debian package management front end

Wajig is a single commandline wrapper around apt, apt-cache, dpkg, /etc/init.d scripts and more, intended to be easy to use and providing extensive documentation for all of its functions.

With a suitable sudo(1) configuration, most (if not all) package installation as well as creation tasks can be done from a user shell. Wajig is also suitable for general system administration.

A Gnome GUI command ‘gjig’ is also included in the package.

Install wajig in Debian

#apt-get install wajig

Using wajig

#wajig

JIG> help
Common JIG commands:

update Update the list of down-loadable packages
new List packages that became available since last update
newupgrades List packages newly available for upgrading
install Install (or upgrade) one or more packages or .deb files
remove Remove one or more packages (see also purge)
toupgrade List packages with newer versions available for upgrading
upgrade Upgrade all of the installed packages or just those listed
listfiles List the files that are supplied by the named package
listnames List all known packages or those containing supplied string
whatis For each package named obtain a one line description
whichpkg Find the package that supplies the given command or file

Читайте также:  Linux nvidia два монитора

Run LIST-COMMANDS for a complete list of commands.

JIG> whichpkg alsamixer
File Path Package
============================== =============================- ===== ============
/usr/bin/alsamixer alsa-utils
/usr/share/doc/alsa-utils /README.alsamixer alsa-utils
/usr/share/man/man1/alsamixer .1.gz alsa-utils
JIG>

auto-apt

package search by file and on-demand package installation tool

auto-apt checks the file access of programs running within its environments, and if a program tries to access a file known to belong in an uninstalled package, auto-apt will install that package using apt-get. This feature requires apt and sudo to work.

It also provides simple database to search which package contains a requesting file.

Install auto-apt in Debian

#apt-get install auto-apt

After installing you need to update the package list using the following command

If you want to use auto-apt follow this syntax

$Id: auto-apt.sh,v 1.58 2004/03/19 17:53:25 ukai Exp $
Usage: auto-apt [options] command [arg . ]

auto-apt is a simple command line interface for setting up auto-apt ennvironment and/or search packages by filename.

Commands:
run — Enter auto-apt environment run [command [cmdarg]]
update — Retrieve new lists of Contents (available file list) update
updatedb — Regenerate lists of Contents (available file list, no download) updatedb
update-local — Generate installed file lists update-local
merge — Merge lists of Contents merge
del — Delete package list del package
check — Check which package will provide the filename check [-v] [-f] filename list — List filelist in dbfile list [-v] [-f]
search — Search package by filename (grep) search [-v] [-f] pattern
debuild — debuild with auto-apt useful to get build-depends:
status — Report current environments (auto-apt or not)

For some commands, command name with -local suffix, it will use pkgfiles.db, which is created by update-local command, instead of pkgcontents.db

Options:
[-s] [-y] [-q] [-i] [-x] [-X]
[-a dists] [-p hooks]
[-D pkgcontents.bin] [-F pkgfiles.bin] [-L detect.list]

Example

#auto-apt search alsamixer

usr/lib/menu/gnome-alsamixer gnome/gnome-alsamixer
usr/lib/menu/alsamixergui sound/alsamixergui
usr/bin/gnome-alsamixer gnome/gnome-alsamixer
usr/bin/alsamixergui sound/alsamixergui
usr/bin/alsamixer sound/alsa-utils
usr/share/pixmaps/gnome -alsamixer/ gnome/gnome-alsamixer
usr/share/doc/alsamixergui/ sound/alsamixergui
usr/share/doc/gnome-alsamixer/ gnome/gnome-alsamixer

Источник

Debian / Ubuntu Linux: Find Out What Package Provides a File

Debian or Ubuntu Linux commands to find out which package owns a file:

  1. Open the terminal application
  2. Type the following command to find out what package provides /usr/bin/passwd file:
    dpkg -S /usr/bin/passwd
  3. Type the following command to find out what package provides /usr/bin/passwd file:
    dpkg -S /usr/bin/passwd
  4. Use apt-file package searching utility:
    apt-file search vim

Let us see how to use these three commands and examples to find out what package provides as file.

How to find the package that provides a file

You can search for a filename from installed packages using dpkg -S command. For example, find out package name for /bin/ls, enter:
$ dpkg -S /bin/ls
Sample output:

  • 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

The -S or —search option search for a filename from installed packages. You can also obtain detailed status information about coreutils package, enter:
$ dpkg -s coreutils
Sample output:

dpkg-query command

You can also use dpkg-query command which is a tool to show information about packages listed in the dpkg database. The -S option search for a filename from installed packages. All standard shell wildchars can be used in the pattern. This command will not list extra files created by maintainer scripts , nor will it list alternatives.
$ dpkg-query -S ‘/bin/ls’
$ dpkg-query -S ‘passwd*’
$ dpkg-query —search ‘/path/to/file’
$ dpkg-query —search ‘/usr/bin/passwd’
$ dpkg-query —search ‘/etc/passwd’

How to use apt-file for package searching on Debian/Ubuntu

You need to install apt-file command which is a command line tool for searching files in packages for the APT package management system:
$ sudo apt-get install apt-file
$ sudo apt-file update
To search in which package a file is included, enter:
$ apt-file search date
$ apt-file search kvm-ok
Sample outputs:

Читайте также:  Genius look 110 driver windows 10

How do I search for files not installed on my Debian/Ubuntu system

Visit the following url:

Debian Linux find the package that provides a file

Ubuntu Linux find the package that provides a file

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

Как в Linux узнать, в каком пакете содержится файл

Если вы компилируете программы из исходных кодов, то вы, наверняка, сталкивались с ошибками компиляции, когда программа не находит какой-либо файл и компиляция обрывается. Что делать в данной ситуации? Понятно, что нужно установить пакет, который содержит требуемый файл. Но как узнать имя этого пакета?

Вполне возможно, что вас выручит Гугл, достаточно в строке поиска набрать что-нибудь вроде fatal error: ffi.h и уже в первых результатах поиска вы найдёте сайты с ответом на ваш вопрос. Это не самый хороший способ, поскольку:

  • если постоянно надеяться только на Google, то в конце-концов он подведёт;
  • обычно ссылки ведут нас на англоязычные сайты — а с иностранными языками в РФ так себе;
  • ну и, в конце-концов, это просто нубство.

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

apt-file

Эта программа предназначена для поиска файлов в пакетах. Также она может показать все файлы в пакете.

Сразу после установки кэш данных о программах пуст. Чтобы его обновить нужно выполнить команду (можно выполнять как от рута, так и от пользователя):

Когда всё готово, то поиск осуществляется так:

К примеру я ищу файл ffi.h:

Как можно увидеть файл найден, но кроме него ещё и много лишнего:

На помощь можно призвать умные регулярные выражения, к примеру в следующей строке замените ffi.h на тот файл, который вы ищите — и вы всегда будете получать самый точный результат:

Ну и для любителей графического интерфейса, вот вам от меня графический интерфейс:

Справка по команде apt-file

whichpkg

whichpkg — это единая оболочка для управления пакетами в Debian. Она является обёрткой вокруг apt, apt-cache, dpkg, aptitude и других. Её цель — простое управление пакетами из одного интерфейса путём унификации главных функций этих инструментов.

Как видно, показаны совпадения в установленных и в неустановленных пакетах. НО мой предыдущий фокус с фильтрацией командой grep здесь не работает.

Как и положено быть унифицированному интерфейсу, у этой команды огромное количество опций и есть встроенный урок по использованию. Но их рассмотрение выходит за рамки этой заметки.

auto-apt

Программа auto-apt предназначена для поиска пакетов по файлу и установке пакетов по требованию.

Инструмент auto-apt проверяет доступ к файлам запущенными программами внутри своего окружения, и если программа пытается получить доступ к файлу про который известно, что он принадлежит к неустановленному пакету, то auto-apt установит этот пакет используя apt-get. Эта функция требует рабочих apt и sudo.

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

После установки нужно обновить список пакетов следующей командой:

Поиск осуществляется так:

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

dlocate

dlocate является альтернативой dpkg -L и dpkg -S. Её преимуществом является более быстрый поиск, разные дополнительные функции вроде подсчёта занимаемого места, но… она ищет только по установленным пакетам — т. е. для целей, которые озвучены в начале заметки она неприменима.

Заключение

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

Источник

Discover to which package a file belongs to

Sometimes you want to know the related package of a file, before installation, or when it is already there. This is of great help during system hardening or general system cleanups. In this article we have a look at several ways to determine the relationships between files and the package they belong to. We have gathered this information for multiple Linux distributions.

Читайте также:  Windows program with javascript

CentOS, Fedora, RHEL

Show files for RPM packages

Show files for packages on the repository

If you use dnf, then you can query files from the packages that are in your repositories. The package itself does not have to be installed.

Use the -q option with dnf to show only the relevant output.

Show files per installed package

To show what files are in a package, use the rpm command.

If you have the file name, you can turn this around and find the related package.

The output will provide the package and its version.

To just see the package name, use the –queryformat option.

With yum you can do a similar request to see the related package.

And with DNF there is the provides argument.

This will give you possibly multiple hits, as a file can be part of packages from different repositories.

This data is less easy to parse due to the different types of lines.

Debian and Ubuntu

If you want to find the related package of a binary (or file), we first have to know the full path. If you know the binary, then use the which command to discover where it is stored. Using the find command is another option, but may be less efficient. With the dpkg package management tool we can find the related package.

Without the awk command, the output will look like this.

Show files installed by package

If you already know the package name, you can quickly look up the files that are installed by a Debian package.

Let’s do the same for the at package and see what it exactly installs (and where).

Gentoo

The first option is using equery, which is part of the package app-portage/gentoolkit.

The package itself should be installed.

Next alternative is qlist, which is part of app-portage/portage-utils

OpenSUSE

Systems running the distributions from SuSE can use the zypper tool to find the link between a file and a package.

Got more useful commands to share? Let it know in the comments and we add them to the article.

Keep learning

So you are interested in Linux security? Join the Linux Security Expert training program, a practical and lab-based training ground. For those who want to become (or stay) a Linux security expert.

Run automated security scans and increase your defenses. Lynis is an open source security tool to perform in-depth audits. It helps with system hardening, vulnerability discovery, and compliance.

Continue reading

Troubleshooting a full /boot partition on Ubuntu

Show vulnerable packages on Arch Linux with arch-audit

Linux security guide: the extended version

How to solve an expired key (KEYEXPIRED) with apt

4 comments

Example for Arch Linux:

$ pacman -Qo /usr/bin/ls
/usr/bin/ls is owned by coreutils 8.26-1

Thanks for sharing Frank

Hey, place a like button somewhere in your blog pages!.

Those like buttons can leak information to Facebook and Twitter, so that is why there are none 🙂

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About Linux Audit

This blog is part of our mission: help individuals and companies, to scan and secure their systems. We simply love Linux security, system hardening, and questions regarding compliance.

Besides the blog, we have our security auditing tool Lynis. Open source, GPL, and free to use.

For those with enterprise needs, or want to audit multiple systems, there is an Enterprise version.

«One security solution to audit, harden, and secure your Linux/UNIX systems.»

Benefits:

  • Perform audits within a few minutes
  • Central management
  • Powerful reporting
  • Compliance checks (e.g. PCI DSS)
  • Additional plugins and more tests

Enjoy the articles!

Linux and UNIX security automation

Lynis is a free and open source security scanner. It helps with testing the defenses of your Linux, macOS, and Unix systems. Typical use-cases for this software include system hardening, vulnerability scanning, and checking compliance with security standards (PCI-DSS, ISO27001, etc).

Recent Posts

Contact

This blog is part of our mission to share valuable tips about Linux security. We are reachable via @linuxaudit

Company details

CISOfy
De Klok 28,
5251 DN, Vlijmen, The Netherlands
+31-20-2260055

Источник

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