Solved

How Can I Export Share Permissions for each Server, from Server.txt Input File?

Posted on 2014-03-18
6
2,585 Views
Last Modified: 2014-03-19
Firstly, I already have the NTFS permissions. I ONLY need the "Share" permissions.

I have been working to understand and manipulate this script from here [http://poshcode.org/3398] to export all share permissions to an HTML file, per server. I understand that this script is not written to access an input file, so I have been implementing variations of the code to include these few lines as described here [https://www.sapien.com/forums/viewtopic.php?f=18&t=6607], to force the Main Script to query the "servers.txt" file and loop through the whole script, then iterate for every servername in the servers.txt file. I will greatly appreciate help to understand exactly how to run this script against many servers. I tried to place this in my PS $Profile, then tried to use it as a ".ps1" file. I will be glad to concatenate in Excel if I need to work with a one-liner per server.

Also, of note is that when I initially ran this a few hours ago, it ran with no errors, then I noticed that the HTML file was created after I refreshed my $Profile by typing .$Profile at cmd prompt or by closing and restarting PS. But subsequently I noticed this line, which is coded in the script:

ERROR: cannot enumerate share permissions

It continued to output an HTML file (only for the local server) but only AFTER I refreshed my "$Profile".

Thank you!

========================
Get-Content servers.txt |
     ForEach-Object{
         # call script file and pass variable $_ which is current line of file
         c:\folder\filename.ps1 -server $_
     }

========================
Function Get-SharePermissions($ShareName){
    $Share = Get-WmiObject win32_LogicalShareSecuritySetting -Filter "name='$ShareName'"
    if($Share){
        $obj = @()
        $ACLS = $Share.GetSecurityDescriptor().Descriptor.DACL
        foreach($ACL in $ACLS){
            $User = $ACL.Trustee.Name
            if(!($user)){$user = $ACL.Trustee.SID}
            $Domain = $ACL.Trustee.Domain
            switch($ACL.AccessMask)
            {
                2032127 {$Perm = "Full Control"}
                1245631 {$Perm = "Change"}
                1179817 {$Perm = "Read"}
            }
            $obj = $obj + "$Domain\$user  $Perm<br>"
        }
    }
    if(!($Share)){$obj = " ERROR: cannot enumerate share permissions. "}
    Return $obj
} # End Get-SharePermissions Function

Function Get-NTFSOwner($Path){
    $ACL = Get-Acl -Path $Path
    $a = $ACL.Owner.ToString()
    Return $a
} # End Get-NTFSOwner Function

Function Get-NTFSPerms($Path){
    $ACL = Get-Acl -Path $Path
    $obj = @()
    foreach($a in $ACL.Access){
        $aA = $a.FileSystemRights
        $aB = $a.AccessControlType
        $aC = $a.IdentityReference
        $aD = $a.IsInherited
        $aE = $a.InheritanceFlags
        $aF = $a.PropagationFlags
        $obj = $obj + "$aC | $aB | $aA | $aD | $aE | $aF <br>"
    }
    Return $obj
} # End Get-NTFSPerms Function

Function Get-AllShares{
    $a = Get-WmiObject win32_share -Filter "type=0"
    Return $a
} # End Get-AllShares Function

# Create Webpage Header
$z = "<!DOCTYPE html PUBLIC `"-//W3C//DTD XHTML 1.0 Strict//EN`"  `"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd`">"
$z = $z + "<html xmlns=`"http://www.w3.org/1999/xhtml`">"
$z = "<head><style>"
$z = $z + "TABLE{border-width: 2px;border-style: solid;border-color: black;border-collapse: collapse;}"
$z = $z + "TH{border-width: 2px;padding: 4px;border-style: solid;border-color: black;background-color:lightblue;text-align:left;font-size:14px}"
$z = $z + "TD{border-width: 1px;padding: 4px;border-style: solid;border-color: black;font-size:12px}"
$z = $z + "</style></head><body>"
$z = $z + "<H4>File Share Report for $env:COMPUTERNAME</H4>"
$z = $z + "<table><colgroup><col/><col/><col/><col/><col/><col/></colgroup>"
$z = $z + "<tr><th>ShareName</th><th>Location</th><th>NTFSPermissions<br>IdentityReference|AccessControlType|FileSystemRights|IsInherited|InheritanceFlags|PropagationFlags</th><th>NTFSOwner</th><th>SharePermissions</th><th>ShareDescription</th></tr>"

$MainShares = Get-AllShares
Foreach($MainShare in $MainShares){
    $MainShareName = $MainShare.Name
    $MainLocation = $MainShare.Path
    $MainNTFSPermissions = Get-NTFSPerms -Path $MainLocation
    $MainNTFSOwner = Get-NTFSOwner -Path $MainLocation
    $MainSharePermissions = Get-SharePermissions -ShareName $MainShareName
    $MainShareDescription = $MainShare.Description

    $z = $z + "<tr><td>$MainShareName</td><td>$MainLocation</td><td>$MainNTFSPermissions</td><td>$MainNTFSOwner</td><td>$MainSharePermissions</td><td>$MainShareDescription</td></tr>"
}
$z = $z + "</table></body></html>"
$OutFileName = $env:COMPUTERNAME + "ShareReport.html"
Out-File -FilePath .\$OutFileName -InputObject $z -Encoding ASCII
$OutFileItem = Get-Item -Path .\$OutFileName
Write-Host " Report available here: $OutFileItem" -Foregroundcolor Yellow
Exit
0
Comment
Question by:kontrariankid
  • 3
  • 3
6 Comments
 

Author Comment

by:kontrariankid
ID: 39939585
I need help with this.. I will increase points if necessary, but I am not seeing the option to do so at this moment in the comments section as indicated here:

http://support.experts-exchange.com/customer/portal/articles/1021286
0
 
LVL 39

Expert Comment

by:footech
ID: 39939975
500 points is the maximum.
I'm not quite clear, do you need a separate file for each server?
0
 

Author Comment

by:kontrariankid
ID: 39940214
Yes sir, I would like to create one HTML report for each server, which lists all shares on said server. But maybe it makes more sense to create one HTML file that contains permissions for ALL servers in the servers.txt input file, as long as there is a separation header that indicates where one server stops and the next one starts.

The above script did output one HTML file named "SAL9001ShareReport.html", but only after I reloaded my PS profile, and now every time I close and restart PS, the same file is created...

$OutFileName = $env:COMPUTERNAME + "ShareReport.html"

I am attaching a copy of that output HTML file here.
SAL9001ShareReport.html
0
Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

 
LVL 39

Accepted Solution

by:
footech earned 500 total points
ID: 39940473
Try saving the below as a .ps1 file.  Then run it.  It will query a file "serverlist.txt" for the list of servers.
$typehash = @{
    0 = "Allow"
    1 = "Deny"
    }

$permhash = @{
    1179817 = "Read"
    1245631 = "Change"
    2032127 = "Full Control"
    }

# Create Webpage Header
$head = @"
<style>
TABLE{border-width: 2px;border-style: solid;border-color: black;border-collapse: collapse;}
TH{border-width: 2px;padding: 4px;border-style: solid;border-color: black;background-color:lightblue;text-align:left;font-size:14px}
TD{border-width: 1px;padding: 4px;border-style: solid;border-color: black;font-size:12px}
</style>
"@

$body = @"
<H4>File Share Report for $server</H4>
"@

$servers = Get-Content serverlist.txt

@(foreach ($server in $servers)
{
    $shareInfo = @(Get-WmiObject Win32_Share -ComputerName $server -filter "type = 0" | Select Name,Path)
    @(foreach ($share in $shareInfo)
    {
        $shareACL = (Get-WmiObject Win32_LogicalShareSecuritySetting -ComputerName $server -filter "name = '$($share.name)'").GetSecurityDescriptor().Descriptor.DACL
        $shareACL | ForEach `
        {
            $user = If ($_.Trustee.Domain)
                    { $_.Trustee.Domain, $_.Trustee.Name -join "\" }
                    Else
                    { $_.Trustee.Name }
            $type = switch ($_.AceType)
                    {
                        0 { $typehash[0]; break }
                        1 { $typehash[1]; break}
                    }
            $perm = switch ($_.AccessMask)
                    {
                        1179817 { $permhash[1179817]; break }
                        1245631 { $permhash[1245631]; break }
                        2032127 { $permhash[2032127]; break }
                    }
            New-Object PsObject -Property @{
                    Server = $server
                    ShareName = $share.name
                    Path = $share.path
                    UserOrGroup = $user
                    Type = $type
                    Permission = $perm
                    }
        }
    }) | Sort Server,ShareName,UserOrGroup |
     Select ShareName,Path,UserOrGroup,Type,Permission |
     ConvertTo-Html -Head $head -Body $body | Out-File shareinfo-$server.html -Encoding ascii
})

Open in new window


Edit:  BTW, thought I should mention that the above is a modification of code I posted in http:Q_28289529.html, which in turn was partially based on the link you provided.
0
 

Author Comment

by:kontrariankid
ID: 39941434
footech.. thank you very much for your help with this! i am attaching a copy of one of the HTML files for your fans.

it works wonderfully! i love the clean appearance of your code as well.

it throws this message, but this is obviously related to many servers being unreachable for whatever reason.

do you think it will be feasible for me to wrestle with this to integrate the NTFS permissions as well with an additional column? i like the Get-ACL approach, but how much work do you think it would be to reach that goal?

can you tell me what "GetWMICOMException" is related to in this instance?

Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
At \\111.111.111.111\foldername\subfolder\PS1\EE_SharePerms\subfolder\EE_Get-SharePerms.ps1:29 char:33
+     $shareInfo = @(Get-WmiObject <<<<  Win32_Share -ComputerName $server -filter "type = 0" | Select Name,Path)
    + CategoryInfo          : InvalidOperation: (:) [Get-WmiObject], COMException
    + FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
shareinfo-MyServerName.html
0
 
LVL 39

Expert Comment

by:footech
ID: 39941494
"The RPC server is unavailable" error can be caused by a few reasons, including: 1) incorrect DNS info, 2) firewall blocking ports, 3) service not running, 4) maybe others.

The code really doesn't have any error handling.  About the most basic you could do is including the following inside the foreach loop, which would just test if the machine is pingable before trying to get share info.
If ( Test-Connection $server -count 1 -quiet )
{
  #do stuff
}

Open in new window

I see no reason why you couldn't add NTFS permissions, but it's not without its challenges.  One question that you would have to decide on is how would the data (the HTML tables) be formatted.  You might notice that the output of what I provided is a bit different than the output of the script in the link you provided.  From your first sample you can see that it groups all share permissions into one cell (and all NTFS perms into another), whereas mine creates a separate row for each share permission - this is more useful when exporting to a .CSV.  If you did the same thing for NTFS perms that could get pretty long.  It's going to depend on what will be useful for you.  Also, if I was going to rework the script to include NTFS perms, I would probably opt to also use PowerShell Remoting to make things easier and quicker.  So, overall it's not a trivial addition.
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Microsoft Windows Server Update Service (WSUS) is free for everyone, but it lacks of some desirable features like send an e-mail to the administrator with the status of all computers on the WSUS server. This article is based on my PowerShell script …
This article will help you understand what HashTables are and how to use them in PowerShell.
Learn the basics of strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
The viewer will learn how to dynamically set the form action using jQuery.

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now