c#でwinrmにアクセスする方法
-
04-10-2019 - |
質問
WMIとは対照的に、WinRMを使用してシステム情報(win32_blablabla)を収集できる小さなアプリケーションを作成したいと思います。 C#からそれを行うにはどうすればよいですか?
主な目標は、DCOM(WMI)とは対照的に、WS-Man(WinRM)を使用することです。
解決
最も簡単な方法は、WSMANオートメーションを使用することだと思います。プロジェクトのWindwos System32からのwsmauto.dll:
次に、以下のコードはあなたのために機能するはずです。 APIの説明はこちらです: MSDN:WinRM C ++ API
IWSMan wsman = new WSManClass();
IWSManConnectionOptions options = (IWSManConnectionOptions)wsman.CreateConnectionOptions();
if (options != null)
{
try
{
// options.UserName = ???;
// options.Password = ???;
IWSManSession session = (IWSManSession)wsman.CreateSession("http://<your_server_name>/wsman", 0, options);
if (session != null)
{
try
{
// retrieve the Win32_Service xml representation
var reply = session.Get("http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Service?Name=winmgmt", 0);
// parse xml and dump service name and description
var doc = new XmlDocument();
doc.LoadXml(reply);
foreach (var elementName in new string[] { "p:Caption", "p:Description" })
{
var node = doc.GetElementsByTagName(elementName)[0];
if (node != null) Console.WriteLine(node.InnerText);
}
}
finally
{
Marshal.ReleaseComObject(session);
}
}
}
finally
{
Marshal.ReleaseComObject(options);
}
}
これが役立つことを願っています
他のヒント
.netからwinrmを介してpowershellを実行する簡単な方法を説明する記事があります http://getthinktank.com/2015/06/22/naos-winrm-windows-remote-management-through-net/.
コピーをコピーするだけで、コードは単一のファイルにあり、System.management.automationへの参照を含むNugetパッケージでもあります。
Autoは、信頼できるホストを管理し、スクリプトブロックを実行し、ファイルを送信することもできます(実際にはサポートされていませんが、作業を作成しました)。リターンは常にPowerShellの生のオブジェクトです。
// this is the entrypoint to interact with the system (interfaced for testing).
var machineManager = new MachineManager(
"10.0.0.1",
"Administrator",
MachineManager.ConvertStringToSecureString("xxx"),
true);
// will perform a user initiated reboot.
machineManager.Reboot();
// can run random script blocks WITH parameters.
var fileObjects = machineManager.RunScript(
"{ param($path) ls $path }",
new[] { @"C:\PathToList" });
// can transfer files to the remote server (over WinRM's protocol!).
var localFilePath = @"D:\Temp\BigFileLocal.nupkg";
var fileBytes = File.ReadAllBytes(localFilePath);
var remoteFilePath = @"D:\Temp\BigFileRemote.nupkg";
machineManager.SendFile(remoteFilePath, fileBytes);
これが役立つことを願っています、私は自動化された展開でこれをしばらく使用してきました。問題が見つかった場合はコメントを残してください。
これは、Visual Studio 2010でデフォルトでイントロップエラーを示していることに注意したいと思います。
CF http://blogs.msdn.com/b/mshneer/archive/2009/12/07/interop-type-xxx-cannot-be-embedded-use-the-applable-interface-instead.aspx
これを解決する2つの方法があるようです。これは最初に上記の記事に文書化されており、問題を処理する正しい方法であると思われます。この例に適した変更は次のとおりです。
wsman wsmanobject = new wsman();これは、iwsman wsman = new wsmanclass()の代わりにです。エラーがスローされます。
2番目の解決策は、VS2010(> Solution Explorer—> Solution—> Project—>参照とWSMANAUTOMATIONを選択することです。右クリックするか、Alt-Enterを押してプロパティにアクセスします。 WSMAUTOリファレンスの「埋め込み型インターポップ型」プロパティの値を変更します。