Linux chmod recursive all

Chmod 777 to a folder and all contents [duplicate]

I have a web directory /www and a folder in that directory called store . Within store are several files and folders. I want to give the folder store and all files and folders within the store folder all permissions. How do I do this? I am guessing via .htaccess.

You need to seriously think about giving 777 to all files and folders under /www directory, which means all your files and directories will be readable, writable and executable by whole world.

Just to counter the alarmist misinformation in the comments: your files probably won’t be writeable or even likely readable «by the whole world». You’d have to setup a web server that explicitly allowed these things, which would be very uncommon. These files will be readable, writeable, and executable by any user who’s able to login to your system.

@JoshNoe It isn’t alarmist. Read the OWASP top 10 web application security vulnerabilities: A5 is «security misconfiguration» (e.g. 777 on upload directory) and A1 is «injection». A1 + A5 = pwnd. google.com/search?q=nginx+config+php+code+injection+jpg+comment On Linux the web server runs under a user (e.g. www-data) so every time the server serves a file it is a user logged into the system.

@Pocketsand Granting 777 to the user your web server runs under generally won’t open your files to «the whole world». By default, most web servers don’y serve any files by default, until you explicitly set them up to.

@JoshNoe I assume you’re talking about whether directory listings are configured but that is not what is being discussed here. The comments are concerning basic defensive security principles to help prevent things like code injection and directory traversal attacks. What your saying is analogous to «It’s alarmist to say people should lock their doors if their curtains are already shut.»

7 Answers 7

If you are going for a console command it would be:

chmod -R 777 /www/store . The -R (or —recursive ) options make it recursive.

Or if you want to make all the files in the current directory have all permissions type:

If you need more info about chmod command see: File permission

and if you have a symlink to said folder, to change the permissions on the symlink do chmod -h 777 /some_path/symlink

Читайте также:  Центральное управление astra linux

Note chmod -R 777 /some/path will fail silently if your target is a one of the following file systems: NFTS / exFAT / FAT32

If by all permissions you mean 777

You can give permission to folder and all its contents using option -R i.e Recursive permissions.

But I would suggest not to give 777 permission to all folder and it’s all contents. You should give specific permission to each sub-folder in www directory folders.

Ideally, give 755 permission for security reasons to the web folder.

sudo chmod -R 755 /www/store 

Each number has meaning in permission. Do not give full permission.

N Description ls binary 0 No permissions at all --- 000 1 Only execute --x 001 2 Only write -w- 010 3 Write and execute -wx 011 4 Only read r-- 100 5 Read and execute r-x 101 6 Read and write rw- 110 7 Read, write, and execute rwx 111 
  • First Number 7 — Read, write, and execute for the user.
  • Second Number 5 — Read and execute for the group.
  • Third Number 5 — Read and execute for others.

If your production web folder has multiple users, then you can set permissions and user groups accordingly.

I haven’t downvoted, but I think the reason is that your answer does not cover the OPs question. It’s still a good answer, just not for this topic.

@MarijkeLuttekes: There are already answers who are giving light on how to give 777 permissions to folder. That’s not my intention to answer. I am saying not to give 777 permission to folder at all to www folder. See first comment for question of anubhava. Instead give 755 or required permissions. We understand sometimes from question that OP is heading in wrong direction. Then we should give path should be followed. It’s not only OP will be requiring solution. With same question another person will come to this page for finding answer, then that person will understand what this answer.

This should be marked the correct answer. While the other answers give the ‘solution’ to the problem, this one explains how a typical folder structure should be setup. Very rarely if ever would you want to make a web folder 777. Read the More info links that @SomnathMuluk has provided so that you can understand why.

Источник

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

Если вы используете Linux в качестве основной операционной системы или управляете серверами Linux, вы столкнетесь с ситуацией, когда попытаетесь создать или отредактировать файл и получите ошибку «Permission deny». Как правило, ошибки, связанные с недостаточными разрешениями, можно решить, установив правильные права доступа или владельца .

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

Читайте также:  Samsung ml 2160 драйвер astra linux

Для получения дополнительной информации о правах доступа к файлам см. «Команда Umask в Linux» .

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

Chmod Рекурсивный

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

Чтобы рекурсивно работать со всеми файлами и каталогами в данном каталоге, используйте команду chmod с параметром -R , ( —recursive ). Общий синтаксис для рекурсивного изменения прав доступа к файлу следующий:

Например, чтобы изменить права доступа для всех файлов и подкаталогов в каталоге /var/www/html на 755 вы должны использовать:

Режим также можно указать с помощью символьного метода:

chmod -R u=rwx,go=rx /var/www/html

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

Использование команды find

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

Наиболее распространенный сценарий — рекурсивное изменение разрешений файла веб-сайта на 644 и разрешений каталога на 755 .

find /var/www/html -type d -exec chmod 755 <> ;find /var/www/html -type f -exec chmod 644 <> ;
find /var/www/html -type d -exec chmod u=rwx,go=rx <> ;find /var/www/html -type f -exec chmod u=rw,go=r <> ;

Команда find ищет файлы или каталоги в /var/www/html и передает каждый найденный файл или каталог команде chmod для установки разрешений.

При использовании find с -exec команда chmod запускается для каждой найденной записи. Используйте команду xargs чтобы ускорить операцию, передав сразу несколько записей:

find /var/www/html -type d -print0 | xargs -0 chmod 755 find /var/www/html -type f -print0 | xargs -0 chmod 644

Выводы

Команда chmod с параметрами -R позволяет рекурсивно изменять права доступа к файлу.

Чтобы рекурсивно установить разрешения для файлов в зависимости от их типа, используйте chmod в сочетании с командой find .

Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.

Источник

Linux chmod Recursive: How to Change File Permissions Recursively

Linux chmod Recursive

With the Linux chmod command, we can recursively change file permissions on all files and directories. This guide explains how.

It’s likely you’ve run into the following errors before:

111 [Permission Denied] "Linux-Screw" [Permission Denied] "Linux-Screw" [readonly]

For any system files, using sudo is the preferred way of editing a file. This allows you to keep all the system context. For everyday use with user files, it’s best to change permissions. chmod can do that for us. It keeps us from needing to escalate permission and gives us access when we need it.

Читайте также:  Установка seahorse astra linux

What is chmod? chmod, or change mode, changes the file mode bits of a given file. You can change it either symbolically or with an octal number representation.

chmod Syntax

chmod [OPTION] MODE FILE Or chmod [OPTION] OCTAL-MODE FILE Options: [-c], --changes Verbose-mode, but only for changes [-f], --silent, --quiet Suppress most error messages [-v], --verbose Output a diagnostic for every file processed [-R], --recursive Change files and directories recursively

Those are the available options. Mode refers to symbolic referencing. If I want to add executable permission to a file, I enter in:

And that will add executable permissions. We’ve gone over the basics, we’ll fix a folder structure and make it available to us.

chmod Recursion

Often when you’re working in a folder directory, you don’t need to change the permission of a single file. You’ll need to change the permission of that file, all files in the current folder, and all subdirectories.

Luckily, chmod -R allows us to recursively change all files.

Shows us the following after we changed permissions.

chmod -R

If you want to know why -altrh is my default and preferred set of options, see my recent article on ls.

Okay, there we go. Above we see our directories and files have changed to match the 755, or rwx r-x r-x. That directory is now available to us since we belong to that group (a user group). It’s also available to us since we’re the user. If you’re cleaning up folders from a previous user you can change ownership of the files with chown.

This makes it available to you as a user. However, there is an issue with the above chmod. When you set your umask to something like 0022, the default perm, directories and files are different. Directories are created at 755. Allowing the cd, change directory, command to function properly. Files are created as 644, one less than the directory. This is because normal files do not need execution permissions. Directories do, for cd. So let’s fix it with find and -exec.

chmod Recursively with Find

find -type d -exec chmod 755<> \; find -type f -exec chmod 644 <> \;

chmod Recursively with Find

And there we go, everything saved and kept in line with the default umask. No executable files, and executable directories.

Conclusion

File permissions can be sticky, but chmod helps us fix that. Now that you know how to change permissions, you can truly take ownership of your directories and files. Need to learn more about navigating the Linux infrastructure with shell commands? Read more tutorials here.

Источник

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