PDA

Показать полную графическую версию : [решено] Запуск скрипта выключения компьютера


snark
29-11-2016, 10:21
Всем привет.
Написал PS скрипт для выключения компьютера по расписанию, но он почему-то работает только от администратора. При запуске от ограниченного пользователя выдаёт ошибку:

http://i.imgur.com/NTJ2byj.png (http://imgur.com/NTJ2byj)


Function Create-GetSchedTime {
Param(
$SchedTime
)
$script:StartTime = (Get-Date).AddSeconds($TotalTime)
$RestartDate = ((get-date).AddSeconds($TotalTime)).AddMinutes(1)
$RDate = (Get-Date $RestartDate -f 'dd.MM.yyyy') -replace "\.","/" # формат 16/03/2016
$RTime = Get-Date $RestartDate -f 'HH:mm' # формат 09:31
&schtasks /delete /tn "Post Maintenance Restart" /f
&schtasks /create /sc once /tn "Post Maintenance Restart" /tr $RCMD /SD $RDate /ST $RTime /f
}

[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName( "Microsoft.VisualBasic") | Out-Null

$Title = "Выключение компьютера"
$Message = "Компьютер будет автоматически выключен через:"
$Button1Text = "Выключить"
$Button2Text = "Отложить на 1 час"
$Button3Text = "Отложить на 4 часа"
$Form = $null
$Button1 = $null
$Button2 = $null
$Label = $null
$TextBox = $null
$Result = $null
$RCMD = "'C:\Windows\system32\cmd.exe' /c shutdown -r -f -t 0"

$timerUpdate = New-Object 'System.Windows.Forms.Timer'
$TotalTime = 900 #in seconds
Create-GetSchedTime -SchedTime $TotalTime

$timerUpdate_Tick={
# Define countdown timer
[TimeSpan]$span = $script:StartTime - (Get-Date)
# Update the display
$hours = "{0:00}" -f $span.Hours
$mins = "{0:00}" -f $span.Minutes
$secs = "{0:00}" -f $span.Seconds
$labelTime.Text = "{0}:{1}:{2}" -f $hours, $mins, $secs
$timerUpdate.Start()
if ($span.TotalSeconds -le 0)
{
$timerUpdate.Stop()
&schtasks /delete /tn "Post Maintenance Restart" /f
shutdown -r -f /t 0
}
}

$Form_StoreValues_Closing=
{
#Store the control values
}

$Form_Cleanup_FormClosed=
{
#Remove all event handlers from the controls
try
{
$Form.remove_Load($Form_Load)
$timerUpdate.remove_Tick($timerUpdate_Tick)
#$Form.remove_Load($Form_StateCorrection_Load)
$Form.remove_Closing($Form_StoreValues_Closing)
$Form.remove_FormClosed($Form_Cleanup_FormClosed)
}
catch [Exception]
{ }
}

# Form
$Form = New-Object -TypeName System.Windows.Forms.Form
$Form.Text = $Title
$Form.Size = New-Object -TypeName System.Drawing.Size(355,165)
$Form.StartPosition = "CenterScreen"
$Form.Topmost = $true
$Form.KeyPreview = $true
$Form.ShowInTaskbar = $Formalse
$Form.FormBorderStyle = "FixedDialog"
$Form.MaximizeBox = $Formalse
$Form.MinimizeBox = $Formalse
# Hide Close (X) button
#$Form.ControlBox = $False
$Icon = [system.drawing.icon]::ExtractAssociatedIcon("c:\Windows\System32\UserAccountControlSettings.exe")
$Form.Icon = $Icon

# Button One (Reboot/Shutdown Now)
$Button1 = New-Object -TypeName System.Windows.Forms.Button
$Button1.Size = New-Object -TypeName System.Drawing.Size(80,23)
$Button1.Location = New-Object -TypeName System.Drawing.Size(10,100)
$Button1.Text = $Button1Text
$Button1.Add_Click({
&schtasks /delete /tn "Post Maintenance Restart" /f
shutdown -r -f /t 0
$Form.Close()
})
$Form.Controls.Add($Button1)

# Button Two (Postpone for 1 Hour)
$Button2 = New-Object -TypeName System.Windows.Forms.Button
$Button2.Size = New-Object -TypeName System.Drawing.Size(115,23)
$Button2.Location = New-Object -TypeName System.Drawing.Size(97,100)
$Button2.Text = $Button2Text
$Button2.Add_Click({
$Button2.Enabled = $False
$timerUpdate.Stop()
$TotalTime = 3600
Create-GetSchedTime -SchedTime $TotalTime
$timerUpdate.add_Tick($timerUpdate_Tick)
$timerUpdate.Start()
})
$Form.Controls.Add($Button2)

# Button Three (Postpone for 4 Hours)
$Button3 = New-Object -TypeName System.Windows.Forms.Button
$Button3.Size = New-Object -TypeName System.Drawing.Size(117,23)
$Button3.Location = New-Object -TypeName System.Drawing.Size(218,100)
$Button3.Text = $Button3Text
$Button3.Add_Click({
$Button3.Enabled = $False
$timerUpdate.Stop()
$TotalTime = 14400
Create-GetSchedTime -SchedTime $TotalTime
$timerUpdate.add_Tick($timerUpdate_Tick)
$timerUpdate.Start()
})
$Form.Controls.Add($Button3)

# Label
$Label = New-Object -TypeName System.Windows.Forms.Label
$Label.Size = New-Object -TypeName System.Drawing.Size(280,25)
$Label.Location = New-Object -TypeName System.Drawing.Size(10,15)
$Label.Text = $Message
$Form.Controls.Add($Label)

# labelTime
$labelTime = New-Object 'System.Windows.Forms.Label'
$labelTime.AutoSize = $True
$labelTime.Font = 'Arial, 24pt, style=Bold'
$labelTime.Location = '100, 46'
$labelTime.Name = 'labelTime'
$labelTime.Size = '43, 15'
$labelTime.TextAlign = 'MiddleCenter'
$Form.Controls.Add($labelTime)

#Start the timer
$timerUpdate.add_Tick($timerUpdate_Tick)
$timerUpdate.Start()

# Show
$Form.Add_Shown({$Form.Activate()})
#Clean up the control events
$Form.add_FormClosed($Form_Cleanup_FormClosed)
#Store the control values when form is closing
$Form.add_Closing($Form_StoreValues_Closing)
#Show the Form
$Form.ShowDialog() | Out-Null

И попутно возникает другой вопрос: возможно ли запускать скрипт от имени SYSTEM, но чтобы GUI окно с кнопками было доступно ограниченному пользователю?

Kazun
29-11-2016, 10:48
На компьютере настроен Aplocker/SRP(по умолчанию учетные записи Администратора не подпадают под правила) - поэтому PowerShell запускается в “Constrained Mode”, причина и метод обхода -
https://sysadmins.lv/blog-en/powershell-50-and-applocker-when-security-doesnt-mean-security.aspx
https://sysadmins.lv/blog-en/powershell-50-and-applocker-when-security-doesnt-mean-security-part-2.aspx

Самое простое создать правила по хэшу:
Создаются файлы вида - C:\Users\UserPROFILE\AppData\Local\Temp\xxxxxxx.xxx.ps1 и xxxxxxx.xxx.psm1 - Включите логирование и найдите, т.к. файл не меняет содержимое, то хэши совпадают.

shutdown - Для этого есть компандлет Stop-Computer

psexec позволяет запускать от System.

Ps. Зачем такие сложности, когда есть планировщик заданий.

greg zakharov
29-11-2016, 12:36
При запуске от ограниченного пользователя выдаёт ошибкуКакбэ... если SeShutdownPrivilege у пользователя нет, то и перезагрузить\выключить систему фиг получится (и Applocker здесь по большому счету не при чем). А изголяться с планировщиком заданий это высший пилотаж содомии.




© OSzone.net 2001-2012