Plink与WMI出错

时间:2013-10-31 18:58:31

标签: powershell ssh wmi plink

我有一个使用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);
            }
        } 

1 个答案:

答案 0 :(得分:0)

Y中的管道做了伎俩

这条线现在是Y | c:/temp/plink.exe -ssh user1@192.168.60.202 -pw password1