Ubuntu permission denied как исправить

Все операционные системы семейства 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: 29 047

As a user of Ubuntu or Debian-based Linux distributions, you may have encountered the frustrating “Permission Denied” error while accessing specific files or directories. This error is typically caused by inadequate permissions or ownership settings, preventing you from accessing the required resources. This article will explore three methods to resolve the “Permission Denied” error on Ubuntu and Debian systems. These methods include using the sudo command for temporarily elevated privileges, setting the right system permissions with chmod, and changing the file ownership using chown. Following the step-by-step guide, you can quickly and effectively resolve permission issues and regain access to your desired files or directories.

Steps to fix the permission denied error on Ubuntu/Debian Linux

Here, let’s review the steps to fix the permission denied error on our Ubuntu or Debian-based systems.

Method 1: Use the Sudo Command

Some files are owned by the root and can be accessed only by the root user or with the sudo command. Changing the permissions or ownership of these files is not advisable. However, if needed, they can be modified with superuser permissions. Examples of such files are :

  • /etc/shadow
  • sudoers file
  • systemwide config files

To access such files, we need to use sudo or be a root user as such :

$ whoami
root
$ cat /etc/shadow
< Contents >

Or ,

$ whoami 
user
$ id
uid=1000(user) gid=1000(user) groups=1000(user),27(sudo)
$ sudo cat /etc/shadow
< Contents >

Method 2: Setting the Right System Permissions

This is the most common way of fixing this operation. Often, we lack the necessary permissions to access a file. To check our available permissions, we can use the ls command:

Let’s assume that this results in the following output :

$ ls -l
total 4
-rw------- 1 user user 20 Feb 12 11:36 Test

We can see that only the owner user has read and write permissions. Thus if another user tries to read this file, they will get an error as such:

$ whoami
user1
$ cat /home/user/Test
cat: /home/user/Test: Permission denied

Hence, to fix this, we would use the chmod command. We can provide read access to everyone (the owner, the group members, and others) with the following command :

Checking the permissions on the file now should yield something like the following :

$ ls -l 
total 4
-rw-r--r-- 1 user user 20 Feb 12 11:36 Test

The same can be done with write and execute permissions. If we want to limit the access to the users of the same group, we can use the following command :

This would allow the users in the same group as the owner to access the file, and the permissions would look something like this :

$ ls -l
total 4
-rw-r----- 1 user user 20 Feb 12 11:36 Test

Now, we can finally read the file as the other user.

$ whoami
user1
$ cat /home/user/Test
This Is A Test File

NOTE: If the root user owns the file and our current user is in the sudoer’s group, we can change the file’s permissions by prefixing our commands with sudo. To know more about the usage of the chmod command, check out this module!

Method 3: Change Ownership Of The File

Although less conventional, the last method on our list can help fix the Permission denied error. Instead of changing the file’s permissions, we will change its ownership here. For this, we would need the chown command. First, let us check the ownership of the file using the following:

$ ls -l
total 4
-rw------- 1 user user 20 Feb 12 13:27 Test

As we can see, the file belongs to the user labeled as ‘user‘ and the group by the same name. Also, notice how only the owner has read and write permissions (these can be changed, as discussed previously). However, at present, we cannot access the file. But we’ll change the ownership (and group) of the file with the following:

$ sudo chown user1:mygroup /home/user/Test

If we check the details on our file now, we will find it to be changed to :

-rw------- 1 user1 my-group   20 Feb 12 13:27 Test

As we can see, the permissions on the files are preserved, but the groups that can access the file are changed. Since the owner has read permissions (if that’s not the case, we can always use chmod), we can now read the file’s contents:

$ cat /home/user/Test
This Is A Test File

Conclusion

It is important for those who work with Linux to understand and resolve Permission Denied errors on Ubuntu and Debian-based systems. We have discussed three effective methods to address this issue: utilizing the sudo command, adjusting system permissions, and modifying file ownership. By improving these techniques, you can improve your experience working with Linux systems while reducing the likelihood of accidentally exposing sensitive information. It is advisable to exercise caution when changing permissions and file ownership and consult the official documentation or contact an expert when uncertain. By developing these skills, you can boost your proficiency with Linux, confidently handle Permission Denied errors, and maintain a secure and efficient working environment.

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.

Last Updated :
03 Jun, 2022

Like Article

Save Article

Многие новички пытаются выполнить запись определенных значений в системные файлы с помощью операторов перенаправления ввода и вывода и получают ошибку 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 для системных файлов, а также несколько путей ее решения. Как видите, все достаточно просто. Надеюсь, эта информация была полезной для вас.

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Creative Commons License

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

Об авторе

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


Posted:
21 Feb, 22


Updated:
05 Mar, 23



by Susith Nonis



5 Min

How to fix 'permission denied' error in Linux? [Solutions]

List of content you will read in this article:

  • 1. What is Linux Permission Denied Error?
  • 2. How To Fix Permission Denied Error in Linux?
  • 3. Representation of permissions
  • 4. How to Solve Bash Permission Denied?
  • 5. Conclusion

In Linux operating system, you cannot execute any command without proper permission. Every file and directory has some permission or privilege (read, write, or execute) associated with them. If you are not authorized to access the file or directory, executing any command on that will result as a “permission denied” error in Linux. This prevalent common can only be resolved by getting the proper access to that file and directory. In this article, we will help you with how to fix the permission denied errors in Linux and what type of error is this with the help of various Linux commands.

What is Linux Permission Denied Error?

This type of error will occur whenever you run a command for which you do not have the execute permission. Similarly, you cannot perform read or write action if you do not have read or write permission for any file or directory. These Linux permissions are the primary reason behind the security of Linux, as they will help in protecting the data from unauthorized access. 

Linux system has three types of permissions

1. read permission

2. write permission

3. execute permission

So, if you want to solve a Linux permission denied error, you can check your privileges for the specific file or folder using the following command. 

ls -la

This command will display the long listing of all files and folders along with the permission, as shown below.

As shown below, we have created a shell script “hello.sh” without the execute permission. On executing “hello.sh”, you will get a “permission denied” error.

How To Fix Permission Denied Error in Linux?

For solving this error, you need to add the correct permissions to the file to execute. However, you need to be a “root” user or have sudo access for changing the permission. For changing the permission, Linux offers a chmod command. The chmod stands for change mod. This command has a simple syntax, as shown below.

chmod flags permissions filename
  • Flags are the additional options that users can set.
  • Permissions can either be read, write or execute in the file. You can represent them in symbolic form (r, w, and x) or octal numbers.
  • The Filename specifies the file’s name for changing the permissions.

Representation of permissions

Below is the symbolic and octal representation of the user’s permissions while executing the “chmod” command. First, we will understand the representation before using it.

  • Symbolic representation

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

where-

  • r specifies the read permissions
  • w specifies the write permissions
  • x specifies the execute permissions
  • Octal representation-

chmod 744 file

where-

  • 4 specifies the read permissions
  • 2 specifies the write permissions
  • 1 specifies the execute permissions
  • 0 means no permissions issued.

How to Solve Bash Permission Denied?

Now, we are aware of the error, as shown below.

Giving the appropriate permission to the user will solve the problem. Thus, we are giving the execute permission to the user to run the “hello.sh” shell script. Execute the below command to provide execute permission.

chmod +x hello.sh

Now, we can see the change in the permission of the “hello.sh” script file. The above command provides the execute permission to the file. As you can see, the root user can make the required changes. If we execute the shell script, we should not get the error. Let’s try by running the below command.

./hello.sh

After executing the “hello.sh”, we get the output that displays the “hello.” Changing permission has solved the problem of bash permission denied.

Conclusion

If you are a regular Linux user, you might have faced the “permission denied” error while executing various commands. This might be due to the incorrect privileges to run that command. Only a root user or user with sudo access can change the permissions for the file or directory you want to access or execute. If you are the correct user to make the required permission changes, you can run the “chmod” command and add the desired permission.

This is all about how you can solve/fix permission denied errors in Linux with the help of the above-listed commands/methods. If you think there are other alternatives to achieve the goal, you can put them down via the comment box. Also, you can buy a Linux VPS server to run and test the above listed commands.

People also read: 

  • How to fix the sudo command not found error
  • How to fix DNS server not responding error 
  • What is 403 forbidden error
  • 500 internal server error: fixed
  • How to fix npm command not found error

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