- Как установить права доступа к файлам на Mac
- Настройка разрешений для файлов Mac с помощью Finder
- Настройка разрешений для файлов Mac с помощью терминала
- Просмотр текущих прав доступа к файлам
- Настройка прав доступа к файлам
- How To Change File Permissions Using The Terminal
- About Permissions
- How To View File Permissions
- How To Change File Permissions
- Example 1: Set Read, Write and Execute For User, Groups and Others
- Example 2: Remove Write and Execute Permissions For Groups and Others
- Example 3: Remove all Permissions For Groups
- Example 5: Change Permissions on Multiple Files
- More Advanced Scenarios
- Before you go
Как установить права доступа к файлам на Mac
Как и все основные операционные системы, macOS позволяет ограничивать доступ к файлам, используя сложный набор прав доступа к файлам. Вы можете установить их самостоятельно с помощью приложения Finder или с помощью команды chmod в терминале вашего Mac. Вот как.
Настройка разрешений для файлов Mac с помощью Finder
Если вы хотите установить разрешения для файла на вашем Mac без использования терминала, вам нужно будет использовать приложение Finder.
Вы можете запустить Finder из Dock внизу экрана. Приложение представлено улыбающимся значком с логотипом Happy Mac.
В окне Finder вы можете просматривать и устанавливать разрешения, щелкнув правой кнопкой мыши файл или папку и выбрав «Получить информацию».
Обширная информация о вашем файле или папке может быть найдена в открывшемся окне «Информация». Однако, чтобы установить права доступа к файлам, вам нужно нажать на стрелку рядом с опцией «Общий доступ и разрешения».
Будет отображен список учетных записей или групп пользователей на вашем Mac с уровнями доступа, показанными в категории «Права».
Если учетной записи или группы пользователей, для которых вы хотите установить разрешения, нет в списке, выберите значок «Плюс» (+) в нижней части окна.
Выберите пользователя или группу в окне выбора, а затем нажмите кнопку «Выбрать». Это добавит его в список.
Уровни доступа говорят сами за себя — пользователи с уровнем доступа «Только чтение» не могут редактировать файлы, но они могут получить к ним доступ. Если для учетной записи установлен уровень «Чтение и запись», они могут выполнять обе функции.
Чтобы изменить это для пользователя или группы в списке, нажмите стрелку рядом с существующим уровнем для этой учетной записи или группы, а затем выберите «Только для чтения» или «Чтение и запись» из списка.
Разрешения сразу устанавливаются. Закройте окно «Информация», как только вы закончите.
Настройка разрешений для файлов Mac с помощью терминала
Если вы когда-либо использовали команду chmod в Linux, то вы будете знать о ее силе. С помощью одной команды терминала вы можете установить права на чтение, запись и выполнение для файлов и каталогов.
СВЯЗАННЫЕ С: Как использовать команду chmod в Linux
chmod Однако команда не является командой только для Linux. Как и многие другие команды терминала Linux, chmod восходит к Unix с 1970-х годов — Linux и macOS оба разделяют это наследие, поэтому chmod Команда доступна в macOS сегодня.
Использовать chmod откройте окно терминала. Вы можете сделать это, нажав значок Launchpad на панели Dock и выбрав опцию «Terminal» в папке «Other».
Кроме того, вы можете использовать встроенную функцию поиска Spotlight от Apple, чтобы открыть терминал.
Просмотр текущих прав доступа к файлам
Чтобы просмотреть текущие разрешения для файла, введите:
Замените «file.txt» своим именем файла. Это покажет все уровни доступа пользователя, а также любые расширенные атрибуты, относящиеся к macOS.
Права доступа к файлу отображаются в первых 11 символах, выводимых ls команда. Первый символ, ан тире ( — ), показывает, что это файл. Для папок это заменяется буквой ( d ) вместо
Следующие девять символов разбиты на группы по три человека.
Первая группа показывает уровни доступа для владельца файла / папки (1), средняя группа показывает разрешения группы (2), а последние три — разрешения для любых других пользователей (3).
Вы также увидите здесь письма, такие как r (читать), w (написать) и x (Выполнить). Эти уровни всегда отображаются в таком порядке, например:
- — означало бы отсутствие доступа для чтения или записи, и файл не является исполняемым.
- r— будет означать, что файл может быть прочитан, но не записан, и файл не является исполняемым.
- rw- будет означать, что файл может быть прочитан и записан, но файл не является исполняемым.
- r-x означает, что файл может быть прочитан и выполнен, но не записан.
- rwx означает, что файл может быть прочитан, записан и выполнен.
Если последний символ является знаком ( @ ), то это означает, что файл или папка имеют расширенные атрибуты файла, относящиеся к безопасности, предоставляя определенным приложениям (например, Finder) постоянный доступ к файлу.
Отчасти это связано с новыми функциями безопасности, представленными в macOS Catalina, хотя списки контроля доступа к файлам (ACL) были функцией Mac начиная с macOS X 10.4 Tiger еще в 2005 году.
СВЯЗАННЫЕ С: Как работают новые функции безопасности macOS Catalina
Настройка прав доступа к файлам
Чтобы установить права доступа к файлам, вы будете использовать chmod команда на терминале. Чтобы удалить все существующие разрешения, установите для пользователя права на чтение и запись, а другим пользователям — на чтение, введите:
u флаг устанавливает права доступа для владельца файла, g относится к группе пользователей, в то время как o относится ко всем другим пользователям. Использование знака равенства ( = ) стирает все предыдущие разрешения для этой категории.
В этом случае владелец файла получает доступ на чтение и запись, а группа пользователей и другие пользователи получают доступ на чтение.
Вы можете использовать знак плюс ( + ) добавить доступ на уровень пользователя. Например:
Это предоставит всем другим пользователям доступ к файлу как для чтения, так и для записи.
Вы можете использовать минус ( — ) вместо этого, например:
Это исключит доступ для чтения и записи для всех других пользователей из файла.
Чтобы стереть, добавить или удалить разрешения для всех пользователей, используйте a флаг вместо. Например:
Это предоставит всем пользователям и группам пользователей доступ для чтения и записи к вашему файлу, а также позволит всем пользователям выполнять файл.
С большой властью приходит большая ответственность, и нельзя отрицать, что chmod Команда — это обширный и мощный инструмент для изменения прав доступа к файлам на Mac. Вы можете, например, заменить буквы ( rwx ) с комбинацией трех (или четырех) восьмеричных цифр, до 777 (для чтения, записи и выполнения).
Если вы хотите узнать больше об этом, введите man chmod на терминале прочитать полный список доступных флагов и настроек.
Источник
How To Change File Permissions Using The Terminal
It can sometimes be necessary to change file and folder permissions on your Mac, usually because you want to restrict access to certain users and groups.
Even though it’s possible to set the file permissions using Finder, Terminal gives you slightly more control, and of course can also be used in Automator scripts for a little more flexibility. This article shows you how to change file permissions on files just using Terminal.
If you are new to using the OSX Terminal, I highly recommend the Macintosh Terminal Pocket Guide by Daniel J. Barrett as a great starting point.
About Permissions
File permissions permit users different types of permissions to read and write files. For example, it’s possible to set read only access to files and folders so that they can’t be changed or deleted by mistake. You might even want to delete all permissions for a particular user so that the file cannot even be opened (though it will still be visible in Finder. To make files invisible, follow this tutorial).
Permissions are usually assigned per User, Group, or Others and may have attributes such as read, write, and execute. Through Terminal, you have a lot of control over permissions, but at a basic level you can set them in Finder as follows:
1. Select a file, folder or application in Finder
2. Select Get Info (CMD + I) and inspect the Sharing & Permissions section at the bottom of the Info panel
3. Add or delete user names (under the Name column) and choose the permissions you want (under the Privilege column)
Now that you know how to edit permissions in Finder, read on to find out how it can be done in Terminal.
Set user permissions in Finder’s Info panel
» data-medium-file=»https://www.chriswrites.com/wp-content/uploads/Article-9-Finder-Permissions-236×300.jpg» data-large-file=»https://www.chriswrites.com/wp-content/uploads/Article-9-Finder-Permissions.jpg» loading=»lazy» src data-src=»https://www.chriswrites.com/wp-content/uploads/Article-9-Finder-Permissions.jpg» alt=»Finder Permissions» width=»319″ height=»405″> Set user permissions in Finder’s Info panel
How To View File Permissions
In this example we’ll use a temporary folder called My Folder on which to demonstrate the various file permissions options.
1. Open Terminal (type Terminal into Spotlight or open from the Applications -> Utilities folder). A terminal window should open, but if not you can use CMD + N to open a new one or just choose New Window from the Shell menu. You’ll notice that the command prompt (which is where you enter commands) is labelled with the name of your Mac, the current folder and your user name. For example:
2. Navigate to the folder where the file, folder or application you want to change resides. At the command prompt, use the cd command (which means change directory) by typing in the text indicated below in bold followed by the Enter/Return key.
roly$ cd “work/chris writes”
Note that you will need to use quotes around filenames only if the item you want to edit contains a space, as it does in this case.
3. Inspect the current file permissions by typing in the ls command with the -l option to show in the long format, for example:
roly$ ls -l
You should see the list of files in the current directory along with all the relevant file permissions for each item in the directory, as shown below. In this case I’ve actually used the -al option to also display the “.” (current) and “..” (upper level) folders, but it’s not necessary.
List the properties of files in the current directory
» data-medium-file=»https://www.chriswrites.com/wp-content/uploads/Article-9-Terminal-LS-Command-300×123.jpg» data-large-file=»https://www.chriswrites.com/wp-content/uploads/Article-9-Terminal-LS-Command.jpg» loading=»lazy» src data-src=»https://www.chriswrites.com/wp-content/uploads/Article-9-Terminal-LS-Command.jpg» alt=»Terminal LS Command» width=»550″ height=»226″> List the properties of files in the current directory
In the leftmost column, the file permissions for each item are listed. You’ll notice that the item My Folder (the last item in the list) has the permissions drwxr-xr-x. The first item “d” in these permissions indicates it’s a directory rather than a file (but the same principles apply). The subsequent 9 items are split into three flags (read, write and execute) for Users, Groups, and Others and can take the values “r” (read), “w” (write), “x” (execute) or “–” (unset).
It’s important to realise that Groups usually means the group to which the owner of the file belongs to, such as administrators or staff, while Others just means everyone else such as other people that have regular user accounts on your Mac.
- drwx—— means it’s a directory and read, write and execute is enabled for the current user, but nothing for anyone else
- drw-r–r– means that it’s a directory and read and write is enabled for the current user, read access for the Group, and read only access for other users (i.e. they can’t write to the file)
- -rwxrwxrwx means that read, write and execute permissions are enabled for Users, Groups and Others
How To Change File Permissions
The next step is to actually change the file permissions to whatever you want. The chmod command is the easiest way to do this. It has hundreds of different options (type man chmod in Terminal to view it’s help files), but we’ll concentrate on the simplest ones in this tutorial.
The chmod command runs in two modes – absolute and symbolic mode. The absolute mode uses an octal number with various values that can be combined to set many of the different read, write and execute permissions at once. This mode is only recommended for advanced users, but if you’re using chmod regularly you’ll get to know the different codes and might find it more convenient.
For the moment we’ll focus on the symbolic mode which is rather more human-readable. To change the file permissions on a file, you need to specify the category (User, Group, Others, or all three), the type of operation (e.g. add permissions, delete permissions, clear permissions, or use the defaults), and the permissions themselves (read, write, or execute).
The folder I created earlier called My Folder has the permissions drwxr-xr-x which means:
- User: rwx (read, write and execute)
- Group: r-x (read and execute)
- Others: r-x (read and execute)
Here are a few examples of adding and removing permissions from my folder.
Example 1: Set Read, Write and Execute For User, Groups and Others
In this case, at the command prompt type chmod ugo+ rwx “My Folder” then hit Enter, followed by ls -l to view the new permissions:
Adding read, write and execute permissions to a folder
» data-medium-file=»https://www.chriswrites.com/wp-content/uploads/Article-9-Terminal-Permissions-1-300×109.jpg» data-large-file=»https://www.chriswrites.com/wp-content/uploads/Article-9-Terminal-Permissions-1.jpg» loading=»lazy» src data-src=»https://www.chriswrites.com/wp-content/uploads/Article-9-Terminal-Permissions-1.jpg» alt=»Terminal Permissions 1″ width=»550″ height=»200″> Adding read, write and execute permissions to a folder
Instead of using chmod ugo+rwx you could also just use the “all” option which sets permissions for users, groups and others as follows:
Example 2: Remove Write and Execute Permissions For Groups and Others
At the command prompt type chmod go-wx “My Folder” followed by Enter then the ls -l command to view the files and permissions for every item in the current folder:
Removing write and execute permissions for Groups and Others
» data-medium-file=»https://www.chriswrites.com/wp-content/uploads/Article-9-Terminal-Permissions-2-300×109.jpg» data-large-file=»https://www.chriswrites.com/wp-content/uploads/Article-9-Terminal-Permissions-2.jpg» loading=»lazy» src data-src=»https://www.chriswrites.com/wp-content/uploads/Article-9-Terminal-Permissions-2.jpg» alt=»Terminal Permissions 2″ width=»550″ height=»200″> Removing write and execute permissions for Groups and Others
Example 3: Remove all Permissions For Groups
There’s another option for chmod which is to reset (i.e. set to unset) file permissions for Users, Groups or Others using the “=” option.
To reset all the permissions for Groups, just type chmod g= “filename”. In my example, this is how it looks:
Reset permissions for Groups on the folder
» data-medium-file=»https://www.chriswrites.com/wp-content/uploads/Article-9-Terminal-Permissions-3-300×211.jpg» data-large-file=»https://www.chriswrites.com/wp-content/uploads/Article-9-Terminal-Permissions-3.jpg» loading=»lazy» src data-src=»https://www.chriswrites.com/wp-content/uploads/Article-9-Terminal-Permissions-3.jpg» alt=»Terminal Permissions 3″ width=»450″ height=»316″> Reset permissions for Groups on the folder
Example 5: Change Permissions on Multiple Files
Changing permissions is simple enough using the examples already described, but usually you’ll want to change permissions on more than one item. Thankfully, chmod can act on multiple files. Suppose you wish to change all text files that have a txt extension. Simply combine the chmod command with the appropriate file list filter, such as:
- chmod go+wx *txt
This enables write and execute permissions for Groups and Others to all text files in the current directory.
Change permissions on multiple files simultaneously
» data-medium-file=»https://www.chriswrites.com/wp-content/uploads/Article-9-Terminal-Permissions-4-300×132.jpg» data-large-file=»https://www.chriswrites.com/wp-content/uploads/Article-9-Terminal-Permissions-4.jpg» loading=»lazy» src data-src=»https://www.chriswrites.com/wp-content/uploads/Article-9-Terminal-Permissions-4.jpg» alt=»Terminal Permissions 4″ width=»500″ height=»220″> Change permissions on multiple files simultaneously
More Advanced Scenarios
Changing the file permissions is relatively straightforward, and there are lots of combination commands that can be used together for more advanced use cases. It’s definitely worth reading the user manual (type man chmod) to view the complete list of its capabilities. Once you start playing around with file permissions, you could even build chmod commands into Automator scripts, for example to run a shell command that contains chmod directives.
There are also several related commands, notably chown which changes the ownership of files and folders – for example you might want to change the ownership of a file to the administrator user.
Before you go
After spending over 20 years working with Macs, both old and new, theres a tool I think would be useful to every Mac owner who is experiencing performance issues.
CleanMyMac is highest rated all-round cleaning app for the Mac, it can quickly diagnose and solve a whole plethora of common (but sometimes tedious to fix) issues at the click of a button. It also just happens to resolve many of the issues covered in the speed up section of this site, so Download CleanMyMac to get your Mac back up to speed today.
Источник