我希望使用ASP.NET将PowerShell从Windows 7远程连接到Windows Server 2008 R2(安装在VMware中)。
这是我的代码:
string shell = "http://schemas.microsoft.com/powershell/Microsoft.PowerShell";
var target = new Uri("http://win-qkheb9s51i8/wsman");
Pipeline p = runSpace.CreatePipeline();
SecureString passing = new SecureString();
string password = "A123456a";
foreach (char c in password)
{
passing.AppendChar(c);
}
passing.MakeReadOnly();
var cred = new PSCredential(@"win-qkheb9s51i8\Administrator", passing);
var connectionInfo = new WSManConnectionInfo(target, shell, cred);
connectionInfo.OperationTimeout = 4 * 60 * 1000; // 4 minutes.
connectionInfo.OpenTimeout = 1 * 60 * 1000;
runSpace = RunspaceFactory.CreateRunspace(connectionInfo);
runSpace.Open();
但在runSpace.open()中有时会出现此错误
连接到远程服务器失败,并显示以下错误消息: 访问被拒绝。有关更多信息,请参阅 about_Remote_Troubleshooting帮助主题。
有时这个错误:
错误:客户端无法连接到指定的目标 请求。验证目标上的服务是否正在运行 接受请求。
我看了about_Remote_Troubleshooting
,但我看不出为什么会出现这些错误。任何人都可以帮助我吗?
答案 0 :(得分:1)
好的,所以你说两台机器都在SAME域上,但我看到你正在尝试使用本地管理员帐户。这可能是一个问题,但不一定。为了复制这一点,我在VM上设置了Win2k8R2,并按照以下步骤操作:
步骤#1和2适用于Server 2008 R2核心安装。如果您已完成安装,请跳至#3。
然后我拿了你的示例代码,我没有真正做出任何实质性的修改
Console.Write("Target: ");
var target = Console.ReadLine();
Console.Write("User: ");
var user = Console.ReadLine();
user = string.Format("{0}\\{1}", target, user);
string shell = "http://schemas.microsoft.com/powershell/Microsoft.PowerShell";
var targetWsMan = new Uri(string.Format("http://{0}:5985/wsman", target));
using (var passing = new SecureString())
{
Console.Write("Password: ");
var cki = default(ConsoleKeyInfo);
do
{
cki = Console.ReadKey(true);
if (cki.Key == ConsoleKey.Enter)
Console.Write(cki.KeyChar);
else
passing.AppendChar(cki.KeyChar);
}
while (cki.Key != ConsoleKey.Enter);
passing.MakeReadOnly();
var cred = new PSCredential(user, passing);
var connectionInfo = new WSManConnectionInfo(targetWsMan, shell, cred);
connectionInfo.OperationTimeout = 4 * 60 * 1000; // 4 minutes.
connectionInfo.OpenTimeout = 1 * 60 * 1000;
using (var runSpace = RunspaceFactory.CreateRunspace(connectionInfo))
{
var p = runSpace.CreatePipeline();
runSpace.Open();
Console.WriteLine("Connected to {0}", targetWsMan);
Console.WriteLine("As {0}", user);
Console.Write("Command to run: ");
var cmd = Console.ReadLine();
p.Commands.Add(cmd);
var returnValue = p.Invoke();
foreach (var v in returnValue)
Console.WriteLine(v.ToString());
}
}
Console.WriteLine("End...");
Console.ReadLine();
我确实添加了对C:\Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0\System.Management.Automation.dll
的dll引用,以防它不是你正在使用的。
然后它奏效了。所以我的感觉是它不是你的代码,而是你的凭据,或目标机器上的远程设置。