使用C#检查在远程计算机上运行的服务的状态

使用C#检查在远程计算机上运行的服务的状态,第1张

概述使用C#检查在远程计算机上运行的服务的状态

我正在使用下面的代码。

ServiceController MyController = new ServiceController(); MyController.Machinename = server_txt.Text.Trim(); MyController.Servicename = "Service1"; string msg = MyController.Status.ToString(); Label1.Text = msg;

此代码适用于有权访问的networking计算机。 如何改变这个,使它适用于使用凭证的不同域中的系统?

是否可以启动一个远程应用程序,并在windows中交互显示?

如何获得远程用户会话映射的驱动器

让Jenkins对远程用户不可见

检查电脑是否打开

使用SSH在远程linux机器上运行带有基础的cleartool命令

如果您使用WMI,则可以在“Connectionoptions”中设置凭据。

Connectionoptions op = new Connectionoptions(); op.Username = "Domain\Domainuser"; op.Password = "password"; ManagementScope scope = new ManagementScope(@"\servername.Domainrootcimv2",op); scope.Connect(); ManagementPath path = new ManagementPath("Win32_Service"); ManagementClass services; services = new ManagementClass(scope,path,null); foreach (ManagementObject service in services.GetInstances()) { if (service.GetPropertyValue("State").ToString().Tolower().Equals("running")) { // Do something } }

MSDN是你的朋友。

using System.ServiceProcess; ServiceController sc = new ServiceController("YourService","Machinename"); if (sc.Status.Equals(ServiceControllerStatus.Stopped) || sc.Status.Equals(ServiceControllerStatus.StopPending) { // it is stopped }

我知道,如果你在那台机器上拥有管理员权限,只需要上面的代码。 但是,如另一条评论所述,如果您正在运行的帐户在该计算机上没有管理员权限,则可能必须使用模拟进行设置,如下所示:

string username = "domain\user"; // there's really just one slash,//but you have to escape it if hard-Coding.. //if brought in by a text Box,it would be just domainuser string password = "whatever"; windowsImpersonationContext adminContext = Impersonation.getWic(username,password); if (adminContext != null) { try { ServiceController sc = new ServiceController("YourService","Machinename"); if (sc.Status.Equals(ServiceControllerStatus.Stopped) || sc.Status.Equals(ServiceControllerStatus.StopPending) { // it is stopped } } catch (Exception ex) { Console.Out.Writeline("nUnable to set profile to Mandatory:nt" + ex.Message); Impersonation.endImpersonation(); adminContext.Undo(); } finally { Impersonation.endImpersonation(); // The above line just basically does this on the tokens -- //if (tokenHandle != IntPtr.Zero) CloseHandle(tokenHandle); adminContext.Undo(); } }

这是我单独的模拟类。 它有2个主要的入口点, getWic()和doImpersonation() – getWic()将采取一个用户名,看起来像domainuser或machinenameuser并把它们分成他们的组成部分,然后交给doImpersonation()而doImpersonation()接受已经分割的部分,如果你有这样的,并不需要getWic()的代码。 两者都返回一个windowsImpersonationContext 。

using System; using System.Data; using System.Configuration; using System.Security.Permissions; using System.Security.Principal; using System.Runtime.InteropServices; [assembly: SecurityPermissionAttribute(SecurityAction.RequestMinimum,UnmanagedCode = true)] [assembly: PermissionSetAttribute(SecurityAction.RequestMinimum,name = "FullTrust")] public class Impersonation { [Dllimport("advAPI32.dll",EntryPoint = "logonUser")] public static extern bool logonUser( string lpszUsername,string lpszDomain,string lpszPassword,int DWlogonType,int DWlogonProvIDer,ref IntPtr phToken); [Dllimport("advAPI32.dll",CharSet = CharSet.auto,SetLastError = true)] public extern static bool Duplicatetoken(IntPtr ExistingTokenHandle,int Security_IMPERSONATION_LEVEL,ref IntPtr DuplicatetokenHandle); [Dllimport("kernel32.dll",CharSet = CharSet.auto)] public extern static bool CloseHandle(IntPtr handle); // Declare the logon Types as constants const int logoN32_logoN_IN@R_502_6704@CTIVE = 2; const int logoN32_logoN_NETWORK = 3; const int logoN32_logoN_BATCH = 4; const int logoN32_logoN_SERVICE = 5; const int logoN32_logoN_UNLOCK = 7; const int logoN32_logoN_NETWORK_CLEARTEXT = 8; // Win2K or higher const int logoN32_logoN_NEW_CREDENTIALS = 9; // Win2K or higher // Declare the logon ProvIDers as constants const int logoN32_PROVIDER_DEFAulT = 0; const int logoN32_PROVIDER_WINNT50 = 3; const int logoN32_PROVIDER_WINNT40 = 2; const int logoN32_PROVIDER_WINNT35 = 1; // Declare the Impersonation Levels as constants const int SecurityAnonymous = 0; const int SecurityIDentification = 1; const int SecurityImpersonation = 2; const int SecurityDelegation = 3; private static windowsIDentity newID; private static IntPtr tokenHandle = new IntPtr(0); private static IntPtr dupetokenHandle = new IntPtr(0); [PermissionSetAttribute(SecurityAction.Demand,name = "FullTrust")] public static windowsImpersonationContext doImpersonation(string svcUsername,string domainname,string password) { // Initialize tokens tokenHandle = IntPtr.Zero; dupetokenHandle = IntPtr.Zero; // Call logonUser to obtain a handle to an access token bool returnValue = logonUser(svcUsername,domainname,password,logoN32_logoN_IN@R_502_6704@CTIVE,logoN32_PROVIDER_WINNT50,ref tokenHandle); if (returnValue == false) { int ret = Marshal.GetLastWin32Error(); //Check for errors if (ret != NO_ERROR) throw new Exception("logonUser Failed with error code : " + GetError(ret)); } bool retVal = Duplicatetoken(tokenHandle,SecurityImpersonation,ref dupetokenHandle); if (retVal == false) { CloseHandle(tokenHandle); throw new Exception("Exception thrown in trying to duplicate token."); } else { // Begin Impersonation bool bRetVal = Duplicatetoken(tokenHandle,(int)SecurityImpersonation,ref dupetokenHandle); newID = new windowsIDentity(dupetokenHandle); windowsImpersonationContext impersonatedUser = newID.Impersonate(); return impersonatedUser; } } public static voID endImpersonation() { if (dupetokenHandle != IntPtr.Zero) CloseHandle(dupetokenHandle); if (tokenHandle != IntPtr.Zero) CloseHandle(tokenHandle); } public static windowsImpersonationContext getWic(string usernameStringFromTextBox,string password) { try { // Establish impersonation string svcUser = usernameStringFromTextBox; string[] arrUser = new string[2]; arrUser = svcUser.Split('\'); string domain = arrUser[0]; string svcUsername = arrUser[1]; // Get Password: Convert from Base-64 String to decrypted string //string keyLength = ConfigurationManager.AppSettings["keyLength"].ToString(); //string keyLocation = ConfigurationManager.AppSettings["keyLocation"].ToString(); //password = RSAEncrypt.DecryptData(password,keyLength,keyLocation); windowsImpersonationContext wic = doImpersonation(svcUsername,domain,password); return wic; } catch (Exception ex) { ErrorLog.ErrorRoutine(new Exception("getWic() Error: " + ex.ToString()),ErrorMessage.NOTIFY_APP_ERROR); return null; } } #region Errors const int NO_ERROR = 0; const int ERROR_ACCESS_DENIED = 5; const int ERROR_ALREADY_ASSIGNED = 85; const int ERROR_BAD_DEVICE = 1200; const int ERROR_BAD_NET_name = 67; const int ERROR_BAD_PROVIDER = 1204; const int ERROR_CANCELLED = 1223; const int ERROR_EXTENDED_ERROR = 1208; const int ERROR_INVALID_ADDRESS = 487; const int ERROR_INVALID_ParaMETER = 87; const int ERROR_INVALID_PASSWORD = 1216; const int ERROR_MORE_DATA = 234; const int ERROR_NO_MORE_ITEMS = 259; const int ERROR_NO_NET_OR_BAD_PATH = 1203; const int ERROR_NO_NETWORK = 1222; const int ERROR_SESSION_CREDENTIAL_CONFliCT = 1219; const int ERROR_BAD_PROfile = 1206; const int ERROR_CANNOT_OPEN_PROfile = 1205; const int ERROR_DEVICE_IN_USE = 2404; const int ERROR_NOT_CONNECTED = 2250; const int ERROR_OPEN_fileS = 2401; private struct ErrorClass { public int num; public string message; public ErrorClass(int num,string message) { this.num = num; this.message = message; } } private static ErrorClass[] ERROR_List = new ErrorClass[] { new ErrorClass(ERROR_ACCESS_DENIED,"Error: Access DenIEd"),new ErrorClass(ERROR_ALREADY_ASSIGNED,"Error: Already Assigned"),new ErrorClass(ERROR_BAD_DEVICE,"Error: Bad Device"),new ErrorClass(ERROR_BAD_NET_name,"Error: Bad Net name"),new ErrorClass(ERROR_BAD_PROVIDER,"Error: Bad ProvIDer"),new ErrorClass(ERROR_CANCELLED,"Error: Cancelled"),new ErrorClass(ERROR_EXTENDED_ERROR,"Error: Extended Error"),new ErrorClass(ERROR_INVALID_ADDRESS,"Error: InvalID Address"),new ErrorClass(ERROR_INVALID_ParaMETER,"Error: InvalID Parameter"),new ErrorClass(ERROR_INVALID_PASSWORD,"Error: InvalID Password"),new ErrorClass(ERROR_MORE_DATA,"Error: More Data"),new ErrorClass(ERROR_NO_MORE_ITEMS,"Error: No More Items"),new ErrorClass(ERROR_NO_NET_OR_BAD_PATH,"Error: No Net Or Bad Path"),new ErrorClass(ERROR_NO_NETWORK,"Error: No Network"),new ErrorClass(ERROR_BAD_PROfile,"Error: Bad Profile"),new ErrorClass(ERROR_CANNOT_OPEN_PROfile,"Error: Cannot Open Profile"),new ErrorClass(ERROR_DEVICE_IN_USE,"Error: Device In Use"),new ErrorClass(ERROR_NOT_CONNECTED,"Error: Not Connected"),new ErrorClass(ERROR_OPEN_fileS,"Error: Open files"),new ErrorClass(ERROR_SESSION_CREDENTIAL_CONFliCT,"Error: Credential Conflict"),}; private static string GetError(int errNum) { foreach (ErrorClass er in ERROR_List) { if (er.num == errNum) return er.message; } return "Error: UnkNown," + errNum; } #endregion }

参考文献:


ServiceController类。 https://msdn.microsoft.com/en-us/library/system.serviceprocess.servicecontroller(v=vs.110).aspx


windowsIDentity.Impersonate方法。 https://msdn.microsoft.com/en-us/library/w070t6ka(v=vs.110).aspx

这是一个尝试类似方法的人的链接 ; 他们的发现是他们需要在运行程序的机器上登录的远程机器上登录。

总结

以上是内存溢出为你收集整理的使用C#检查在远程计算机上运行的服务的状态全部内容,希望文章能够帮你解决使用C#检查在远程计算机上运行的服务的状态所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1277931.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-09
下一篇 2022-06-09

发表评论

登录后才能评论

评论列表(0条)

保存