Chmod 777 root linux

Команда chmod Linux

Система полномочий в Linux имеет очень важное значение, поскольку благодаря ей можно разделять привилегии между пользователями, ограничить доступ к нежелательным файлам или возможностям, контролировать доступные действия для сервисов и многое другое. В Linux существует всего три вида прав — право на чтение, запись и выполнение, а также три категории пользователей, к которым они могут применяться — владелец файла, группа файла и все остальные.

Эти права применяются для каждого файла, а поскольку все в системе Linux, даже устройства, считаются файлами, то, получается что эти права применимы ко всему. Мы более подробно рассматривали как работают права доступа к файлам Linux в отдельной статье, а этой, я хочу остановиться на команде chmod, которая используется для установки прав.

Команда chmod Linux

Эта команда имеет типичный для команд linux синтаксис, сначала команда, затем опции, а в конце файл или папка, к которой ее нужно применить:

$ chmod опции права /путь/к/файлу

Сначала рассмотрим какими бывают права доступа linux и как они устанавливаются. Пред этим рекомендую прочитать статью про права, ссылка на которую есть выше. Есть три основных вида прав:

Также есть три категории пользователей, для которых вы можете установить эти права на файл linux:

Синтаксис настройки прав такой:

группа_пользователей действие в ид_прав

В качестве действий могут использоваться знаки «+» — включить или «-« — отключить. Рассмотрим несколько примеров:

  • u+x — разрешить выполнение для владельца;
  • ugo+x — разрешить выполнение для всех;
  • ug+w — разрешить запись для владельца и группы;
  • o-x — запретить выполнение для остальных пользователей;
  • ugo+rwx — разрешить все для всех;

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

Права на папку linux такие же, как и для файла. Во время установки прав сначала укажите цифру прав для владельца, затем для группы, а потом для остальных. Например, :

  • 744 — разрешить все для владельца, а остальным только чтение;
  • 755 — все для владельца, остальным только чтение и выполнение;
  • 764 — все для владельца, чтение и запись для группы, и только чтение для остальных;
  • 777 — всем разрешено все.

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

  • -c — выводить информацию обо всех изменениях;
  • -f — не выводить сообщения об ошибках;
  • -v — выводить максимум информации;
  • —preserve-root — не выполнять рекурсивные операции для корня «/»;
  • —reference — взять маску прав из указанного файла;
  • -R — включить поддержку рекурсии;
  • —version — вывести версию утилиты;
Читайте также:  Exchange mail from linux

Теперь, когда вы знаете опции и как настраиваются права доступа chmod, давайте рассмотрим несколько примеров как работает команда chmod linux.

Примеры использования chmod

Я не буду приводить много примеров, так как там и так все более-менее понятно после пояснения правил создания выражений установки прав. Сначала самый частый случай — разрешить выполнения скрипта владельцу:

Или можно воспользоваться цифровой записью:

chmod 766 file
ls — l file

Недостаток цифровой записи в том, что вы не можете модифицировать уже существующие права доступа linux. Например, в первом варианте вы просто добавили флаг выполнения для владельца файла, а все остальные права оставили неизменными. В восьмеричном варианте мы полностью заменили текущие права новыми — все для владельца и чтение/запись для группы и остальных. Как видите, права установлены как и ожидалось. Теперь отключим выполнение владельцем:

Дальше разрешим только чтение всем, кроме владельца:

Файлы с правами 000 недоступны никаким пользователям, кроме суперпользователя и владельца. Вернем права обратно:

Такая же ситуация с файлами, владельцем которых вы не являетесь, если вы хотите изменить их права — используйте sudo. Из модификаторов прав вы можете конструировать любые последовательности, я думаю тут нет смысла разбирать их все. Для того чтобы поменять права на все файлы в папке используйте опцию -R:

chmod -R ug+rw dir
ls -l dir/

Также вы можете смотреть подробную информацию про вносимые изменения, например:

Выводы

В этой небольшой статье была рассмотрена команда chmod linux. Она очень часто используется наряду с такими командами, как chown и umask для управления правами. Надеюсь, эта информация была полезной для вас. Если у вас остались вопросы, спрашивайте в комментариях!

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

Источник

Learn to Use Chmod Command With These Examples

This article will teach you how to change permissions in Linux with practical examples of chmod command.

Sooner or later in the Linux world, you will have to change the permission on a file or directory. This is done with the chmod command.

In this article, I’ll share with you some of the practical examples of chmod command. I’ll also explain some the popular terms like chmod 777 or chmod 755 or chmod -r.

Before you see the chmod examples, I would strongly advise you to learn the basics of file permissions in Linux. Using chmod command will be a lot easier once you understand the permissions.

Chmod command in Linux

What is chmod? chmod stands for change mode. This command is used for changing the mode of access.

Читайте также:  Linux жесткие мягкие ссылки

But wait! Is it not meant for changing the permission? Actually, in early Unix days, permissions were called mode of access. This is why this particular command was named chmod.

chmod command has the following syntax:

Before you see how to use chmod, you should know its options.

  • -v : output a diagnostic for every file processed
  • -c : like verbose but report only when a change is made
  • –reference=FILE : use FILE’s mode instead of MODE values
  • R : change permissions recursively

Note that using -v option report if change were made or if nothing needed to be done. When combined with -R option, -v can produce a lot of output. –reference=FILE let you use the current permission mode of FILE as the permissions to set on the target file. Note this option requires a double-dash prefix (–) not (-).

Chmod command examples

Using chmod command is very easy if you know what permissions you have to set on a file.

For example, if you want the owner to have all the permissions and no permissions for the group and public, you need to set the permission 700 in absolute mode:

You can do the same in symbolic mode.

If you want an easy way to know the Linux file permission in numeric or symbolic mode, you can use this chmod calculator. Just select the appropriate permissions and it will tell you the permissions in both absolute and symbolic mode.

Change permission on all the files in a directory recursively

chmod has the recursive option that allows you to change the permissions on all the files in a directory and its sub-directories.

chmod 777: Everything for everyone

You might have heard of chmod 777. This command will give read, write and execute permission to the owner, group and public.

If you want to change the mode to 777, you can use the command like this:

chmod 777 is considered potentially dangerous because you are giving read, write and execute permission on a file/directory to everyone (who is on your system). You should totally avoid it.

chmod +x or chmod a+x: Execution for everyone

Probably one of the most used case of chmod is to give a file the execution bit. Often after downloading an executable file you will need to add this permission before using it. To give owner, group and everyone else permission to execute file:

chmod 755: Only owner can write, read and execute for everyone

This next command will set the following permission on file: rwxr-xr-x. Only the owner will be allowed to write to the file. Owner, group members and everyone else will have read and execute permission.

chmod 700: Everything for owner only

This command will give read, write and execute permission to the owner. Group and others will have no permissions, not even read.

Читайте также:  Snort настройка kali linux

chmod 666: No one executes

To give owner, group and everyone else read and write permission on file.

chmod 644: Everyone can read, only owner can write

With this next one, owner will have read and write while group and everyone else have read permission.

chmod 600: Owner can read and write, nothing else for anyone

With this next one, owner will have read and write while group and everyone else will have no permissions whatsoever.

chmod command examples in symbolic mode

In the above examples, I use bitmask to set the new MODE. Those are easy to calculate. Simple addition is required. Consider the following:

You can now easily see where I got the 755, 666, 640 from. You don’t have to use bitmask to set new permission. A more human readable way is available. This second format looks like this:

chmod OPTIONS  /path/to/file

While this may seem complicated, it is quite simple. You first start with typing chmod and the OPTIONS that you want. Then, ask yourself: Who am I changing permissions for? User, Group, Others. This will give you the first section of the command:

The next step to complete the command, you either decide to add permissions bits (+), remove permissions (-), or set permission (=). This last one will add or remove permissions as needed to set permission as you requested.

The next section is where you decide the permission MODE to apply(+), remove (-) or match (=). You can specify any combination of rwx.

This next example will apply read/write permission to file for the owner. The verbose option will cause chmod to report on the action.

This next one will set the group’s write permission on directory and all its content recursively. It will report only on changes.

chmod -cR g+w /path/to/directory

You can combine multiple operation to be done on permission like this next example. It will make sure owner has read/write/execute, also add write permission for group and remove execution for everyone else:

chmod u=rwx,g+w,o-x /path/to/file

This last one will use rFile as a reference to set permission on file. When completed, the permission of file will be exactly as they are for rFile

chmod --reference=/path/to/rFile /path/to/file

There are more options and MODE that can be used with chmod that are not covered or mentioned here. I wanted to keep this to basic and hopefully help a few new Linux user.

A word of warning!

With chmod and sudo you now have to power to change permission on almost any files. This does NOT mean you should. Permissions outside your home directory are set the way they are for a reason. Changing them is rarely the appropriate solutions to any problems.

I hope these chmod command examples were helpful for you. Got a question or suggestion? Please leave a comment below.

Источник

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