windows 使用PSCredential对象以非交互方式验证命令

z9smfwbn  于 2023-03-19  发布在  Windows
关注(0)|答案(2)|浏览(84)

我正在使用PSCredential对象对一个命令进行身份验证,我需要以不同用户的身份运行该命令。

> whoami
dmn1\srveikafka
> $secpasswd = ConvertTo-SecureString "mypassword" -AsPlainText -Force
> $mycreds = New-Object System.Management.Automation.PSCredential ("srveizookeeper", $secpasswd)
>
> $sess = new-pssession -computername remotecomputer.xyz.com -credential $mycreds
> invoke-command -session $sess -scriptblock {whoami}
dmn1\srveizookeeper

但是当我把这些相同的命令作为powershell脚本运行时,我得到了这个错误。

new-pssession : [remotecomputer.xyz.com] Connecting to remote server remotecomputer.xyz.com failed with the following
error message : Access is denied. For more information, see the about_Remote_Troubleshooting Help topic.
At C:\workstation\add_zookeeper_spn.ps1:13 char:9
+ $sess = new-pssession -computername remotecomputer.xyz.com -credential $mycreds
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotin
   gTransportException
    + FullyQualifiedErrorId : AccessDenied,PSSessionOpenFailed
Invoke-Command : Cannot validate argument on parameter 'Session'. The argument is null or empty. Provide an argument
that is not null or empty, and then try the command again.
At C:\workstation\add_zookeeper_spn.ps1:14 char:25
+ invoke-command -session $sess -scriptblock {whoami}
+                         ~~~~~
    + CategoryInfo          : InvalidData: (:) [Invoke-Command], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeCommandCommand

我有没有搞错或遗漏什么?

vxqlmq5t

vxqlmq5t1#

您可能需要将域作为用户名的一部分包含在凭据构造函数中:

$mycreds = New-Object System.Management.Automation.PSCredential ("dmn1\srveizookeeper", $secpasswd)
ig9co6j1

ig9co6j12#

如果要连接到远程计算机而不弹出任何凭据窗口

Enable-PSRemoting -Force -Verbose

Set-WsManQuickConfig

winrm set winrm/config/client '@{TrustedHosts="your-remote-Ip"}'

Restart-Service WinRM

$secpasswd = ConvertTo-SecureString "remote-password" -AsPlainText -Force

$mycreds = New-Object System.Management.Automation.PSCredential("your-remote-ip\remote-username", $secpasswd)

从您的计算机进入远程服务器

$Session = New-PSSession -ComputerName your-remote-ip -Credential $mycreds
Enter-PSSession $Session

相关问题