Отключение PowerShell от службы Windows - программирование
Подтвердить что ты не робот

Отключение PowerShell от службы Windows

У меня есть служба Windows, которая регулярно запускает PowerShell script на удаленном компьютере с помощью WsManConnectionInfo/RunspaceFactory (в соответствии с шагами из этой статьи: Удаленное выполнение команд в PowerShell с использованием С#):

var connectionInfo = new WSManConnectionInfo(false, server, 5985, "/wsman",
                                             "http://schemas.microsoft.com/powershell/Microsoft.PowerShell",
                                             cred)
                        {
                            OperationTimeout = 4*60*1000,
                            OpenTimeout = 1*60*1000
                        };
using (var runSpace = RunspaceFactory.CreateRunspace(connectionInfo))
{
    runSpace.Open();
    using (var p = runSpace.CreatePipeline())
    {
        p.Commands.AddScript(script);
        var output = p.Invoke();
        ...
    }
}

Теперь, если я запускаю службу Windows самостоятельно с учетной записью администратора, все хорошо. Но если я запустил службу с учетной записью LocalSystem, я получаю следующее исключение:

System.Management.Automation.Remoting.PSRemotingTransportException:
    Connecting to remote server NOSRVDEV02 failed with the following error message :
        WinRM cannot process the request. The following error with
        errorcode 0x8009030d occurred while using Negotiate authentication:
        A specified logon session does not exist. It may already have been terminated.

    Possible causes are:
        -The user name or password specified are invalid.
        -Kerberos is used when no authentication method and no user name are specified.
        -Kerberos accepts domain user names, but not local user names.
        -The Service Principal Name (SPN) for the remote computer name and port does not exist.
        -The client and remote computers are in different domains and there is no trust between the two domains.

    After checking for the above issues, try the following:
        -Check the Event Viewer for events related to authentication.
        -Change the authentication method; add the destination computer to the WinRM TrustedHosts configuration setting or use HTTPS transport.
         Note that computers in the TrustedHosts list might not be authenticated.
        -For more information about WinRM configuration, run the following command: winrm help config. For more information, see the about_Remote_Troubleshooting Help topic.

    at System.Management.Automation.Runspaces.AsyncResult.EndInvoke()
    at System.Management.Automation.Runspaces.Internal.RunspacePoolInternal.EndOpen(IAsyncResult asyncResult)
    at System.Management.Automation.RemoteRunspace.Open()
    ...

Примечание. Это не имеет ничего общего с учетными данными в WsManConnectionInfo - только параметры учетной записи на вкладке "Вход в систему".

Я не хочу предоставлять привилегии администратора службы. Любые идеи, почему пользователь LocalSystem не смог войти в систему?

Дополнительная информация:

  • Удаленный компьютер не является членом домена.
  • Я попытался подключиться как по IP-адресу, так и по имени хоста (оба указаны на локальном компьютере TrustedHosts).

EDIT: Еще больше информации (резюме комментариев):

  • Локальный компьютер: Windows 7 Ultimate 64bit (виртуальная машина в окне Windows 8).
  • Удаленный компьютер: Windows Server 2008R2 Datacenter 64bit.
  • Основной причиной, по которой мы не хотим менять учетные записи пользователей службы, является то, что это обновление старой службы, которая уже развернута на многих клиентах (клиентах).
  • Служба также обращается к реестру Windows и файловой системе на локальном компьютере, поэтому установка учетной записи пользователя на что-то более ограниченное, например NetworkService, просто откроет другую банку червей.
4b9b3361

Ответ 1

Довольно неожиданное решение для этого: имя пользователя в объекте PSCredential (cred) должно иметь префикс имени удаленного компьютера без домена, например. " MYREMOTESERVERNAME\имя_данного_имя", а не только " имя_отмена".

Я понятия не имею, почему префикс нужен только при подключении к учетной записи LocalSystem, хотя...