Меню

Debian permission denied ошибка

Linux is a community of open-source Unix-like operating systems that are based on the Linux Kernel. Linux distributions are constructed in such a secured way that a user cannot make changes unless he/she has administration access. Users who are first time exploring Linux encounter the problem of Permission being Denied. In this article, we will learn how to fix them with the following methods.

  • Sudo command missing
  • Insufficient permissions to access the files
  • Change ownership of the file

Let’s explore all the methods one by one.

Method 1: Sudo command missing

Step 1: This is one of the very common mistakes that experienced Linux users also make and has nothing wrong with your system or files. The sudo command allows you to access the files, and folders, and change settings that are accessible to only a root user. For example, here we are installing a new application and the user who is installing should be a root user. 

First, we enter the command

apt-get install neofetch

And we get the following error.

Step 2: Now add the sudo command, after entering the following command, you are required to enter the password.

sudo apt-get install neofetch

The output is as follows:

Method 2: Insufficient permissions to access the files

Step 1: Some files don’t have the required permission for accessing. In the following example, we want to read a file but we don’t have sufficient permissions.

$ cat geeks.txt

The output is 

Step 2: Now we will change the access permission using the chmod command. The +rwx adds the read-write access.

$ chmod +rwx geeks.txt
$ cat geeks.txt

The output is as follows

The chmod has the following commands:

  • r: It means the read permission.
  • w: It means write permissions
  • x: It means execution permissions.
  • +: It provides permission. 
  • : It removes the permission. 

Method 3: Change ownership of the file

This also gives a Permission Denied error to a user in a mixed system when the user doesn’t have the access to a particular file. We can add users using the chown command.

Step 1: First, check the users who have access using the following command.

ls -l

Only a single user and a single group have access to read, write and execute as can be seen in the output.

Step 2; Now add the user geeks using the following command.

sudo chown geeks geeks.txt

Now check the owners of the file. The output is as follows:

So the user geeks now has the access to the text file.

I appreciate you folks taking the time out to try to help me. I’ve tried to break my reply down into different headers to make it easier to digest.

PREFACE:
I should be clear that all the apt-get commands I’ve mentioned seem to succeed, and this looks like a non-fatal error. I’ve definitely been pulling down new packages with «apt-get dist-upgrade», and «apt-get autoremove» does find packages eligible for automatic removal and successfully removes them. However, it still worries me and I’d really like to get to the bottom of it.

I’ve noticed that I do not get the error messages I’m asking about if apt-get dist-upgrade doesn’t find anything to upgrade:

Code: Select all

# apt-get dist-upgrade
Reading package lists...
Building dependency tree...
Reading state information...
Calculating upgrade...
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.

RUNNING APT-GET AS ROOT
Yes, I’m running apt-get as root. I use «su -«, then the root password, and run from there. I do not have sudo installed.

The exact commands I run, as root, are «apt-get update» followed by «apt-get dist-upgrade». Afterwards I run «apt-get autoremove» and «apt-get clean» just to clean up.

For the sake of science, I just tried to run «apt-get update» as a non-root user. I got this error message instead of my usual success:

Code: Select all

apt-get update
W: chmod 0700 of directory /var/lib/apt/lists/partial failed - SetupAPTPartialDirectory (1: Operation not permitted)
E: Could not open lock file /var/lib/apt/lists/lock - open (13: Permission denied)
E: Unable to lock directory /var/lib/apt/lists/
W: Problem unlinking the file /var/cache/apt/pkgcache.bin - RemoveCaches (13: Permission denied)
W: Problem unlinking the file /var/cache/apt/srcpkgcache.bin - RemoveCaches (13: Permission denied)
E: Could not open lock file /var/lib/dpkg/lock - open (13: Permission denied)
E: Unable to lock the administration directory (/var/lib/dpkg/), are you root?

Similarly, «apt-get upgrade» as a non-root user yields:

Code: Select all

E: Could not open lock file /var/lib/dpkg/lock - open (13: Permission denied)
E: Unable to lock the administration directory (/var/lib/dpkg/), are you root?

MOVING /VAR AND /TMP TO A NEW DISK
I really don’t think migrating /var and /tmp to a new disk is the problem, but I’ve been wrong before and it was the only system change I could come up with. FWIW on my previous box I did the exact same operation and did not experience this problem, but I realize that doesn’t mean much coming from a random stranger on the internet like myself. I suspect I just managed to fall afoul of some glitch in the package updates -this is testing, after all -but I don’t know how to resolve it. You’d also think that someone else would be having the same problem, but maybe I’m just lucky, I guess?

To move /var and /tmp to the new disk, I booted into single user mode from grub. Then I used fdisk to partition the entire new disk as a new LVM physical volume, created a volume group called vg01 consisting of only that physical volume, and then created the logical volumes /dev/vg01/var_lv and /dev/vg01/tmp_lv. I then mounted them as /mnt/new_var and /mnt/new_tmp. I did a «ls -l /var» and «ls -l /tmp» to note the directory structure before proceeding. Then, I did «mv /var/* /mnt/new_var» and «mv /tmp /mnt/new_tmp». «ls -l /mnt/new_tmp» and «ls -l /mnt/new_var» matched up with the earlier «ls -l /var» and «ls -l /tmp» output, so that looked good. To make sure I didn’t miss any hidden files or directories in /var or /tmp, I and used «ls -ld /var/.*» and «ls -ld /tmp/.*» to check for stragglers. There were a few in /tmp, so I moved them over one at a time using «mv». Afterwards, I updated my /etc/fstab and rebooted. I used the «mount» command with no args to make sure things took.

FWIW, I here’s relevant output from mount:

Code: Select all

# mount | grep /tmp
/dev/mapper/vg01-tmp_lv on /tmp type ext4 (rw,relatime,data=ordered)

Code: Select all

# mount | grep /var
/dev/mapper/vg01-var_lv on /var type ext4 (rw,relatime,data=ordered)

/VAR/LIB/APT/LISTS
It looks like the contents of /var/lib/apt/lists were successfully moved to the new disk along with the rest of /var. I can give a full listing if you really want, but thought this post was long enough as-is.

SYSTEM LOGS
I don’t see anything that looks relevant in the output from dmesg. I’ve poked around at some of the logs in /var/log, including /var/log/apt/history.log and /var/log/apt/term.log. I didn’t see anything that looked related to the problem, nor clued me in to exactly when the disk migration took place, let alone whether the two coincided.

Все операционные системы семейства Linux имеют четко разграниченные права доступа. В своей домашней директории пользователь может делать все, что ему угодно, до тех пор, пока укладывается в отведенные рамки. Попытка выйти за них приводит к появлению ошибки «Permission Denied».

Изменение прав в терминале

Рассмотрим вариант, в котором необходимо прочесть текстовый документ, созданный другим пользователем. Файлы TXT в Linux можно просматривать непосредственно в терминале с помощью команды «cat».

  1. Заходим в каталог с интересующим нас документом. Набираем команду «cat filename», подставляя вместо «filename» имя нужного файла. На скриншоте показана ошибка «Permission Denied», выглядящая в русской локализации как «Отказано в доступе».

    Ошибка «Permission Denied»

    Получаем ошибку «Permission Denied» при попытке просмотреть содержимое файла

  2. Проверяем права доступа к содержимому каталога, набрав «ls -l». Результат, полученный для текстового документа, выделен рамкой. Разрешение на чтение и запись имеет только его владелец.

    Просмотр прав доступа командой «ls»

    Проверяем права доступа к документу используя команду «ls -l»

  3. Набираем команду «sudo chmod 755 filename». С ее помощью мы от имени администратора системы даем разрешение на чтение документа себе и любому другому пользователю. Проверяем результат выполнения и убеждаемся, что права доступа изменились нужным образом.

    Изменение прав доступа командой «chmod»

    Используем команду «chmod» и административные права для получения доступа

  4. Повторно используем «cat» и читаем ранее недоступное содержимое.

    Просмотр текстового файла командой «cat»

    Просматриваем содержимое текстового документа командой «cat»

Загрузка ... Загрузка …

Изменение прав в файловом менеджере

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

  1. Как видно на скриншоте, значок файла изначально имеет дополнительные символы, указывающие на то, что доступ у нему ограничен. При попытке посмотреть содержимое получаем графический вариант ошибки «Permission Denied».

    Графический вариант ошибки «Permission Denied»

    При попытке открыть текстовый документ получаем ошибку «Permission Denied»

  2. Разворачиваем меню «Файл». Выбираем в списке действий «Открыть как Администратор».

    Переключение файлового менеджера в режим root

    Открываем меню «Файл» и перезапускаем файловый менеджер от имени root

  3. Вводим в отмеченное стрелкой поле пароль root. Нажимаем кнопку «Аутентификация» или клавишу Enter.

    Окно аутентификации root

    Набираем пароль root в окне аутентификации

  4. В новом окне файлового менеджера вызываем контекстное меню для нужного файла. Выбираем в нем пункт «Параметры».

    Контекстное меню файлового менеджера

    Открываем параметры файла с помощью контекстного меню

  5. Переключаемся на вкладку «Права». Меняем разрешения для группы и остальных пользователей. Для последних выберем в качестве примера «Только чтение». Внеся изменения, закрываем окно параметров.

    Вкладка «Права» в свойствах файла

    На вкладке «Права» разрешаем доступ для группы root и остальных пользователей

  6. Теперь текстовый документ будет открываться в выбранном нами режиме «Только чтение», без возможности редактировать содержимое.

    Файл, открытый в режиме чтения

    Открываем ранее недоступный файл в режиме чтения и изучаем содержимое

Загрузка ... Загрузка …

В заключение

Как видим, избавиться от ошибки Permission Denied достаточно просто. Решив изменить правда доступа к системным файлам, лишний раз убедитесь, что полностью уверены в своих действиях и понимаете последствия вносимых изменений.

Загрузка ... Загрузка …

Post Views: 26 458

im sorry if this is not in the correct place (ie answering my own question with an update, but it was too long for a «comment», and I did not want to edit the previous answer, anywhoo here we go…

Thanks for your reply.
First I tried to rm using sudo as advised, but got permission denied. Then was able to cd up to the «/var/lib/apt/lists/» directory, but no further.
So using «su» I could cd into the «partial» directory and run «rm ./*», clearing out the contents.

Re-running «apt-get update» (as root… sigh*) first gave me

Ign:13 http://security.debian.org stretch/updates/non-free Translation-en
Hit:12 http://security.debian.org stretch/updates/non-free amd64 Packages
Err:13 http://security.debian.org stretch/updates/non-free Translation-en
  BZ2_bzread: /var/lib/apt/lists/partial/security.debian.org_dists_stretch_updates_non-free_i18n_Translation-en.bz2 Read error (-5: DATA_ERROR_MAGIC)
Ign:14 tor+http://zcaptnv5ljsxpnjt.onion jessie InRelease
Hit:15 tor+http://zcaptnv5ljsxpnjt.onion jessie Release
Fetched 295 kB in 2s (130 kB/s)
Reading package lists... Done
E: Failed to fetch http://security.debian.org/dists/stretch/updates/non-free/i18n/Translation-en  BZ2_bzread: /var/lib/apt/lists/partial/security.debian.org_dists_stretch_updates_non-free_i18n_Translation-en.bz2 Read error (-5: DATA_ERROR_MAGIC)
E: Some index files failed to download. They have been ignored, or old ones used instead.

The running update again gave me the same error as before…

Ign:13 http://security.debian.org stretch/updates/non-free Translation-en
Ign:12 http://security.debian.org stretch/updates/non-free amd64 Packages
Err:13 http://security.debian.org stretch/updates/non-free Translation-en
  Could not open file /var/lib/apt/lists/partial/security.debian.org_dists_stretch_updates_non-free_i18n_Translation-en.bz2 - open (13: Permission denied) [IP: 195.20.242.89 80]
Ign:12 http://security.debian.org stretch/updates/non-free amd64 Packages
Fetched 62.9 kB in 1s (43.0 kB/s)
Reading package lists... Done
E: Failed to fetch http://security.debian.org/dists/stretch/updates/non-free/i18n/Translation-en  Could not open file /var/lib/apt/lists/partial/security.debian.org_dists_stretch_updates_non-free_i18n_Translation-en.bz2 - open (13: Permission denied) [IP: 195.20.242.89 80]
E: Some index files failed to download. They have been ignored, or old ones used instead.

Here is the directory entry for my «partial» directory, are the permissions the same for everyone else?

drwx------ 2 _apt root    16384 Aug  5 15:41 partial

Thanks again for the help.

На чтение 2 мин. Просмотров 207 Опубликовано 14.05.2021

При использовании Linux вы можете столкнуться с ошибкой «доступ запрещен» . Эта ошибка возникает, когда у пользователя нет прав на редактирование файла. Root имеет доступ ко всем файлам и папкам и может вносить любые изменения. Однако другим пользователям может быть запрещено вносить такие изменения.

Помните, что только root или пользователи с Sudo привилегии могут изменять разрешения для файлов и папок.

Разрешения можно изменить с помощью ключевого слова chmod . Синтаксис команды:

chmod flags permissions filename

  • flags — это дополнительные параметры, которые пользователи могут устанавливать.
  • разрешения определяет, может ли пользователь читать, писать или выполнять файл. Они могут быть представлены с помощью символьных или восьмеричных чисел.
  • filename — это имя файла, права доступа которого изменены.

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

chmod u = rwx, g = r, o = r file

Здесь каждая буква имеет значение:

  • r дает права на чтение

  • w дает разрешение на запись

  • x дает права на выполнение

Эту же команду можно запустить с использованием восьмеричной записи:

файл chmod 744

Здесь каждая цифра представляет сумму разрешенных разрешений:

  • 4 дает разрешение на чтение

  • 2 дает разрешения на запись

  • 1 дает разрешения на выполнение

  • 0 не дает разрешений

Сумма этих разрешений используется для представления каждого типа авторов.

Флаги

Можно установить следующие флаги:

Флаг — справка — версия -R, —recursive — reference = file — сохранить -root — no-preserve-root -v, — подробный -f, —silent, —quiet -c, —changes Описание открыть меню справки вывод номера версии рекурсивное изменение разрешений установить разрешения аналогично файлу не открывать рекурсивно на ‘/’ открывать рекурсивно на ‘/ ‘, по умолчанию выводить сообщение для каждого файла не выводить сообщения об ошибках дает подробный вывод при внесении изменений

Многие новички пытаются выполнить запись определенных значений в системные файлы с помощью операторов перенаправления ввода и вывода и получают ошибку bash permission denied. Эта ошибка выводится, даже если вы использовали sudo.

Казалось бы, sudo есть, значит права суперпользователя получены и все должно работать но тут все не так просто. В этой статье мы рассмотрим почему возникает ошибка bash permission denied и как ее обойти.

Допустим, вы выполняете команду:

sudo echo "nameserver 8.8.8.8" >> /etc/resolv.conf

А в результате вместо записи строчки в /etc/resolv.conf получаете ошибку:

bash: /etc/resolv.conf permission denied

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

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

echo ‘текст’ | sudo tee -a /путь/к/файлу

echo 'nameserver 8.8.8.8' | sudo tee -a /etc/resolv.conf

Это очень простое решение, но, кроме того, вы можете запустить оболочку bash с правами суперпользователя, чтобы дать ей доступ на запись:

sudo sh -c ‘echo текст >> /путь/к/файлу’
sudo bash -c ‘echo текст >> /путь/к/файлу’

Например:

sudo bash -c 'echo nameserver 8.8.8.8 >> /etc/resolv.conf

Еще одно решение, призванное, упростить эту команду, добавить такой код в ~/.bashrc:

sudoe() {
[[ "$#" -ne 2 ]] && echo "Usage: sudoe <text> <file>" && return 1
echo "$1" | sudo tee --append "$2" > /dev/null
}

Дальше для вывода строки в файл выполняйте:

sudoe ‘текст’ >> /путь/к/файлу

Например:

sudoe "nameserver 8.8.8.8" > /etc/resolv.conf

Теперь все будет работать, как и ожидалось, и ошибка bash отказано в доступе не появится. Еще можно поменять права на файл, а потом уже выводить в него строку. Но это очень неправильное решение. И даже не потому, что это небезопасно, а больше потому что там намного больше действий.

Выводы

В этой небольшой статье мы разобрали почему возникает ошибка bash permission denied при использовании команды echo для системных файлов, а также несколько путей ее решения. Как видите, все достаточно просто. Надеюсь, эта информация была полезной для вас.

Creative Commons License

Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .

Об авторе

Основатель и администратор сайта losst.ru, увлекаюсь открытым программным обеспечением и операционной системой Linux. В качестве основной ОС сейчас использую Ubuntu. Кроме Linux, интересуюсь всем, что связано с информационными технологиями и современной наукой.

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Death stranding ошибка при запуске windows 1809
  • Death stranding ошибка при загрузке