Using ICACLS to set file permission to 'read-only'

时间:2017-04-09 23:21:19

标签: powershell batch-file command-line chmod icacls

I'm having a heck of a time transferring from the simple, intuitive chmod 400 to trying to do the same thing in Windows Command Prompt using ICACLS. Compared to the sleek, octal representation of UNIX/LINUX's chmod, ICACLS seems a complex nightmare.

I have a SSH .pem key which I'm trying to make read-only. I want to replace the old permissions which are currently on it with this new, read-only permission. The closest I've come to finding an answer is the following:

ICACLS "D:\Folder A\Another Folder\File Name Here.ext" /GRANT:R "DOMAIN\USERNAME":R
(found here: https://www.experts-exchange.com/questions/27624477/What-command-can-give-user-read-only-permission.html)

I believe the :R at the very end allows me to replace the current permissions, which is what I want. But I don't know what to put for the "DOMAIN\USERNAME"segment. Any advice?

2 个答案:

答案 0 :(得分:7)

Unix和Windows中的权限以不同的方式工作。在Windows中,默认情况下您具有继承权,并且权限更加精细,因为您拥有ACE(每个身份的权限),而不仅仅是所有者/组/其他。所有者的权限仅在创建时提供。如果您以后更改了所有者,则需要在所有者修改文件之前手动更新ACE。

因此,您需要知道您要授予谁的权限。如果您只想向您登录的用户授予读取权限,可以在PowerShell中使用$env:username或在cmd中使用%USERNAME%

使用PowerShell的示例:

$path = ".\test.txt"
#Reset to remove explict permissions
icacls.exe $path /reset
#Give current user explicit read-permission
icacls.exe $path /GRANT:R "$($env:USERNAME):(R)"
#Disable inheritance and remove inherited permissions
icacls.exe $path /inheritance:r

如果您希望将其设置为chmod 400,则可以检查所有者的身份并为该帐户分配权限。请注意,这也可以是管理员组:

$path = ".\test.txt"
icacls.exe $path /reset
icacls.exe $path /GRANT:R "$((Get-Acl -Path .\test.txt).Owner):(R)"
icacls.exe $path /inheritance:r

或者您可以在PowerShell中使用内置cmdlet:

$path = ".\test.txt"

#Get current ACL to file/folder
$acl = Get-Acl $path

#Disable inheritance and remove inherited permissions
$acl.SetAccessRuleProtection($true,$false)

#Remove all explict ACEs
$acl.Access | ForEach-Object { $acl.RemoveAccessRule($_) }

#Create ACE for owner with read-access. You can replace $acl.Owner with $env:UserName to give permission to current user
$ace = New-Object System.Security.AccessControl.FileSystemAccessRule -ArgumentList $acl.Owner, "Read", "Allow"
$acl.AddAccessRule($ace)

#Save ACL to file/folder
Set-Acl -Path $path -AclObject $acl

答案 1 :(得分:0)

Does

attrib +r "D:\Folder A\Another Folder\File Name Here.ext"

do what you want?