簡體   English   中英

盡管是管理員,但訪問 localhost 仍被拒絕 - PowerShell

[英]Access is denied to localhost despite being administrator - PowerShell


好的,這已經困擾我一段時間了,我現在嘗試了太多東西。

我正在嘗試運行 PowerShell 腳本 - 我的用戶帳戶是域中的常規帳戶,但它是我計算機上的本地管理員。 因此,我創建了一個 PowerShell 腳本,提示我輸入憑據(我在其中鍵入域管理員帳戶的憑據)以用於調用另一個需要此域管理員提升的腳本。 該腳本如下所示:

Invoke-Command -FilePath "C:\Temp\script.ps1" -ComputerName localhost -Credential Get-Credential

這里的script.ps1是需要域管理員提升的腳本。
執行顯示的腳本會導致提示輸入憑據,然后出現以下錯誤:

[localhost] Connecting to remote server localhost failed with the following error message : Access is denied.

我試過弄亂一個看起來像這樣的 .bat 文件:

SET ThisScriptsDirectory=%~dp0
SET PowerShellScriptPath=%ThisScriptsDirectory%script.ps1 PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%PowerShellScriptPath%""' -Verb RunAs}";

同樣,但我無法使其工作 - 它沒有將腳本提升到域管理員級別。
然而,最后,我需要提及的是,如果我使用域管理員提升打開 PowerShell,導航到 C:\\Temp\\script.ps1 並通過 .\\script.ps1 執行它,那么我想使用域提升運行的腳本可以工作。

有什么建議嗎?

幫助我的一個主題(我有一個類似的案例)是關於遠程故障排除中的“如何為非管理用戶啟用遠程處理”部分 基本上,它會告訴您執行 PS 命令:Set-PSSessionConfiguration Microsoft.PowerShell -ShowSecurityDescriptorUI 並向您嘗試使用它的用戶授予執行權限。

如果您具有本地管理權限,請以管理員身份運行 powershell 並運行不帶-Credential標志的Invoke-Command

如果您僅在本地運行腳本,則不需要Invoke-Command 您最好只運行腳本並向其傳遞參數。

好吧,如果我理解正確,你就錯了。

您提供的憑據用於訪問 localhost(您不需要 BTW)。 腳本仍然在未提升的情況下執行。 有兩種解決方案:

  • 您需要提升 powershell 本身並執行腳本。
  • 您需要更改腳本,使其本身接受 Credential 參數並使用它來訪問事物。 在你展示劇本之前,我無話可說。

您可以通過以下方式提升 shell:

 start powershell -verb Runas

這里的問題是,除非您禁用 UAC,否則它會提示您。 不幸的是,我知道沒有簡單的方法可以解決這個問題。 一種可靠的方法是將腳本添加到任務調度程序並將任務設置為運行提升,然后運行它並刪除任務。 所有這些都可以自動化。 這是不幸的 UAC 系統設計的結果(用於相同目的的 Linux 上的 sudo 會將響應緩存一段時間,以便后續命令不會提示)。 這會是這樣的:

  schtasks /Create /TN runner ... /TR powershell -File script.ps1 /RU username /RP password /RL HIGHEST
  schtasks /run runner
  schtasks /delete runner

啟用 PSRemoting 服務以自動啟動

在主機和遠程機器上

Set-Service winrm -StartupType Automatic 
Start-Service winrm

啟用 PSREmoting

在主機和遠程機器上

EnablePSRemoting -Force

將計算機添加到受信任的主機

在遠程機器上

Set-Item wsman:\localhost\Client\TrustedHosts -Value "$(hostname),*$((Get-WmiObject Win32_ComputerSystem).Domain)"

在 Powershell 遠程處理中啟用多跳

確定允許傳遞 Cred 的主機

Enable-WSManCredSSP –Role Client –DelegateComputer   "$(hostname),*$((Get-WmiObject Win32_ComputerSystem).Domain)"

在源機器上。

Enable-WSManCredSSP –Role Server

您必須指定身份驗證和憑據

在主機上

$Cred = [System.Management.Automation.PSCredential]::new("<username>",$("<Password>" | ConvertTo-SecureString -AsPlainText -Force))
invoke-command -ComputerName localhost -ScriptBlock {Write-Host $args[0]} -ArgumentList "Hello!, It Works" -Authentication Credssp -Credential $cred

參考

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_remote_troubleshooting?view=powershell-6

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM