public long StartProgramInGuest(GuestProgramSpec guestProgramSpec) { //throw new NotImplementedException(); return(_vimService.StartProgramInGuest( _morProcessManager, //VimLib.VimServiceReference.ManagedObjectReference _this, _morVM, //VimLib.VimServiceReference.ManagedObjectReference vm, _NamePasswordAuthentication, //VimLib.VimServiceReference.GuestAuthentication auth, guestProgramSpec //VimLib.VimServiceReference.GuestProgramSpec spec )); }
private void RunProgramInGuest(VimService service, string vmKey, string username, string password, string programPath, string arguments) { var auth = new NamePasswordAuthentication { username = username, password = password, interactiveSession = false }; var vmRef = new ManagedObjectReference { type = "VirtualMachine", Value = vmKey }; var progSpec = new GuestProgramSpec { programPath = programPath, arguments = arguments }; var processMgr = new ManagedObjectReference { type = "GuestProcessManager", Value = "guestOperationsProcessManager" }; var result = service.StartProgramInGuest(processMgr, vmRef, auth, progSpec); }
/// <summary> /// Runs a guest process in the specified virtual machine. /// </summary> /// <param name="vmObject">The <see cref="VSphereManagedObject" /> representing the virtual machine.</param> /// <param name="fileName">The file name of the application to run.</param> /// <param name="arguments">The command-line arguments to pass to the application when the process starts.</param> /// <param name="credential">The credential to run the process as.</param> /// <param name="waitForExit">if set to <c>true</c> wait for the process to exit before returning.</param> /// <returns>The ID of the guest process that was started.</returns> /// <exception cref="ArgumentNullException"> /// <paramref name="vmObject" /> is null. /// <para>or</para> /// <paramref name="credential" /> is null. /// </exception> public long RunVirtualMachineGuestProcess(VSphereManagedObject vmObject, string fileName, string arguments, NetworkCredential credential, bool waitForExit) { if (vmObject == null) { throw new ArgumentNullException(nameof(vmObject)); } if (credential == null) { throw new ArgumentNullException(nameof(credential)); } VSpherePropertySpec spec = new VSpherePropertySpec(VSphereManagedObjectType.GuestOperationsManager, "processManager"); VSphereManagedObject guestOperationsManager = RetrieveObject(new VSphereManagedObject(_serviceContent.guestOperationsManager), spec); var processManager = (ManagedObjectReference)guestOperationsManager.Properties["processManager"]; NamePasswordAuthentication auth = new NamePasswordAuthentication { username = BuildUserName(credential), password = credential.Password, interactiveSession = true }; GuestProgramSpec guestProgram = new GuestProgramSpec { programPath = fileName, arguments = arguments }; long processId = _vimService.StartProgramInGuest(processManager, vmObject.ManagedObjectReference, auth, guestProgram); if (waitForExit) { while (true) { var processInfo = _vimService.ListProcessesInGuest(processManager, vmObject.ManagedObjectReference, auth, new[] { processId }).FirstOrDefault(); if (processInfo?.exitCodeSpecified == true) { break; } Thread.Sleep(TimeSpan.FromSeconds(1)); } } return(processId); }
public override IAsyncExecutionResult startExecutableAsync(string toExecute, string args, string workingDir = null) { string tempDir = String.Format("C:\\users\\{0}\\", _spec.kernelVMUsername); if (workingDir == null) { workingDir = tempDir; } execFileSet fileSet = prepareForExecution(toExecute, args, tempDir); NamePasswordAuthentication auth = new NamePasswordAuthentication { Username = _spec.kernelVMUsername, Password = _spec.kernelVMPassword, InteractiveSession = true }; VimClientImpl _vClient = conn.getConnection(); VirtualMachine _underlyingVM = conn.getMachine(); GuestOperationsManager gom = (GuestOperationsManager)_vClient.GetView(_vClient.ServiceContent.GuestOperationsManager, null); GuestAuthManager guestAuthManager = (GuestAuthManager)_vClient.GetView(gom.AuthManager, null); guestAuthManager.ValidateCredentialsInGuest(_underlyingVM.MoRef, auth); GuestProcessManager guestProcessManager = _vClient.GetView(gom.ProcessManager, null) as GuestProcessManager; GuestProgramSpec progSpec = new GuestProgramSpec { ProgramPath = fileSet.launcherPath, Arguments = "", WorkingDirectory = workingDir }; guestProcessManager.StartProgramInGuest(_underlyingVM.MoRef, auth, progSpec); return(new asyncExecutionResultViaFile(this, fileSet)); }
public int RunProcess( string executable, string args, bool waitForExit = false ) { GuestProcessManager processManager = new GuestProcessManager( _virtualHost, _manager.ProcessManager ); GuestProgramSpec arguments = new GuestProgramSpec { Arguments = args, ProgramPath = executable, WorkingDirectory = Path.GetDirectoryName( executable ) }; long pid = processManager.StartProgramInGuest( _vm.MoRef, _authentication, arguments ); int exitCode = 0; if ( waitForExit ) { while ( true ) { GuestProcessInfo process = processManager.ListProcessesInGuest( _vm.MoRef, _authentication, new[] {pid} ) .FirstOrDefault( p => p.Pid == pid ); if ( process == null || process.EndTime != null ) { if ( process != null && process.ExitCode.HasValue ) { exitCode = process.ExitCode.Value; } break; } Thread.Sleep( 60000 ); processManager.UpdateViewData(); } } return exitCode; }
public int StartProcessAndWaitForExit( string processLocationInVm, string arguments ) { GuestProcessManager processManager = new GuestProcessManager( _virtualMachine.Client, _manager.ProcessManager ); GuestProgramSpec args = new GuestProgramSpec { Arguments = arguments, ProgramPath = processLocationInVm, WorkingDirectory = Path.GetDirectoryName( processLocationInVm ) }; long pid = processManager.StartProgramInGuest( _virtualMachine.MoRef, _authentication, args ); int exitCode = 0; while ( true ) { GuestProcessInfo process = processManager.ListProcessesInGuest( _virtualMachine.MoRef, _authentication, new[] {pid} ) .FirstOrDefault( p => p.Pid == pid ); if ( process == null || process.EndTime != null ) { if ( process != null && process.ExitCode.HasValue ) { exitCode = process.ExitCode.Value; } break; } Thread.Sleep( 6000 ); processManager.UpdateViewData(); } return exitCode; }
public void StartProcess( string processLocationInVm, string arguments ) { GuestProcessManager processManager = new GuestProcessManager( _virtualMachine.Client, _manager.ProcessManager ); GuestProgramSpec args = new GuestProgramSpec { Arguments = arguments, ProgramPath = processLocationInVm, WorkingDirectory = Path.GetDirectoryName( processLocationInVm ) }; processManager.StartProgramInGuest( _virtualMachine.MoRef, _authentication, args ); }
//WIP for SSO auth /*private static byte[] GetSSPIToken(string packageName) * { * ClientCurrentCredential clientCred = null; * ClientContext client = null; * * ServerCurrentCredential serverCred = null; * ServerContext server = null; * * byte[] clientToken; * byte[] serverToken; * * SecurityStatus clientStatus; * * try * { * clientCred = new ClientCurrentCredential(packageName); * serverCred = new ServerCurrentCredential(packageName); * * Console.Out.WriteLine(clientCred.PrincipleName); * * client = new ClientContext( * clientCred, * serverCred.PrincipleName, ContextAttrib.Zero * ); * * server = new ServerContext( * serverCred, ContextAttrib.Zero * ); * * clientToken = null; * serverToken = null; * * clientStatus = client.Init(serverToken, out clientToken); * * * } * finally * { * if (server != null) * { * server.Dispose(); * } * * if (client != null) * { * client.Dispose(); * } * * if (clientCred != null) * { * clientCred.Dispose(); * } * * if (serverCred != null) * { * serverCred.Dispose(); * } * } * return clientToken; * }*/ static void ExecuteCommand(GuestAuthentication creds, string arguments, string programPath, string workingDirectory, bool output) { try { ManagedObjectReference processManager = GetProperty <ManagedObjectReference>(serviceContent.guestOperationsManager, "processManager"); var guestProgramSpec = new GuestProgramSpec() { arguments = arguments, programPath = programPath, workingDirectory = workingDirectory, }; if (output) { //Set file to receive output var outfile = Path.GetRandomFileName(); guestProgramSpec.arguments += @" > C:\Users\Public\" + outfile + @" 2>&1"; //Start the program and receive the PID back Log("[x] Attempting to run cmd with the following arguments: " + guestProgramSpec.arguments); Log(@"[x] Temporarily saving out to C:\Users\Public\" + outfile); long pid = vim.StartProgramInGuest(processManager, vm, creds, guestProgramSpec); //Display PID Log("[x] Process started with PID " + pid + " waiting for execution to finish"); bool finished = false; while (!finished) { //Get status of our process long[] pids = { pid }; GuestProcessInfo[] guestProcessInfo = vim.ListProcessesInGuest(processManager, vm, creds, pids); if (guestProcessInfo.Length == 0) { Log("Error retrieving status of the process, check for the existance of the output file manually"); } if (guestProcessInfo[0].exitCodeSpecified) { Log("[x] Execution finished, attempting to retrieve the results"); //Get the results var fileTransferInformation = vim.InitiateFileTransferFromGuest(guestFileManager, vm, creds, @"C:\Users\Public\" + outfile); using (var client = new System.Net.WebClient()) { client.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore); var results = client.DownloadString(fileTransferInformation.url); Log("[x] Output: "); Log(results); } //Delete the file vim.DeleteFileInGuest(guestFileManager, vm, creds, @"C:\Users\Public\" + outfile); Log("[x] Output file deleted"); finished = true; } } } else { //Start the program and receive the PID back Log("[x] Attempting to execute with cmd /c the following command: " + guestProgramSpec.arguments); long pid = vim.StartProgramInGuest(processManager, vm, creds, guestProgramSpec); //Display PID Log("[x] Process started with PID" + pid); } } catch (Exception fault) { Error(fault); } }
public static int MainFindVM(MainSearchVM_In inParam, MainSearchVM_Out outRet) { VmSummaryInfo vmSummaryInfo = new VmSummaryInfo(); System.Net.ServicePointManager.Expect100Continue = false; MyCertVerify certVerify = new MyCertVerify(); System.Net.ServicePointManager.ServerCertificateValidationCallback = certVerify.RemoteCertificateValidationCallback; BasicHttpBinding binding = null; if (string.Compare("https", inParam.Protocal, StringComparison.InvariantCultureIgnoreCase) == 0) { binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport) { AllowCookies = true, OpenTimeout = TimeSpan.FromHours(1), ReceiveTimeout = TimeSpan.FromHours(1), SendTimeout = TimeSpan.FromHours(1), CloseTimeout = TimeSpan.FromHours(1), MaxBufferPoolSize = 1024 * 1024 * 2, MaxReceivedMessageSize = 1024 * 512, MaxBufferSize = 1024 * 512 }; } else { binding = new BasicHttpBinding() { AllowCookies = true, OpenTimeout = TimeSpan.FromHours(1), ReceiveTimeout = TimeSpan.FromHours(1), SendTimeout = TimeSpan.FromHours(1), CloseTimeout = TimeSpan.FromHours(1), MaxBufferPoolSize = 1024 * 1024 * 2, MaxReceivedMessageSize = 1024 * 512, MaxBufferSize = 1024 * 512 }; } string sdkUrl = string.Format("{0}://{1}{2}/sdk", inParam.Protocal, inParam.ServerName, 0 == inParam.Port ? "" : ":" + inParam.Port.ToString()); EndpointAddress epa = new EndpointAddress(sdkUrl); vmSummaryInfo.VmHost.ServerName = inParam.ServerName; vmSummaryInfo.VmHost.UserName = inParam.User; vmSummaryInfo.VmHost.Password = inParam.Password; vmSummaryInfo.VmHost.Port = inParam.Port; StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (var vimClient = new VimPortTypeClient(binding, epa)) { //var serviceCertificate = vimClient.ClientCredentials.ServiceCertificate; //serviceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.Custom; //serviceCertificate.Authentication.CustomCertificateValidator = new MyX509CertificateValidator(null); //serviceCertificate.Authentication.RevocationMode = X509RevocationMode.NoCheck; //var clientCertificate = vimClient.ClientCredentials.ClientCertificate; try { ManagedObjectReference morServiceInstance = new ManagedObjectReference() { @type = "ServiceInstance", Value = "ServiceInstance" }; ServiceContent sc = vimClient.RetrieveServiceContent(morServiceInstance); vmSummaryInfo.VmHost.ThumbPrint = StaticHelpers.FormatThumbPrint(certVerify.Thumbprint); sb.AppendFormat("{0}, {1}, {2}, {3}, {4}", epa.Uri, inParam.User, inParam.Password, vmSummaryInfo.VmHost.ThumbPrint, certVerify.Thumbprint); sb.AppendLine(); //StaticHelpers.PrintServerAboutInfo(sb, sc.about); sc.about.Dump(nameof(sc.about), sw, false); Console.WriteLine("{0}", sb.ToString()); sb.Clear(); using (MyCollectionDisposable collectionDisposal = new MyCollectionDisposable()) { UserSession userSession = vimClient.Login(sc.sessionManager, inParam.User, inParam.Password, null); collectionDisposal.Add(() => vimClient.Logout(sc.sessionManager)); //bool bListAllVMs = false; //if(bListAllVMs) if (inParam.ToListAllVMs) { CListVMs listVMs = new CListVMs(vimClient, sc.propertyCollector); listVMs.list_all_vms(sc); } VimPropCollector pc = new VimPropCollector(vimClient, sc.propertyCollector); VimFinder vimFinder = new VimFinder(vimClient, sc.propertyCollector, sc.rootFolder); List <ManagedObjectReference> morDatacenters = new List <ManagedObjectReference>(); vimFinder.FindDatacenters(morDatacenters); foreach (var datacenter in morDatacenters) { try { ManagedObjectReference morVM = (ManagedObjectReference)vimClient.FindByDatastorePath(sc.searchIndex, datacenter, inParam.VmPath); if (null != morVM) { vmSummaryInfo.VmHost.VmxSpec = "moref=" + morVM.Value; VirtualMachineConfigInfo virtualMachineConfigInfo = (VirtualMachineConfigInfo)pc.Get(morVM, "config"); //StaticHelpers.PrintMor(sb, morVM); morVM.Dump(nameof(morVM), sw, false); //StaticHelpers.PrintVMCI(sb, virtualMachineConfigInfo); StaticHelpers.PrintVirtualDisksBriefInfo(sb, virtualMachineConfigInfo, vmSummaryInfo.VmHost.CurrentDiskPath); virtualMachineConfigInfo.Dump(nameof(virtualMachineConfigInfo), sw, false); Console.WriteLine("{0}", sb.ToString()); sb.Clear(); VimSnapshotInfo si = new VimSnapshotInfo(vimClient, sc.propertyCollector, morVM, sb, vmSummaryInfo.Snapshots); si.Traverse(); Console.WriteLine("{0}", sb.ToString()); sb.Clear(); //datastore ManagedObjectReference:Datastore[] datastore-983 (datastore_on_30_1T) var datastore = (ManagedObjectReference[])pc.Get(morVM, "datastore"); if (null != datastore) { var datastoreName = from item in datastore select new { Datastore = item, DatastoreName = (string)pc.Get(item, "name") }; foreach (var item in datastoreName) { sb.AppendLine(); //StaticHelpers.PrintMor(sb, item.Datastore); item.Datastore.Dump(nameof(item.Datastore), sw, false); sb.AppendFormat("{0}\t\"{1}\"", nameof(item.DatastoreName), item.DatastoreName); sb.AppendLine(); } } //guest GuestInfo guest var guest = (GuestInfo)pc.Get(morVM, "guest"); //StaticHelpers.PrintGuestInfo(sb, guest); guest.Dump(nameof(guest), sw, false); //layout VirtualMachineFileLayout layout var layout = (VirtualMachineFileLayout)pc.Get(morVM, "layout"); //StaticHelpers.PrintVirtualMachineFileLayout(sb, layout); layout.Dump(nameof(layout), sw, false); //layoutEx VirtualMachineFileLayoutEx layoutEx var layoutEx = (VirtualMachineFileLayoutEx)pc.Get(morVM, "layoutEx"); //StaticHelpers.PrintVirtualMachineFileLayoutEx(sb, layoutEx); layoutEx.Dump(nameof(layoutEx), sw, false); //name string "shuli02-vc60" var name = (string)pc.Get(morVM, "name"); sb.AppendFormat("{0}\t\"{1}\"", nameof(name), name); //network ManagedObjectReference:Network[] network-822(VM Network) var network = (ManagedObjectReference[])pc.Get(morVM, "network"); if (null != network) { foreach (var Network in network) { //StaticHelpers.PrintMor(sb, Network); Network.Dump(nameof(Network), sw, false); } } //parent ManagedObjectReference:Folder group-v3 (vm) var parent = (ManagedObjectReference)pc.Get(morVM, "parent"); //StaticHelpers.PrintMor(sb, parent); parent.Dump(nameof(parent), sw, false); //resourceConfig ResourceConfigSpec resourceConfig var resourceConfig = (ResourceConfigSpec)pc.Get(morVM, "resourceConfig"); //StaticHelpers.PrintResourceConfigSpec(sb, resourceConfig); resourceConfig.Dump(nameof(resourceConfig), sw, false); //resourcePool ManagedObjectReference:ResourcePool resgroup-980 (VC) var resourcePool = (ManagedObjectReference)pc.Get(morVM, "resourcePool"); //StaticHelpers.PrintMor(sb, resourcePool); resourcePool.Dump(nameof(resourcePool), sw, false); //runtime VirtualMachineRuntimeInfo runtime var runtime = (VirtualMachineRuntimeInfo)pc.Get(morVM, "runtime"); //StaticHelpers.PrintVirtualMachineRuntimeInfo(sb, runtime); runtime.Dump(nameof(runtime), sw, false); string runtimeHostName = (string)pc.Get(runtime.host, "name"); ManagedObjectReference morRuntimehostParent = (ManagedObjectReference)pc.Get(runtime.host, "parent"); string runtimeHostParentName = (string)pc.Get(morRuntimehostParent, "name"); //StaticHelpers.PrintMor(sb, runtime.host); runtime.host.Dump(nameof(runtime.host), sw, false); sb.AppendFormat("{0}\t\"{1}\"", nameof(runtimeHostName), runtimeHostName); sb.AppendLine(); sb.AppendLine(); //StaticHelpers.PrintMor(sb, morRuntimehostParent); morRuntimehostParent.Dump(nameof(morRuntimehostParent), sw, false); sb.AppendFormat("{0}\t\"{1}\"", nameof(runtimeHostParentName), runtimeHostParentName); sb.AppendLine(); sb.AppendLine(); //storage VirtualMachineStorageInfo storage var storage = (VirtualMachineStorageInfo)pc.Get(morVM, "storage"); //StaticHelpers.PrintVirtualMachineStorageInfo(sb, storage); storage.Dump(nameof(storage), sw, false); Console.WriteLine("{0}", sb.ToString()); sb.Clear(); //summary VirtualMachineSummary summary var summary = (VirtualMachineSummary)pc.Get(morVM, "summary"); //StaticHelpers.PrintVirtualMachineSummary(sb, summary); summary.Dump(nameof(summary), sw, false); Console.WriteLine("{0}", sb.ToString()); sb.Clear(); ///////////////////////////////////////////////////////////////////////////////////////////// sb.Append('~', 80); sb.AppendLine(); sb.Append('~', 80); sb.AppendLine(); vmSummaryInfo.Dump(nameof(vmSummaryInfo), sw, false); sb.Append('~', 80); sb.AppendLine(); sb.Append('~', 80); sb.AppendLine(); Console.WriteLine("{0}", sb.ToString()); sb.Clear(); ///////////////////////////////////////////////////////////////////////////////////////////// bool testVmOperation = false; if (testVmOperation) { try { MyVMOperation vmop = new MyVMOperation(vimClient, sc.propertyCollector, morVM); TaskInfoState state = vmop.ConsolidateVMDisks(); string snapshotid1 = null; state = vmop.CreateSnapshot("test snapshot name 1", "test snapshot description1 ", false, true, out snapshotid1); VirtualDisk[] VirtualDisks1 = vmop.QuerySnapshotVirtualDisks(snapshotid1); string snapshotid2 = null; state = vmop.CreateSnapshot("test snapshot name 2", "test snapshot description2 ", false, true, out snapshotid2); VirtualDisk[] VirtualDisks2 = vmop.QuerySnapshotVirtualDisks(snapshotid2); try { foreach (var vdisk in VirtualDisks1) { long startOffset = 0; long diskSize = vdisk.capacityInBytes == 0 ? vdisk.capacityInKB * 1024 : vdisk.capacityInBytes; while (startOffset < diskSize) { DiskChangeInfo diskChangeInfo = vmop.QueryChangedDiskAreas(snapshotid2, vdisk, startOffset); if (null != diskChangeInfo.changedArea) { foreach (var changedArea in diskChangeInfo.changedArea) { changedArea.Dump(nameof(changedArea), sw, false); } Console.WriteLine("{0}", sb.ToString()); sb.Clear(); } startOffset = diskChangeInfo.startOffset + diskChangeInfo.length; } } } catch (Exception exQueryChangedDiskAreas) { StaticHelpers.PrintException(exQueryChangedDiskAreas, 0); } state = vmop.RemoveSnapshot(snapshotid2, false, true); state = vmop.RemoveSnapshot(snapshotid1, false, true); } catch (Exception exTestVmOperation) { StaticHelpers.PrintException(exTestVmOperation, 0); } } ///////////////////////////////////////////////////////////////////////////////////////////// bool testGustOp = false; if (testGustOp) { try { string guestUser = "******"; string guestPassword = "******"; VimGuestOperation vimGuestOp = new VimGuestOperation(vimClient, sc.propertyCollector, sc.guestOperationsManager, morVM, guestUser, guestPassword); string[] vars = vimGuestOp.ReadEnvironmentVariableInGuest(new string[] { "path" }); GuestProgramSpec guestProgramSpec = new GuestProgramSpec() { programPath = @"c:\Windows\notepad.exe", arguments = "", workingDirectory = @"c:\", envVariables = null }; long pid = vimGuestOp.StartProgramInGuest(guestProgramSpec); GuestProcessInfo[] gpi = vimGuestOp.ListProcessesInGuest(new long[] { pid }); vimGuestOp.TerminateProcessInGuest(pid); string guestFilePath = @"E:\1.vhdx"; string localFile = @"E:\~temp\1.vhdx"; vimGuestOp.FileTransferFromGuest(guestFilePath, localFile); string guestFilePath2 = @"e:\111\1.vhdx"; vimGuestOp.FileTransferToGuest(guestFilePath2, localFile, true); } catch (Exception exGust) { StaticHelpers.PrintException(exGust, 0); } } } } catch (Exception exFind) { StaticHelpers.PrintException(exFind, 0); } } } } catch (Exception ex) { StaticHelpers.PrintException(ex, 0); } } return(0); }