- permission denied in a folder for a user after chown and chmod
- 2 Answers 2
- UNIX permissions on directories
- Permission denied in 777 folder
- 1 Answer 1
- Create file in folder: permission denied
- 3 Answers 3
- chmod: cannot read directory `.’: Permission denied [closed]
- 2 Answers 2
- Команда chmod Linux
- Команда chmod Linux
- Примеры использования chmod
- Выводы
permission denied in a folder for a user after chown and chmod
I have a directory at
and I’m trying to get user dbadmin all privilages in that folder.
I’ve done chown to dbadmin and chmod 777 on that folder but dbadmin still gets a permission denied error.
If I put sudo in front of the command(I put dbadmi in sudoers), then it works. Why can’t I get it to work without sudo?
2 Answers 2
Can dbadmin traverse /home/ec2-user ? Try doing chmod a+x /home/ec2-user
There could be more reasons for being denied, like a specific acl or a LSM but this is the most likely cause.
UNIX permissions on directories
The UNIX permissions rwx¹ work on directories as follows:
- r: You can view the contents of the directory (the names of the files or folders inside)
- w: You can create new files, delete or rename existing files.
- x: You can traverse the folder.
The traverse permission means that you can access the folder children (assuming you know its name -which you can obtain if you also have read permission-).
In this case dbadmin could read and traverse / as well as /home, but /home/ec2-user probably had a mode like drwx—— 2 ec2-user in order to protect its contents. Thus, even if you had an important file readable by anyone deep inside your home folder, other users can’t get into it, since they wouldn’t be able to go pass /home/ec2-user (which is exactly what you wanted to do, in this case).
¹ Note that I am skipping over the more exotic ones.
Источник
Permission denied in 777 folder
I have never seen this before. No permission to LS even with 777? I need to share this folder for more convenient development. How can I solve it? Thank you.
EDITED: (here are your requests)
hmmm. what is this?
1 Answer 1
This happens because there is a directory higher in the tree where you do not have execute permission. If a parent directory has no execute permission for some user, then that user cannot stat any subdirectories regardless of the permissions on those subdirectories.
Example:
Even though I am the owner of the directory ‘brownies’ and all users have permission to read and enter it, I can’t access it if its parent directory has no execute permission.
It’s better to use groups to manage permissions than give to give directories 777 permission. Are you sure you need to do that?
How to fix the problem in a more secure way:
Let’s assume on /var/opt/gitlab directory you have something like this:
Add yourself and all the other users who need permission to the git group, for example:
Users have to log out and back in for this to take effect. Even if write permission is needed on a subdirectory, you don’t need to add it on a parent directory, by the way, so you don’t have to use chmod at all. You might want to change your subdirectory permissions to prevent anyone from being able to write to it:
Источник
Create file in folder: permission denied
I have a problem copying files to a directory on Ubuntu 12.04. I create a directory in the home directory so that the path where I want to copy to is:
But when ini run the following command in the terminal to create a sample file as follows:
I can not copy files directly in that directory. How can I assign permissions with the chown & chmod commands to copy the files?
I do not know which user and group to use.
3 Answers 3
First of all you have to know that the default permission of directories in Ubuntu is 644 which means you can’t create a file in a directory you are not the owner.
you are trying as user:francisco-vergara to create a file in a directory /home/sixven/camp_sms/inputs which is owned by user:sixven .
So how to solve this:
You can either change the permission of the directory and enable others to create files inside.
This command will change the permission of the directory recursively and enable all other users to create/modify and delete files and directories inside.
You can change the owner ship of this directory and make user:francisco-vergara as the owner
But like this the user:sixven can’t write in this folder again and thus you may moving in a circular infinite loop.
So i advise you to use Option 1.
Or if this directory will be accessed by both users you can do the following trick:
change ownership of the directory to user:francisco-vergara and keep the group owner group:sixven .
Like that both users can still use the directory.
But as I said you before It’s easiest and more efficient to use option 1.
Источник
chmod: cannot read directory `.’: Permission denied [closed]
Want to improve this question? Update the question so it’s on-topic for Stack Overflow.
Closed 8 years ago .
I am trying to recursively change the permission of directories and sub-directories for «data» directory and running into following error..can someone provide inputs on the below error?
2 Answers 2
Directories need the execute permission set in order to see their contents.
You can think of read and execute on directories this way: directories are data files that hold two pieces of information for each file within, the file’s name and it’s inode number. Read permission is needed to access the names of files in a directory. Execute (a.k.a. search) permission is needed to access the inodes of files in a directory, if you already know the file’s name.
When you change a directory permission to 644, you are unable to read the files in that directory although you can read that directory to see it exists.
You need to do this:
A better way might be to use string permission if you simply want to turn off
Otherwise, you can see the directory, but not access the information in that directory.
You maybe better off using relative permissions instead of absolute permissions:
Will remove write permission from group and other, but not touch execute permission.
You can also use find just to set the directories or just to set files:
This will only touch directories, setting read and execute permission on all directories and setting write permission for the owner. This way, you’re not setting execute permission on files themselves.
Источник
Команда chmod Linux
Система полномочий в Linux имеет очень важное значение, поскольку благодаря ей можно разделять привилегии между пользователями, ограничить доступ к нежелательным файлам или возможностям, контролировать доступные действия для сервисов и многое другое. В Linux существует всего три вида прав — право на чтение, запись и выполнение, а также три категории пользователей, к которым они могут применяться — владелец файла, группа файла и все остальные.
Эти права применяются для каждого файла, а поскольку все в системе Linux, даже устройства, считаются файлами, то, получается что эти права применимы ко всему. Мы более подробно рассматривали как работают права доступа к файлам Linux в отдельной статье, а этой, я хочу остановиться на команде chmod, которая используется для установки прав.
Команда chmod Linux
Эта команда имеет типичный для команд linux синтаксис, сначала команда, затем опции, а в конце файл или папка, к которой ее нужно применить:
$ chmod опции права /путь/к/файлу
Сначала рассмотрим какими бывают права доступа linux и как они устанавливаются. Пред этим рекомендую прочитать статью про права, ссылка на которую есть выше. Есть три основных вида прав:
- r — чтение;
- w — запись;
- x — выполнение;
- s — выполнение от имени суперпользователя (дополнительный);
Также есть три категории пользователей, для которых вы можете установить эти права на файл linux:
- u — владелец файла;
- g — группа файла;
- o — все остальные пользователи;
Синтаксис настройки прав такой:
группа_пользователей действие в ид_прав
В качестве действий могут использоваться знаки «+» — включить или «-« — отключить. Рассмотрим несколько примеров:
- u+x — разрешить выполнение для владельца;
- ugo+x — разрешить выполнение для всех;
- ug+w — разрешить запись для владельца и группы;
- o-x — запретить выполнение для остальных пользователей;
- ugo+rwx — разрешить все для всех;
Но права можно записывать не только таким способом. Есть еще восьмеричный формат записи, он более сложен для понимания, но пишется короче и проще. Я не буду рассказывать как считать эти цифры, просто запомните какая цифра за что отвечает, так проще:
- 0 — никаких прав;
- 1 — только выполнение;
- 2 — только запись;
- 3 — выполнение и запись;
- 4 — только чтение;
- 5 — чтение и выполнение;
- 6 — чтение и запись;
- 7 — чтение запись и выполнение.
Права на папку linux такие же, как и для файла. Во время установки прав сначала укажите цифру прав для владельца, затем для группы, а потом для остальных. Например, :
- 744 — разрешить все для владельца, а остальным только чтение;
- 755 — все для владельца, остальным только чтение и выполнение;
- 764 — все для владельца, чтение и запись для группы, и только чтение для остальных;
- 777 — всем разрешено все.
Каждая из цифр не зависит от предыдущих, вы вбираете именно то, что вам нужно. Теперь давайте рассмотрим несколько опций команды, которые нам понадобятся во время работы:
- -c — выводить информацию обо всех изменениях;
- -f — не выводить сообщения об ошибках;
- -v — выводить максимум информации;
- —preserve-root — не выполнять рекурсивные операции для корня «/»;
- —reference — взять маску прав из указанного файла;
- -R — включить поддержку рекурсии;
- —version — вывести версию утилиты;
Теперь, когда вы знаете опции и как настраиваются права доступа chmod, давайте рассмотрим несколько примеров как работает команда chmod linux.
Примеры использования chmod
Я не буду приводить много примеров, так как там и так все более-менее понятно после пояснения правил создания выражений установки прав. Сначала самый частый случай — разрешить выполнения скрипта владельцу:
Или можно воспользоваться цифровой записью:
chmod 766 file
ls — l file
Недостаток цифровой записи в том, что вы не можете модифицировать уже существующие права доступа linux. Например, в первом варианте вы просто добавили флаг выполнения для владельца файла, а все остальные права оставили неизменными. В восьмеричном варианте мы полностью заменили текущие права новыми — все для владельца и чтение/запись для группы и остальных. Как видите, права установлены как и ожидалось. Теперь отключим выполнение владельцем:
И снова проверяем:
Дальше разрешим только чтение всем, кроме владельца:
chmod 744 file
ls -l file
Или отберем все права:
chmod ugo-rwx file
Файлы с правами 000 недоступны никаким пользователям, кроме суперпользователя и владельца. Вернем права обратно:
chmod 755 file
ls -l file
Такая же ситуация с файлами, владельцем которых вы не являетесь, если вы хотите изменить их права — используйте sudo. Из модификаторов прав вы можете конструировать любые последовательности, я думаю тут нет смысла разбирать их все. Для того чтобы поменять права на все файлы в папке используйте опцию -R:
chmod -R ug+rw dir
ls -l dir/
Также вы можете смотреть подробную информацию про вносимые изменения, например:
chmod -Rv ug+rw dir
Выводы
В этой небольшой статье была рассмотрена команда chmod linux. Она очень часто используется наряду с такими командами, как chown и umask для управления правами. Надеюсь, эта информация была полезной для вас. Если у вас остались вопросы, спрашивайте в комментариях!
Источник