header1   header
header
header Register : : Login header
header
connector   connector
menuleft menuright
submenu   submenu
left
Temporary Local Admin Rights on a host
Last Post 11 May 2011 05:20 PM by Daniel Petcher. 2 Replies.
Printer Friendly
  •  
  •  
  •  
  •  
  •  
Sort:
PrevPrev NextNext
You are not authorized to post a reply.
Author Messages Resolved
Daniel PetcherUser is Offline
New Member
New Member
Posts:7
Avatar

--
06 May 2011 01:19 PM
    Sometimes I need to add a user to his machine's local Administrators group for a limited time so that he can install poorly-written software. I've written some scripts to help, but I'm hoping someone can help me make the scheduling aspect more elegant. Any suggestions?

    I found code online to help me write this script to give a particular user local administrative rights on a specific machine:

    # Add Local Admin group member # # USAGE: Add-LocalAdmin.ps1 computer domain user # param ($computer,$domain,$user) $objUser = [ADSI]("winNT://$domain/$user") $objGroup = [ADSI]("WinNT://$computer/Administrators") $objGroup.PSBase.Invoke("Add",$objUser.PSBase.Path)

    It works, but the computer in question must be online when the script runs. A good guess helped me to reverse the process this way:

    # Remove Local Admin group member # # USAGE: Remove-LocalAdmin.ps1 computer domain user # param ($computer,$domain,$user) $objUser = [ADSI]("winNT://$domain/$user") $objGroup = [ADSI]("WinNT://$computer/Administrators") $objGroup.PSBase.Invoke("Remove",$objUser.PSBase.Path)
    These scripts are nice for interactive use, but I frequently want to grant administrative rights for 24 hours only and revoke them afterward. Scheduling tasks seems to be a nightmare, no matter how I try it. My initial approach was to write a script that would call the first script and then use get-date to calculate the time and date for 24 hours from now. That wasn't tough with (get-date).AddHours(24) re-formatting that into strings that schtasks.exe liked proved to be more hassle than my patience would allow.

    My next approach was to ask the user to tell me when to revoke the Administrator group membership. This works well, but I still need to add input validation up at the top of the script in case the user supplies a date and/or time that doesn't fit schtasks.exe's strict formatting limitations. Here's my code:

    # Adds a domain user to a host's local administrators group and schedules #    a task to remove the user later # USAGE: Revoke-LocalAdminLater.ps1 computer domain user time date # param (  $computer,  $domain,  $user,  $endTime, # hh:mm  $endDate # mm/dd/yyyy ) # end param # Add user now.... $objUser = [ADSI]("WinNT://$domain/$user") $objGroup = [ADSI]("WinNT://$computer/Administrators") $result = $objGroup.PSBase.Invoke("Add",$objUser.PSBase.Path) $result Write-Host Write-Host Write-Host "Added $domain\$user to Local Administrators group on $computer" Write-Host # Make sure there isn't already a script in-place if (Test-Path -Path C:\scripts\Remove-$user.ps1) {rm C:\scripts\Remove-$user.ps1 ; Write-Host "Cleared previous Remove-$user script..." } Write-Host "Building Remove-$user script:" Write-Host New-Item -Name .\Remove-$user.ps1 -ItemType File -Value "# Remove $user at $endTime " @" # Write-Host "Removing $user from Administrators group on $computer...." "@ | Add-Content .\Remove-$user.ps1 $scriptline = '$objUser = [ADSI](' + '"' + "WinNT://$domain/$user" + '"' + ")" Add-Content .\Remove-$user.ps1 -Value $scriptline $scriptline = '$objGroup = [ADSI](' + '"' + "WinNT://$computer/Administrators" + '"' + ")" Add-Content .\Remove-$user.ps1 -Value $scriptline $scriptline = '$objGroup.PSBase.Invoke(' + '"' + "Remove" + '"' + ',$objUser.PSBase.Path)' Add-Content .\Remove-$user.ps1 -Value $scriptline @" Write-Host "Removing task from the queue..." "@ | Add-Content .\Remove-$user.ps1 $scriptline = 'invoke-expression ' + '"schtasks.exe /delete /F /TN Remove-' + $user +'"' Add-Content .\Remove-$user.ps1 -Value $scriptline @" invoke-expression "cmd.exe /c pause" "@ | Add-Content .\Remove-$user.ps1 Write-Host "Verify the Remove-$user script:" Write-Host cat .\Remove-$user.ps1 Write-Host Write-host Write-Host "Schedule the task..." $result = invoke-expression "cmd.exe /c `"`"schtasks.exe /Create /TN Remove-$user /SC ONCE /ST $endTime /SD $endDate /TR `"powershell.exe -executionpolicy unrestricted -file C:\scripts\Remove-$user.ps1`" 2>&1`"`"" $result Write-Host "Check the task schedule...." # $result = invoke-expression "cmd.exe /c `"schtasks.exe /query /FO TABLE /TN Remove-$user 2>&1`"" $result Write-Host "Schedule removal of the Remove-$user.ps1 script file..." Write-Host "to be developed later" Write-Host "Logging is also greatly desired."
    My opinions are mine. My employers have other people to speak for them.
    Daniel PetcherUser is Offline
    New Member
    New Member
    Posts:7
    Avatar

    --
    06 May 2011 02:02 PM
    • Accepted Answer

    At lunch, I was listening to a podcast at powerscripting.net when I heard about this: Windows PowerShell Pack (it's also available as part of the Windows 7 Resource Kit). http://archive.msdn.microsoft.com/P...rShellPack

    To quote from the web page briefly:

    About the PowerShell Pack
    Windows PowerShell Pack contains 10 modules to help supercharge your Windows PowerShell scripting. The PowerShellPack lets you write user interfaces in PowerShell script, manage RSS feeds, schedule operating system tasks, and much more.

    Here's the nice part about scheduled tasks: The code is readable PowerShell! Here are two code samples. The first one schedules a repeating task; the second one does just what I wanted: it schedules a task for some offset against the current time. Check these out:

    New-task | `
    Add-TaskTrigger -DayOfWeek Monday, Wednesday, Friday -WeeksInterval 2 -At "3:00 PM" | `
    Add-TaskAction -Script { Get-Process | `
    Out-GridView Start-Sleep -Seconds 100 `
    } | Register-ScheduledTask TestTask

    New-task | `
    Add-TaskTrigger -In (New-TimeSpan -Seconds 30) | `
    Add-TaskAction -Script `
    { `
     Get-Process | Out-GridView Start-Sleep -Seconds 100 `
    } | Register-ScheduledTask TestTask

    With this tool, I can call my simple script for removing admin rights "now" and insert it as the TaskAction's Script without needing any weird contortions with escaping quotation marks and I change the TimeSpan to 24 hours instead of 30 seconds. The only problem with this code is that it leaves a scheduled task on the server with "Next Run Time = N/A". But this residue can be cleaned-up by adding:

    Get-ScheduledTask -Name "MyTask" | Remove-Task

    My opinions are mine. My employers have other people to speak for them.
    Daniel PetcherUser is Offline
    New Member
    New Member
    Posts:7
    Avatar

    --
    11 May 2011 05:20 PM
    Oops! I almost forgot to post my scripts:

    # Add Local Admin group member
    #
    # USAGE: Add-LocalAdmin.ps1 computer domain user
    #
    param (
       $computer,
       $domain,
       $user)

    if (Test-Connection -ComputerName $computer -Quiet) {
       $objUser = [ADSI]("winNT://$domain/$user") 
       $objGroup = [ADSI]("WinNT://$computer/Administrators")
       $objGroup.PSBase.Invoke("Add",$objUser.PSBase.Path)
    }
    else
    {
       Write-Host "$computer is not responding to a ping"
       Invoke-Expression "cmd.exe /c pause"
       exit
    }


    Next, the script to remove rights now:

    # Remove Local Admin group member
    #
    # USAGE: Remove-LocalAdmin.ps1 computer domain user
    #
    param (
       $computer,
       $domain,
       $user )

    # This tool is available in the Windows 7 Resource kit or
    # at http://archive.msdn.microsoft.com/P...ShellPack:" target="_blank" rel="nofollow">http://archive.msdn.microsoft.com/P...ShellPack:

    Write-Host "Importing TaskScheduler module"
    Import-Module TaskScheduler # Required for the task scheduling code below to work
    Write-Host "Imported TaskScheduler module"
    Write-Host
    Write-Host "Removing $domain\$user from Administrators' group on $computer"
    if (Test-Connection -ComputerName $computer -Quiet) {
       $objUser = [ADSI]("winNT://$domain/$user")
       $objGroup = [ADSI]("WinNT://$computer/Administrators")
       $objGroup.PSBase.Invoke("Remove",$objUser.PSBase.Path)

    # Clean-up scheduled task:
       Get-ScheduledTask -Name Remove-$user | Remove-Task
    }
    else
    {
       Write-Host "$computer is not responding to a ping"
       Invoke-Expression "cmd.exe /c pause" 
       exit
    }


    Finally, the script to Add local administrators and schedule a task to revoke their rights in 24 hours:

    # Adds a domain user to a host's local administrators group and schedules
    # a task to remove the user later
    # USAGE: RevokeLater-LocalAdmin.ps1 computer domain user

    param ( 
       $computer,    
       $domain, 
       $user ) # end param

    # This tool is available in the Windows 7 Resource kit or
    # at http://archive.msdn.microsoft.com/P...ShellPack:" target="_blank" rel="nofollow">http://archive.msdn.microsoft.com/P...ShellPack:

    Import-Module TaskScheduler
    # Required for the task scheduling code below to work

    #
    # First, add $user as an administrator....
    #

    if (Test-Connection -ComputerName $computer -Quiet) { 
       .\Add-LocalAdmin $computer $domain $user 
       Write-Host 
       Write-Host "Added $domain\$user to the Administrators group on $computer" 
       Write-Host
    }
    else

       Write-Host "$computer is not responding to a ping. Correct this condition and try again." 
       invoke-expression "cmd.exe /c pause" 
       exit
    }

    #
    # Schedule deletion for 24 hours from now
    #
    $removeIt = "-File C:\Scripts\LocalAdmin\Remove-LocalAdmin.ps1 $computer $domain $user"
    $posh = "C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe"

    Write-Host "Scheduling Remove-$user ...."
    New-Task -StartWhenAvailable | ` 
       Add-TaskTrigger -In (New-TimeSpan -Hours 24) | ` 
       Add-TaskAction -Path $posh -Arguments $removeIt | `
    Register-ScheduledTask -Name Remove-$user
    #
    # Features yet to be added:
    # - Logging who was given rights by whom and when
    # - Emailing the log weekly
    My opinions are mine. My employers have other people to speak for them.
    You are not authorized to post a reply.


    Active Forums 4.3
    right
    footer   footer
    footer Sponsored by Quest Software • SAPIEN Technologies • Compellent • Microsoft Windows Server 2008 R2 footer
    footer   footer