我有一个使用 Plink ssh 的 powershell 脚本。该脚本有效,但我需要让它通过 C# 和 WMI 工作
powershell 脚本的问题行是 c:/temp/plink.exe -ssh user1@192.168.60.202 -pw password1
当我尝试通过 WMI 使用它时,我收到错误“服务器的主机密钥未缓存在注册表中......”
我需要与 WMIEndpoint 对应的主机密钥吗?为 WMI 终结点创建必要密钥的步骤是什么?
下面是重现问题的控制台应用程序的代码
private static SecureString ConvertToSecureString(string s)
{
var ss = new SecureString();
foreach (var passChar in s) ss.AppendChar(passChar);
return ss;
}
private static void RunScriptAsPrivilegedAccount(string userAndDomain, string privilegedPassword, string endPointUrl, string script)
{
var ss = ConvertToSecureString(privilegedPassword);
var psCredential =
new PSCredential(userAndDomain, ss);
var winRmEndpoint = new Uri(endPointUrl);
var connectionInfo = new WSManConnectionInfo(winRmEndpoint,
"http://schemas.microsoft.com/powershell/Microsoft.PowerShell", psCredential);
using (var runspace = RunspaceFactory.CreateRunspace(connectionInfo))
{
using (var powershell = PowerShell.Create())
{
runspace.Open();
powershell.Runspace = runspace;
powershell.AddScript(script);
powershell.Invoke();
if((powershell.Streams.Error.Count > 0))
{
string errorMessage = String.Join(",",powershell.Streams.Error.Select(
x => x.Exception.Message).ToArray());
throw new ApplicationException(errorMessage);
}
}
}
}
static void Main(string[] args)
{
RunScriptAsPrivilegedAccount(
"AdminAccount@myDomain.com",
"adminPwd",
"http://localhost:5985/wsman",
"c:/temp/plink.exe -ssh user1@192.168.60.202 -pw password1");
try
{
Console.Write("Success");
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
}