Как настроить удаленную PowerShell с использованием wsmanconnectioninfo в C# с помощью аутентификации сертификации?C#

Место общения программистов C#
Ответить Пред. темаСлед. тема
Anonymous
 Как настроить удаленную PowerShell с использованием wsmanconnectioninfo в C# с помощью аутентификации сертификации?

Сообщение Anonymous »

Я пытаюсь создать удаленную PowerShell (RPS), которая будет формировать соединение между машинами для выполнения команд RPS. У меня есть следующий пример настройки « hostpc с приложением C# Console (которое выполняет RPS) для формирования соединения между двумя удаленными ПК »
Следующая ссылка (сертификат (без пароля) аутентификация в WinRM) была обнаружена из одного из комментариев в ответе в отдельном вопросе. Из статьи автор представил подход на высоком уровне для создания аутентификации на основе пароля) в WINRM, и они являются следующими: < /p>
  • Настройка SSL-подключения к WinRM в конечной точке < /li>
    Создание сертификата пользователя, используемого для аутентификации < /li>
    . Он отключен по умолчанию для сервера Auth и включен на стороне клиента. < /Li>
    Добавьте сертификат пользователя и его сертификат CA в хранилище сертификата конечной точки < /li>
    Создать отображение пользователя в Winrm с отпечатками допуска выпуска на конечной точке. Следующее: < /p>
    Настройка аутентификации сертификата: < /h1>

    Настройка WinRM для работы с HTTPS в удаленных ПК < /li>
    Созданный сертификат клиента в hostpc < /li>
    Экспертировал сертификат клиента и импортировал его на реконструктуре < /li> < />> >. WinRM to enable the Certificate Authentication on the Remote PCs
  • Created Certificates in each Remote PC
  • Binded the Remote PC certificates to the HTTPS Listener
  • Created the winrm user mapping using the HostPC certificate in each Remote PC
настроил Winrm для работы с HTTPS < /em> < /p>

Код: Выделить всё

winrm quickconfig -transport:https
Создание сертификата

Код: Выделить всё

New-SelfSignedCertificate `
-DnsName 
 `
-CertStoreLocation  `
-KeyLength 2048 `
-NotAfter (Get-Date).AddYears(xx) `
-TextExtension @("2.5.29.37={text}")
Аутентификация сертификата

Код: Выделить всё

winrm set winrm/config/service/auth @{Certificate="true"}
Сертификат привязки с https alluster

Код: Выделить всё

winrm create winrm/config/Listener?Address=*+Transport=HTTPS "@{Hostname=";CertificateThumbprint="}"
Пользовательское отображение

Код: Выделить всё

New-Item -Path WSMan:\localhost\ClientCertificate `
-Subject '' `
-URI * `
-Issuer   `
-Credential (Get-Credential)
< /code>
 c# сторона приложения: < /h1>

connectionInfo = new WSManConnectionInfo(new Uri($"https://{MachineName}:5986/wsman"),
"http://schemas.microsoft.com/powershell/Microsoft.PowerShell", (PSCredential?)null);
connectionInfo.CertificateThumbprint = CertLoader.CertificateLoad(MachineName);


public string? CertificateLoad(string? machinename)
{
X509Store? store = null;
X509Certificate2? cert = null;

try
{
if(machinename == null)
{


return null;
}

store = new X509Store(, );
store.Open(OpenFlags.ReadOnly);
cert = store.Certificates.OfType().FirstOrDefault(c =>
c.Subject.Contains($"{machinename}", StringComparison.OrdinalIgnoreCase));
store.Close();
return cert.Thumbprint;
}
catch (Exception ex)
{

return null;
}
}



using (runspace = RunspaceFactory.CreateRunspace(connectioninfo))
{
runspace.Open();
using (pipeline = PowerShell.Create())
{
Тем не менее, он продолжает сбой, когда он попадает в использование (runspace = runspacefactory.createrunspace (connectionInfo)) со следующим сообщением об ошибке:

Код: Выделить всё

Exception Message: System.Management.Automation.PSInvalidOperationException:  The WS-Management service cannot find the certificate that was requested.
at System.Management.Automation.Remoting.Client.WSManClientSessionTransportManager.Initialize(Uri connectionUri, WSManConnectionInfo connectionInfo)
at System.Management.Automation.Remoting.Client.WSManClientSessionTransportManager..ctor(Guid runspacePoolInstanceId, WSManConnectionInfo connectionInfo, PSRemotingCryptoHelper cryptoHelper, String sessionName)
at System.Management.Automation.Runspaces.WSManConnectionInfo.CreateClientSessionTransportManager(Guid instanceId, String sessionName, PSRemotingCryptoHelper cryptoHelper)
at System.Management.Automation.Remoting.ClientRemoteSessionDSHandlerImpl..ctor(ClientRemoteSession session, PSRemotingCryptoHelper cryptoHelper, RunspaceConnectionInfo connectionInfo, URIDirectionReported uriRedirectionHandler)
at System.Management.Automation.Remoting.ClientRemoteSessionImpl..ctor(RemoteRunspacePoolInternal rsPool, URIDirectionReported uriRedirectionHandler)
at System.Management.Automation.Internal.ClientRunspacePoolDataStructureHandler.CreateClientRemoteSession(RemoteRunspacePoolInternal rsPoolInternal)
at System.Management.Automation.Internal.ClientRunspacePoolDataStructureHandler..ctor(RemoteRunspacePoolInternal clientRunspacePool, TypeTable typeTable)
at System.Management.Automation.Runspaces.Internal.RemoteRunspacePoolInternal.CreateDSHandler(TypeTable typeTable)
at System.Management.Automation.Runspaces.Internal.RemoteRunspacePoolInternal..ctor(Int32 minRunspaces, Int32 maxRunspaces, TypeTable typeTable, PSHost host, PSPrimitiveDictionary applicationArguments, RunspaceConnectionInfo connectionInfo, String name)
at System.Management.Automation.Runspaces.RunspacePool..ctor(Int32 minRunspaces, Int32 maxRunspaces, TypeTable typeTable, PSHost host, PSPrimitiveDictionary applicationArguments, RunspaceConnectionInfo connectionInfo, String name)
at System.Management.Automation.RemoteRunspace..ctor(TypeTable typeTable, RunspaceConnectionInfo connectionInfo, PSHost host, PSPrimitiveDictionary applicationArguments, String name, Int32 id)
at System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(RunspaceConnectionInfo connectionInfo, PSHost host, TypeTable typeTable, PSPrimitiveDictionary applicationArguments, String name)
at System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(RunspaceConnectionInfo connectionInfo, PSHost host, TypeTable typeTable)
at System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(PSHost host, RunspaceConnectionInfo connectionInfo)
at System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(RunspaceConnectionInfo connectionInfo)
Кроме того, (я не могу вспомнить, что я сделал), прежде чем я получил ошибку выше, он не удался в runspace.open (); часть со следующим сообщением:
System.Management.Automation.Remoting.PSRemotingTransportException: 'Connecting to remote server xxxxxxxxx failed with the following error message :
WS-Management cannot process the request.
The operation failed because of an HTTP error.
The HTTP error (12186) is: The client certificate credentials were not recognized. . For more information, see the about_Remote_Troubleshooting Help topic.'
< /code>
Итак, может ли кто -нибудь помочь мне: < /p>

Определить, что я сделал неправильно? < /li>
понимать, как исправить эти сообщения об ошибках?>

Подробнее здесь: https://stackoverflow.com/questions/796 ... using-cert
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «C#»