2014年3月24日 星期一

[教學]HyperV setup for remote management


從Window 2012 Server 開始 Hyper-V 的管理介面就被獨立出來,如果要管理通常的作法有兩種:
  • 在Windows8 裝Hyper-V Manager 遠端管理Window 2012 上的Hyper-V Server
  • 透過WMI API 去管理 Window 2012 上的 Hyper-V Server
不過如果要開啟遠端管理的權限,則需要作很多複雜的設定,可以參考以下兩篇文章:

1. 安裝HVRemote 來設定 - Hyper-V Remote Management Configuration Utility (HVRemote)
2. 手動開啟Window 2012 的管理權限 -  Admin Guide 2. Cloud Node. Hyper-V


不過還好第二篇文章也佛心來著把所有複雜的設定指令都寫成script (change_registry.ps1),之後就可以利用Administorator 的權限開啟遠端管理的功能,指令source code 如下:



#
# Script to change registry key owners and registry values
# to match required values to work with Abiquo
#
# Author: Sergio Pena
# Date: 07.23.2013
#
# Changelog.
# 07.23.2013    Added interactivity so it request user data.        
#
#

$username = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
$me = [System.Security.Principal.NTAccount]"$username"

#
# Hack to be able to take ownership of registry keys
#

function enable-privilege {
 param(
  ## The privilege to adjust. This set is taken from
  ## http://msdn.microsoft.com/en-us/library/bb530716(VS.85).aspx
  [ValidateSet(
   "SeAssignPrimaryTokenPrivilege", "SeAuditPrivilege", "SeBackupPrivilege",
   "SeChangeNotifyPrivilege", "SeCreateGlobalPrivilege", "SeCreatePagefilePrivilege",
   "SeCreatePermanentPrivilege", "SeCreateSymbolicLinkPrivilege", "SeCreateTokenPrivilege",
   "SeDebugPrivilege", "SeEnableDelegationPrivilege", "SeImpersonatePrivilege", "SeIncreaseBasePriorityPrivilege",
   "SeIncreaseQuotaPrivilege", "SeIncreaseWorkingSetPrivilege", "SeLoadDriverPrivilege",
   "SeLockMemoryPrivilege", "SeMachineAccountPrivilege", "SeManageVolumePrivilege",
   "SeProfileSingleProcessPrivilege", "SeRelabelPrivilege", "SeRemoteShutdownPrivilege",
   "SeRestorePrivilege", "SeSecurityPrivilege", "SeShutdownPrivilege", "SeSyncAgentPrivilege",
   "SeSystemEnvironmentPrivilege", "SeSystemProfilePrivilege", "SeSystemtimePrivilege",
   "SeTakeOwnershipPrivilege", "SeTcbPrivilege", "SeTimeZonePrivilege", "SeTrustedCredManAccessPrivilege",
   "SeUndockPrivilege", "SeUnsolicitedInputPrivilege")]
  $Privilege,
  ## The process on which to adjust the privilege. Defaults to the current process.
  $ProcessId = $pid,
  ## Switch to disable the privilege, rather than enable it.
  [Switch] $Disable
 )

 ## Taken from P/Invoke.NET with minor adjustments.
 $definition = @'
 using System;
 using System.Runtime.InteropServices;
  
 public class AdjPriv
 {
  [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
  internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall,
   ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);
  
  [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
  internal static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok);
  [DllImport("advapi32.dll", SetLastError = true)]
  internal static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);
  [StructLayout(LayoutKind.Sequential, Pack = 1)]
  internal struct TokPriv1Luid
  {
   public int Count;
   public long Luid;
   public int Attr;
  }
  
  internal const int SE_PRIVILEGE_ENABLED = 0x00000002;
  internal const int SE_PRIVILEGE_DISABLED = 0x00000000;
  internal const int TOKEN_QUERY = 0x00000008;
  internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
  public static bool EnablePrivilege(long processHandle, string privilege, bool disable)
  {
   bool retVal;
   TokPriv1Luid tp;
   IntPtr hproc = new IntPtr(processHandle);
   IntPtr htok = IntPtr.Zero;
   retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
   tp.Count = 1;
   tp.Luid = 0;
   if(disable)
   {
    tp.Attr = SE_PRIVILEGE_DISABLED;
   }
   else
   {
    tp.Attr = SE_PRIVILEGE_ENABLED;
   }
   retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);
   retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
   return retVal;
  }
 }
'@

 $processHandle = (Get-Process -id $ProcessId).Handle
 $type = Add-Type $definition -PassThru
 $type[0]::EnablePrivilege($processHandle, $Privilege, $Disable)
}

enable-privilege SeTakeOwnershipPrivilege 

#
# Take ownership of registry Key
# HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID\{76A64158-CB41-11D1-8B02-00600806D9B6}
#
$key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey("SOFTWARE\\CLASSES\\CLSID\\{76A64158-CB41-11D1-8B02-00600806D9B6}",[Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree,[System.Security.AccessControl.RegistryRights]::takeownership)
Write-Host "Key Opened: $key"
# You must get a blank acl for the key b/c you do not currently have access
$acl = $key.GetAccessControl([System.Security.AccessControl.AccessControlSections]::None)
$acl.SetOwner($me)
$key.SetAccessControl($acl)
$key.Close()

#
# Take ownership of registry Key
# HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID\{76A64158-CB41-11D1-8B02-00600806D9B6}\InProcServer32
#
$key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey("SOFTWARE\\CLASSES\\CLSID\\{76A64158-CB41-11D1-8B02-00600806D9B6}\\InProcServer32",[Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree,[System.Security.AccessControl.RegistryRights]::takeownership)
Write-Host "Key Opened: $key"
$acl = $key.GetAccessControl([System.Security.AccessControl.AccessControlSections]::None)
$acl.SetOwner($me)
$key.SetAccessControl($acl)
$key.Close()

#
# Take ownership of registry Key 
# HKEY_LOCAL_MACHINE \SOFTWARE\Classes\AppID\{76A64158-CB41-11D1-8B02-00600806D9B6}
#
$key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey("SOFTWARE\\CLASSES\\AppID",[Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree,[System.Security.AccessControl.RegistryRights]::takeownership)
Write-Host "Key Opened: $key"
$acl = $key.GetAccessControl([System.Security.AccessControl.AccessControlSections]::None)
$acl.SetOwner($me)
$key.SetAccessControl($acl)
$key.Close()


#
# Give Full control on RegKey
# HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID\{76A64158-CB41-11D1-8B02-00600806D9B6}
# 
$key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey("SOFTWARE\\CLASSES\\CLSID\\{76A64158-CB41-11D1-8B02-00600806D9B6}", [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree,[System.Security.AccessControl.RegistryRights]::ChangePermissions)
Write-Host "Key Opened: $key"
$acl = $key.GetAccessControl()
$RegRights = [System.Security.AccessControl.RegistryRights]::FullControl
$Inherit  = "ContainerInherit,ObjectInherit"
$Propagation = "None"
$Type = [System.Security.AccessControl.AccessControlType]::Allow
$rule = New-Object System.Security.AccessControl.RegistryAccessRule($me,$RegRights,$Inherit,$Propagation,$Type)
$acl.AddAccessRule($rule)
$key.SetAccessControl($acl)
$key.Close()

#
# Give Full control on RegKey
# HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID\{76A64158-CB41-11D1-8B02-00600806D9B6}\InProcServer32
# 
$key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey("SOFTWARE\\CLASSES\\CLSID\\{76A64158-CB41-11D1-8B02-00600806D9B6}\\InProcServer32", [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree,[System.Security.AccessControl.RegistryRights]::ChangePermissions)
Write-Host "Key Opened: $key"
$acl = $key.GetAccessControl()
$RegRights = [System.Security.AccessControl.RegistryRights]::FullControl
$Inherit  = "ContainerInherit,ObjectInherit"
$Propagation = "None"
$Type = [System.Security.AccessControl.AccessControlType]::Allow
$rule = New-Object System.Security.AccessControl.RegistryAccessRule($me,$RegRights,$Inherit,$Propagation,$Type)
$acl.AddAccessRule($rule)
$key.SetAccessControl($acl)
$key.Close()

#
# Give Full control on RegKey
# HKEY_LOCAL_MACHINE\SOFTWARE\Classes\AppID\{76A64158-CB41-11D1-8B02-00600806D9B6}
# 
$key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey("SOFTWARE\\CLASSES\\AppID", [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree,[System.Security.AccessControl.RegistryRights]::ChangePermissions)
Write-Host "Key Opened: $key"
$acl = $key.GetAccessControl()
$RegRights = [System.Security.AccessControl.RegistryRights]::FullControl
$Inherit = "ContainerInherit,ObjectInherit"
$Propagation = "None"
$Type = [System.Security.AccessControl.AccessControlType]::Allow
$rule = New-Object System.Security.AccessControl.RegistryAccessRule($me,$RegRights,$Inherit,$Propagation,$Type)
$acl.AddAccessRule($rule)
$key.SetAccessControl($acl)
$key.Close()

#
# INCLUDE REGISTRY VALUES
#

# [HKEY_CLASSES_LOCAL_MACHINE\AppID\{76A64158-CB41-11D1-8B02-00600806D9B6}]
# "DllSurrogate"=""

New-Item HKLM:\SOFTWARE\Classes\AppID\`{76A64158-CB41-11D1-8B02-00600806D9B6`}
Set-ItemProperty HKLM:\SOFTWARE\Classes\AppID\`{76A64158-CB41-11D1-8B02-00600806D9B6`} -Name DllSurrogate -Value ''

# [HKEY_CLASSES_LOCAL_MACHINE\CLSID\{76A64158-CB41-11D1-8B02-00600806D9B6}]
# @="WBEM Scripting Locator"
# "AppID"="{76a64158-cb41-11d1-8b02-00600806d9b6}"

Set-ItemProperty HKLM:\SOFTWARE\Classes\CLSID\`{76A64158-CB41-11D1-8B02-00600806D9B6`} -Name '(default)' -Value 'WBEM Scripting Locator'
Set-ItemProperty HKLM:\SOFTWARE\Classes\CLSID\`{76A64158-CB41-11D1-8B02-00600806D9B6`} -Name 'AppID' -Value '{76A64158-cb41-11d1-8b02-00600806d9b6}'

# [HKEY_CLASSES_LOCAL_MACHINE\CLSID\{76A64158-CB41-11D1-8B02-00600806D9B6}\InProcServer32]
#@=hex(2):25,00,53,00,79,00,73,00,74,00,65,00,6d,00,52,00,6f,00,6f,00,74,00,25,  00,5c,00,73,00,79,00,73,00,74,00,65,00,6d,00,33,00,32,00,5c,00,77,00,62,00,  65,00,6d,00,5c,00,77,00,62,00,65,00,6d,00,64,00,69,00,73,00,70,00,2e,00,64,  00,6c,00,6c,00,00,00
#"ThreadingModel"="Both"
# I think this property is not really necessary
#Set-ItemProperty HKLM:\SOFTWARE\Classes\CLSID\`{76A64158-CB41-11D1-8B02-00600806D9B6`}\InProcServer32 -Name '(default)' -Value ([byte[]](0x25,0x00,0x53,0x00,0x79,0x00,0x73,0x00,0x74,0x00,0x65,0x00,0x6d,0x00,0x52,0x00,0x6f,0x00,0x6f,0x00,0x74,0x00,0x25,0x00,0x5c,0x00,0x73,0x00,0x79,0x00,0x73,0x00,0x74,0x00,0x65,0x00,0x6d,0x00,0x33,0x00,0x32,0x00,0x5c,0x00,0x77,0x00,0x62,0x00,0x65,0x00,0x6d,0x00,0x5c,0x00,0x77,0x00,0x62,0x00,0x65,0x00,0x6d,0x00,0x64,0x00,0x69,0x00,0x73,0x00,0x70,0x00,0x2e,0x00,0x64,0x00,0x6c,0x00,0x6c,0x00,0x00,0x00))
Set-ItemProperty HKLM:\SOFTWARE\Classes\CLSID\`{76A64158-CB41-11D1-8B02-00600806D9B6`}\InProcServer32 -Name "ThreadingModel" -Value "Both"


不過Windows 真的讓人最無法理解的就是那寫registry Key,看倌們就自行驗證這些程式碼吧~

Ps. 如果無法執行這個程式碼,可能是權限不足的關係,請在power shell 執行以下指令:

 set-executionpolicy -executionpolicy unrestricted

或者你不想要權限全開,只要這次執行打開就好,請執行

powershell.exe -executionpolicy unrestricted -command .\change_registry.ps1
 
 

張貼留言