zoukankan      html  css  js  c++  java
  • C# 模仿PING操作,监控主机是否可以通信

    以下是C#代码,可以直接复制使用。

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Management;
    
    namespace PingMock
    {
        class MockerClass
        {
            private static Object thisobject = new Object();
            public void Ping(string Host)
            {
                //string rtn = "";
                
                ManagementObjectSearcher mos = null;
                ManagementObjectCollection moc = null;
                LogClass writeLog = new LogClass();
    
                try
                {
                    string searchString = "select * from win32_PingStatus where Address = '" + Host.Trim() + "'";
    
                    mos = new ManagementObjectSearcher(searchString);
                    moc = mos.Get();
    
                    foreach (ManagementObject mo in moc)
                    {
                        object obj = mo.Properties["StatusCode"].Value;
    
                        if (obj == null)
                        {
                            lock (thisobject)
                            {
                                writeLog.WriteLogFile(Host + " PING 执行失败。可能是主机未知。");
                            }
                            //return Host+" PING 执行失败。可能是主机未知。";
                        }
                        else
                        {
                            if (obj.ToString().Trim() == "0")
                            {
                                //rtn = "OK";
                                break;
                            }
                            lock (thisobject)
                            {
                                writeLog.WriteLogFile(Host + " PING 不通!");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    writeLog.WriteLogFile(Host + " PING 不通,可能原因为:" + ex.Message);
                    //rtn = Host+" PING 不通,可能原因为:"+ ex.Message;
                }
                finally
                {
                    if (moc != null) moc.Dispose();
                    if (mos != null) mos.Dispose();
                }
    
                //return rtn;
            } 
        }
    }
    

      

    可以修改城自己需要的形式。我这个是不返回结果,直接记录日志中。

  • 相关阅读:
    Python ES操作
    SVN总结
    MongoDB问题总结
    MySQL
    PyQt小工具
    Python logging模块
    shell脚本
    cmd命令
    eclipse java 项目打包
    Robot Framework:failed: Data source does not exist.错误
  • 原文地址:https://www.cnblogs.com/StupidsCat/p/2619512.html
Copyright © 2011-2022 走看看