?
Solved

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

Posted on 2014-03-18
6
Medium Priority
?
2,880 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 40

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
Ransomware Attacks Keeping You Up at Night?

Will your organization be ransomware's next victim?  The good news is that these attacks are predicable and therefore preventable. Learn more about how you can  stop a ransomware attacks before encryption takes place with our Ransomware Prevention Kit!

 
LVL 40

Accepted Solution

by:
footech earned 2000 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 40

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

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The following article is intended as a guide to using PowerShell as a more versatile and reliable form of application detection in SCCM.
Windows 10 came with  a lot of built in applications, Some organisations leave them there, some will control them using GPO's. This Article is useful for those who do not want to have any applications in their image (example:me).
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
Suggested Courses

770 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