Changing ownership using icacls on windows
Using the icacls command, you can change the owner of a directory or folder, for example:
icacls c:pssecret.docx /setowner John /T /C /L /Q
- /Q — suppress success messages;
- /L — the command is executed directly above the symbolic link, not the specific object;
- /C — the execution of the command will continue despite the file errors. Error messages will still be displayed;
- /T — the command is performed for all files and directories that are located in the specified directory and its subdirectories.
You can change the owner of all the files in the directory:
icacls c:ps* /setowner John /T /C /L /Q
Also, with icacls you can reset the current permissions on the file system objects:
ICACLS C:ps /T /Q /C /RESET
After executing this command, all current permissions on the file object in the specified folder will be reset. They will be replaced with permissions inherited from the parent object.
Note that the icacls command with the /setowner option doesn’t allow you to forcibly change the file system object ownership. If you are not the current object owner, use the takeown.exe command to replace the file or folder ownership.
To find out all files with non-canonical ACL or lengths that do not match the number of ACEs, use the /verify parameter.
icacls "c:test" /verify /T
How to view file and folder permissions using the icacls command?
The iCACLS command allows displaying or changing Access Control Lists (ACLs) for files and folders on the file system. The predecessor of the iCACLS.EXE utility is the CACLS.EXE command (which was used in Windows XP).
The complete syntax of the icacls tools and some useful usage examples can be displayed using the command:
icacls.exe /?
To list current NTFS permissions on a specific folder (for example, C:PS), open a Command prompt and run the command:
icacls c:PS
Save and restore ntfs acls using icacls
Using the icacls command, you can save the current object’s ACL into a text file. Then you can apply the saved permission list to the same or other objects (a kind of way to backup ACLs).
To export the current ACL on the C:PS folder and save them to the PS_folder_ACLs.txt file, run the command:
icacls C:PS* /save c:tempPS_folder_ACLs.txt /t
This command saves ACLs not only to the directory itself but also to all subfolders and files. You can open the resulting text file using notepad or any text editor.
To apply saved access ACLs (restore permissions), run the command:
icacls C:PS /restore c:tempPS_folder_ACLs.txt
Thus, the process of ACLs transferring from one folder to another (or between hosts) becomes much easier.
Using icacl in powershell script to change permissions
If you need to go down the folder structure and change NTFS permissions only on certain types of files, you can use the ICACL utility. For example, you need to find all files with the “pass” phrase in the name and the *.docx extension in your shared network folder.
$files = get-childitem "d:docs" -recurse | Where-Object { $_.Extension -eq ".txt" }foreach($file in $files){
if($file -like "*pass*"){
$path = $file.FullName
icacls $file.FullName /grant corpITSec:(R)
write-host $file.FullName
}
}
You can use icacls in PowerShell scripts to change NTFS permissions on directories on remote computers:
Корень проблем icacls.exe
Проблемы Icacls.exe могут быть отнесены к поврежденным или отсутствующим файлам, содержащим ошибки записям реестра, связанным с Icacls.exe, или к вирусам / вредоносному ПО.
В основном, осложнения icacls.exe связаны с:
Настройка разрешений доступа к объекту
Чтобы наделить какого-либо пользователя какими-либо правами доступа, необходимо выполнить команду:
Просмотр действующих разрешений
Чтобы с помощью утилиты ICACLS просмотреть действующие разрешения доступа к какому-либо объекту, необходимо в окне командной строки выполнить следующую команду:
[code]icacls c:papka_ili_file[/code]Ответом на данную команду послужит список всех пользователей и групп пользователей, которые имеют какие-нибудь права доступа к данному объекту. Напротив каждого пользователя будут указаны права доступа, которые у него есть. Правда указаны они будут с помощью сокращений. Приведу список сокращений для основных прав доступа:
- F — Полный доступ. Скорее всего «f» подразумевает под собой первую букву слова «full»(полный).
- M — Изменение. Скорее всего от слова «modification».
- RX — Чтение и выполнение. «Read» и, возможно, «execution».
- R — Чтение. «Read».
- W — Запись. «Write».
- D — Удаление. «Delete».
Напомню, что в расширенной настройке прав доступа количество различных прав доступа много больше. Чтобы увидеть полный список, введите команду
[code]icacls /?[/code]Хочу добавить, что возможности командной строки всегда выше, нежели возможности настройки через интерфейс. И утилита ICACLS не выделилась из этого правила. Утилита ICACLS дает возможность наделить пользователя правом доступа Максимально возможный(MA).
Распространенные проблемы icacls.exe
Общие проблемы icacls.exe, возникающие с MSDN Disc 3712:
Проблемы MSDN Disc 3712 icacls.exe возникают при установке, во время работы программного обеспечения, связанного с icacls.exe, во время завершения работы или запуска или менее вероятно во время обновления операционной системы. Отслеживание того, когда и где возникает ошибка icacls.exe, является важной информацией при устранении проблемы.
Резервная копия прав доступа к объекту
[code]icacls c:papka /save name /t[/code] [code]icacls c:drugaya_papka /restore name[/code]Приведенные две команды еще ярче показывают то, что возможности командной строки намного выше возможностей интерфейса. Так, первая команда утилиты ICACLS способна создать резервную копию прав доступа для указанного объекта и сохранить его в файл с именем name.
Вторая же команда позволяет применить резервную копию для другого объекта. Таким образом процесс переноса прав доступа с одной папки на другую становится намного легче. Тут стоит отметить, что файл с правами доступа по умолчанию сохраняется в корневую папку активного пользователя.
Вот такие основные возможности предоставляет пользователю утилита ICACLS.