我们正在尝试结合使用 Azure 服务总线队列和 Azure 辅助角色来自动化大量的 azure/服务维护任务。简而言之,概念如下......
- 维护任务已发布到 SB 队列
- 辅助角色监听 SB 队列上的任务
- 辅助角色连接到所需的虚拟机/Web 角色/云服务并执行远程 Powershell 命令
实际上,在开发环境中操作时,这可以按预期工作,但是在发布辅助角色后,远程 powershell 连接失败,并显示“访问被拒绝”响应。建立连接的代码如下...
PSCredential cred = new PSCredential(config.Username, config.PrimaryPassword);
WSManConnectionInfo connection = new WSManConnectionInfo(true, config.PrimaryServer, 5986, "/wsman", "http://schemas.microsoft.com/powershell/Microsoft.PowerShell", cred);
using (Runspace runspace = RunspaceFactory.CreateRunspace(connection))
{
runspace.Open();
using (PowerShell shell = PowerShell.Create())
{
shell.Runspace = runspace;
// DO SOMETHING HERE
shell.Invoke();
}
runspace.Close();
}
最初,我怀疑这是 CA 证书问题,但后来我通过 RDP 连接到辅助角色,并确认证书已正确部署。此外,我还设法通过“winrs -r:”命令(也使用远程桌面连接)实现与目标服务器的连接。
作为确认,辅助角色也在以提升的权限运行。
如有任何帮助,我们将不胜感激
提前致谢
最佳答案
经过大量实验,Runspace.Open() 命令似乎需要在具有管理访问权限的帐户下运行(使用提升的权限运行辅助角色无法实现此目的),因此,为了解决该问题,我执行了以下操作...
通过角色上的启动任务,我使用以下命令创建了一个帐户...
net user roleusername rolepassword /add
net localgroup Administrators roleusername /add
exit /B 0
然后,我使用以下代码模拟该用户,以确保该角色作为新创建的本地管理员帐户运行。
[DllImport("advapi32.DLL", SetLastError = true)]
public static extern int LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);
[DllImport("advapi32.DLL")]
public static extern bool ImpersonateLoggedOnUser(IntPtr hToken);
[DllImport("advapi32.DLL")]
public static extern bool RevertToSelf();
public static object Impersonate(string username, string password)
{
string domainname = ".";
if (username.Contains(@"\"))
{
domainname = username.Substring(0, username.IndexOf(@"\"));
username = username.Substring(username.IndexOf(@"\") + 1);
}
IntPtr securityToken;
LogonUser(username, domainname, password, 9, 0, out securityToken);
if (securityToken != IntPtr.Zero)
{
var newIdentity = new WindowsIdentity(securityToken);
WindowsImpersonationContext impersonationContext = newIdentity.Impersonate();
return impersonationContext;
}
throw new InvalidOperationException("The username or password combination was invalid, please verify your settings");
}
public static void UndoImpersonation(object impersonationContext)
{
var context = impersonationContext as WindowsImpersonationContext;
if (context != null) context.Undo();
}
我希望这可以帮助其他遇到同样问题的人。
关于c# - 从 Azure 辅助角色建立 WSManConnection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28025969/