Powershell遠程機多跳問題

何爲多跳問題,即A機器遠程到B機器,然後去C機器copy或者獲取文件。
這裏寫圖片描述
對於Powershell新手,多跳問題(multi-hop)是一個難搞的事情,明明Winrm到遠程機沒問題,在遠程機上直接操作也是能行,爲啥兩跳以後,就會報access is deny等一系列問題呢?最最根本的原因是從A機器遠程到B機器時會丟掉credential。國內的博客上好多解決方案,絕不奏效,都沒有提到最最關鍵的一步:組策略的修改。
第一步:Trustedhost
因爲你要連遠程機,所以遠程機必須是trusted。很簡單的一句命令搞定。

Set-Item WSMan:\localhost\Client\TrustedHosts -value * -Force

如果不加,可能會報如下這樣子的錯:
這裏寫圖片描述
第二步:CredSSP
因爲遠程到B機器時丟掉了credential,所以首先想到的就是Enable-WSManCredSSP,文檔如是說:

The Enable-WSManCredSSP cmdlet enables Credential Security Support Provider (CredSSP) authentication on a client or on a server computer. When CredSSP authentication is used, the user credentials are passed to a remote computer to be authenticated. This type of authentication is designed for commands that create a remote session from another remote session. For example, if you want to run a background job on a remote computer, use this kind of authentication.
粗略翻譯如下:
Enable-WSManCredSSP能開啓CredSSP授權電腦爲一個客戶端或者服務端。CredSSP授權可以允許把用戶憑據代到被授權的遠程機。這類授權是爲從一個遠程會話向另一個遠程會話建立鏈接而設計的。例如,當你當在遠程機器執行一個後臺執行任務時,用這種授權
這個時候就需要理解,哪個是server哪個是client,憑據是從client機器帶到server機器,所以不要授權反了,那樣肯定沒效果,還是上邊例子,A爲client,B爲server,憑據從A機器會代到B機器。沒毛病。廢話少說,上代碼!

##當前A機器爲cosdesdev1,我們控制B機器vmaosupse2去C機器cosmoxydev8的UNC路徑讀取文件夾列表
Enable-WSManCredSSP -Role "Client" -DelegateComputer * -force | out-null
$secPassword = ConvertTo-SecureString "guguji5" -AsPlainText -Force
$cred = New-Object system.Management.Automation.PSCredential("advent\axyssu", $secPassword)

invoke-Command -ComputerName vmaosupse2 -Credential $cred -ScriptBlock {
    Enable-WSManCredSSP -Role "Server" -force | out-null
}
invoke-Command -ComputerName vmaosupse2 -Credential $cred -Authentication Credssp -ScriptBlock{
    $path = "\\cosmoxydev8\c$\Moxy\Client"
    get-childitem -path $path
}

得到的報錯大概如下圖
這裏寫圖片描述
從我認識的僅有的幾個英語單詞中,可以挑出“組策略”不允許代理用戶的憑據到目標機器。接下來,就到了下一步,也是成功的關鍵。

第三步:組策略修改
我參考了好多文章都沒成功,因爲都只做了第一步,其實組策略的修改纔是關鍵。首先在運行gpedit.msc打開組策略的面板,Computer Configuration(計算機配置)->Administrative Templates(管理員模版)->System(系統)->Credentials Delegation(憑據代理),在雙擊“允許僅服務器代理NTLM憑據”(藍色的那一項),設置爲“啓用”,在增加servers list里加入“*”。
這裏寫圖片描述
這裏寫圖片描述
然後去windows servers裏重啓winrm servers,再次執行第一步中代碼即可成功。

感謝田總的指導,田總金句“跟你講多少遍也不如自己試一遍“

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章