标签:des c style class blog code
早上的时候接到主管的一个任务,要获取服务器上的cpu,硬盘, 数据库等 的使用情况,并以邮件的方式发给boss, = =没办法,公司的服务器真是不敢恭维,顺便吐槽一下公司的网速,卡的时候30k左右徘徊,这不是在浪费我们的时间吗!!!
话不多说上代码,因为是实习,主管还是挺关照我的,一早就给我发了个类库(里面涉及到要查询本机信息的都有).这样我剩下了一大半的时间,
这个功能总的来说就两步: 一,先获取本机的信息 二,发送邮件。
获取本机信息用到的类库 SystemInfo.cs 和 DiskInfo.cs
SystemInfo.cs
1 //程序开发:lc_mtt 2 //CSDN博客:http://lemony.cnblogs.com 3 //个人主页:http://www.3lsoft.com 4 //注:此代码禁止用于商业用途。有修改者发我一份,谢谢! 5 //---------------- 开源世界,你我更进步 ---------------- 6 7 using System; 8 using System.Collections.Generic; 9 using System.Diagnostics; 10 using System.Threading; 11 using System.IO; 12 using System.Text; 13 using System.Management; 14 using System.Runtime.InteropServices; 15 16 namespace Lemony.SystemInfo 17 { 18 /// <summary> 19 /// 系统信息类 - 获取CPU、内存、磁盘、进程信息 20 /// </summary> 21 public class SystemInfo 22 { 23 private int m_ProcessorCount = 0; //CPU个数 24 private PerformanceCounter pcCpuLoad; //CPU计数器 25 private long m_PhysicalMemory = 0; //物理内存 26 27 private const int GW_HWNDFIRST = 0; 28 private const int GW_HWNDNEXT = 2; 29 private const int GWL_STYLE = (-16); 30 private const int WS_VISIBLE = 268435456; 31 private const int WS_BORDER = 8388608; 32 33 #region AIP声明 34 [DllImport("IpHlpApi.dll")] 35 extern static public uint GetIfTable(byte[] pIfTable, ref uint pdwSize, bool bOrder); 36 37 [DllImport("User32")] 38 private extern static int GetWindow(int hWnd, int wCmd); 39 40 [DllImport("User32")] 41 private extern static int GetWindowLongA(int hWnd, int wIndx); 42 43 [DllImport("user32.dll")] 44 private static extern bool GetWindowText(int hWnd, StringBuilder title, int maxBufSize); 45 46 [DllImport("user32", CharSet = CharSet.Auto)] 47 private extern static int GetWindowTextLength(IntPtr hWnd); 48 #endregion 49 50 #region 构造函数 51 /// <summary> 52 /// 构造函数,初始化计数器等 53 /// </summary> 54 public SystemInfo() 55 { 56 //初始化CPU计数器 57 pcCpuLoad = new PerformanceCounter("Processor", "% Processor Time", "_Total"); 58 pcCpuLoad.MachineName = "."; 59 pcCpuLoad.NextValue(); 60 61 //CPU个数 62 m_ProcessorCount = Environment.ProcessorCount; 63 64 //获得物理内存 65 ManagementClass mc = new ManagementClass("Win32_ComputerSystem"); 66 ManagementObjectCollection moc = mc.GetInstances(); 67 foreach (ManagementObject mo in moc) 68 { 69 if (mo["TotalPhysicalMemory"] != null) 70 { 71 m_PhysicalMemory = long.Parse(mo["TotalPhysicalMemory"].ToString()); 72 } 73 } 74 } 75 #endregion 76 77 #region CPU个数 78 /// <summary> 79 /// 获取CPU个数 80 /// </summary> 81 public int ProcessorCount 82 { 83 get 84 { 85 return m_ProcessorCount; 86 } 87 } 88 #endregion 89 90 #region CPU占用率 91 /// <summary> 92 /// 获取CPU占用率 93 /// </summary> 94 public float CpuLoad 95 { 96 get 97 { 98 return pcCpuLoad.NextValue(); 99 } 100 } 101 #endregion 102 103 #region 可用内存 104 /// <summary> 105 /// 获取可用内存 106 /// </summary> 107 public long MemoryAvailable 108 { 109 get 110 { 111 long availablebytes = 0; 112 //ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT * FROM Win64_PerfRawData_PerfOS_Memory"); 113 //foreach (ManagementObject mo in mos.Get()) 114 //{ 115 // availablebytes = long.Parse(mo["Availablebytes"].ToString()); 116 //} 117 ManagementClass mos = new ManagementClass("Win32_OperatingSystem"); 118 foreach (ManagementObject mo in mos.GetInstances()) 119 { 120 if (mo["FreePhysicalMemory"] != null) 121 { 122 availablebytes = 1024 * long.Parse(mo["FreePhysicalMemory"].ToString()); 123 } 124 } 125 return availablebytes; 126 } 127 } 128 #endregion 129 130 #region 物理内存 131 /// <summary> 132 /// 获取物理内存 133 /// </summary> 134 public long PhysicalMemory 135 { 136 get 137 { 138 return m_PhysicalMemory; 139 } 140 } 141 #endregion 142 143 #region 获得分区信息 144 /// <summary> 145 /// 获取分区信息 146 /// </summary> 147 public List<DiskInfo> GetLogicalDrives() 148 { 149 List<DiskInfo> drives = new List<DiskInfo>(); 150 ManagementClass diskClass = new ManagementClass("Win32_LogicalDisk"); 151 ManagementObjectCollection disks = diskClass.GetInstances(); 152 foreach (ManagementObject disk in disks) 153 { 154 // DriveType.Fixed 为固定磁盘(硬盘) 155 if (int.Parse(disk["DriveType"].ToString()) == (int)DriveType.Fixed) 156 { 157 drives.Add(new DiskInfo(disk["Name"].ToString(), long.Parse(disk["Size"].ToString()), long.Parse(disk["FreeSpace"].ToString()))); 158 } 159 } 160 return drives; 161 } 162 /// <summary> 163 /// 获取特定分区信息 164 /// </summary> 165 /// <param name="DriverID">盘符</param> 166 public List<DiskInfo> GetLogicalDrives(char DriverID) 167 { 168 List<DiskInfo> drives = new List<DiskInfo>(); 169 WqlObjectQuery wmiquery = new WqlObjectQuery("SELECT * FROM Win64_LogicalDisk WHERE DeviceID = ‘" + DriverID + ":‘"); 170 ManagementObjectSearcher wmifind = new ManagementObjectSearcher(wmiquery); 171 foreach (ManagementObject disk in wmifind.Get()) 172 { 173 if (int.Parse(disk["DriveType"].ToString()) == (int)DriveType.Fixed) 174 { 175 drives.Add(new DiskInfo(disk["Name"].ToString(), long.Parse(disk["Size"].ToString()), long.Parse(disk["FreeSpace"].ToString()))); 176 } 177 } 178 return drives; 179 } 180 #endregion 181 182 #region 获得进程列表 183 /// <summary> 184 /// 获得进程列表 185 /// </summary> 186 public List<ProcessInfo> GetProcessInfo() 187 { 188 List<ProcessInfo> pInfo = new List<ProcessInfo>(); 189 Process[] processes = Process.GetProcesses(); 190 foreach (Process instance in processes) 191 { 192 try 193 { 194 pInfo.Add(new ProcessInfo(instance.Id, 195 instance.ProcessName, 196 instance.TotalProcessorTime.TotalMilliseconds, 197 instance.WorkingSet64, 198 instance.MainModule.FileName)); 199 } 200 catch { } 201 } 202 return pInfo; 203 } 204 /// <summary> 205 /// 获得特定进程信息 206 /// </summary> 207 /// <param name="ProcessName">进程名称</param> 208 public List<ProcessInfo> GetProcessInfo(string ProcessName) 209 { 210 List<ProcessInfo> pInfo = new List<ProcessInfo>(); 211 Process[] processes = Process.GetProcessesByName(ProcessName); 212 foreach (Process instance in processes) 213 { 214 try 215 { 216 pInfo.Add(new ProcessInfo(instance.Id, 217 instance.ProcessName, 218 instance.TotalProcessorTime.TotalMilliseconds, 219 instance.WorkingSet64, 220 instance.MainModule.FileName)); 221 } 222 catch { } 223 } 224 return pInfo; 225 } 226 #endregion 227 228 #region 结束指定进程 229 /// <summary> 230 /// 结束指定进程 231 /// </summary> 232 /// <param name="pid">进程的 Process ID</param> 233 public static void EndProcess(int pid) 234 { 235 try 236 { 237 Process process = Process.GetProcessById(pid); 238 process.Kill(); 239 } 240 catch { } 241 } 242 #endregion 243 244 #region 获取 IP 地址信息 245 /// <summary> 246 /// 获取 IP 地址信息 247 /// </summary> 248 /// <returns></returns> 249 public static List<IpInfo> GetIpInfo() 250 { 251 //定义范型 252 List<IpInfo> ipinfos = new List<IpInfo>(); 253 254 ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); 255 ManagementObjectCollection moc = mc.GetInstances(); 256 foreach (ManagementObject mo in moc) 257 { 258 try 259 { 260 if ((bool)mo["IPEnabled"] == true) 261 { 262 string mac = mo["MacAddress"].ToString().Replace(‘:‘, ‘-‘); 263 System.Array ar = (System.Array)(mo.Properties["IpAddress"].Value); 264 string ip = ar.GetValue(0).ToString(); 265 ipinfos.Add(new IpInfo(ip, mac)); 266 } 267 } 268 catch { } 269 } 270 271 return ipinfos; 272 } 273 #endregion 274 275 #region 根据物理地址获取 IP 地址 276 /// <summary> 277 /// 根据物理地址获取 IP 地址 278 /// </summary> 279 /// <param name="MACAddress"物理地址></param> 280 /// <returns>IP 地址</returns> 281 public static string GetIpByMac(string MACAddress) 282 { 283 List<IpInfo> ipinfos = SystemInfo.GetIpInfo(); 284 foreach (IpInfo ipinfo in ipinfos) 285 { 286 if (string.Compare(ipinfo.MACAddress, MACAddress, true) == 0) 287 { 288 return ipinfo.IPAddress; 289 } 290 } 291 292 return ""; 293 } 294 #endregion 295 296 #region 根据 IP 地址获取物理地址 297 /// <summary> 298 /// 根据 IP 地址获取物理地址 299 /// </summary> 300 /// <param name="IPAddress"IP 地址></param> 301 /// <returns>物理地址</returns> 302 public static string GetMacByIp(string IPAddress) 303 { 304 List<IpInfo> ipinfos = SystemInfo.GetIpInfo(); 305 foreach (IpInfo ipinfo in ipinfos) 306 { 307 if (string.Compare(ipinfo.IPAddress, IPAddress, true) == 0) 308 { 309 return ipinfo.MACAddress; 310 } 311 } 312 return ""; 313 } 314 #endregion 315 316 #region 获取所有网络信息 317 /// <summary> 318 /// 获取所有的网络信息 319 /// </summary> 320 /// <returns>NetInfo 网络信息范型</returns> 321 public static List<NetInfo> GetAllNetInfo() 322 { 323 //定义范型 324 List<NetInfo> ninfos = new List<NetInfo>(); 325 326 //定义,获取 MIB_IFTABLE 对象 327 MIB_IFTABLE tbl = GetAllIfTable(); 328 329 //如果成功 330 if (tbl != null) 331 { 332 tbl.Deserialize(); 333 for (int i = 0; i < tbl.Table.Length; i++) 334 { 335 ninfos.Add(GetNetInfo(tbl.Table[i])); 336 } 337 } 338 339 return ninfos; 340 } 341 #endregion 342 343 #region 获取指定类型的网络信息 344 /// <summary> 345 /// 获取指定类型的网络信息 346 /// </summary> 347 /// <param name="nettype">网络类型</param> 348 /// <returns>NetInfo 网络信息范型</returns> 349 public static List<NetInfo> GetNetInfoByType(NetType nettype) 350 { 351 //定义范型 352 List<NetInfo> ninfos = new List<NetInfo>(); 353 354 //定义,获取 MIB_IFTABLE 对象 355 MIB_IFTABLE tbl = GetAllIfTable(); 356 357 //如果成功 358 if (tbl != null) 359 { 360 tbl.Deserialize(); 361 for (int i = 0; i < tbl.Table.Length; i++) 362 { 363 NetInfo ninfo = GetNetInfo(tbl.Table[i]); 364 if (ninfo.Type == nettype) 365 { 366 ninfos.Add(ninfo); 367 } 368 } 369 } 370 371 return ninfos; 372 } 373 #endregion 374 375 #region 获取指定物理地址的网络信息 376 /// <summary> 377 /// 获取指定物理地址的网络信息 378 /// </summary> 379 /// <param name="MACAddress">物理地址</param> 380 /// <returns>NetInfo 网络信息范型</returns> 381 public static NetInfo GetNetInfoByMac(string MACAddress) 382 { 383 //定义,获取 MIB_IFTABLE 对象 384 MIB_IFTABLE tbl = GetAllIfTable(); 385 386 //如果成功 387 if (tbl != null) 388 { 389 tbl.Deserialize(); 390 for (int i = 0; i < tbl.Table.Length; i++) 391 { 392 NetInfo ninfo = GetNetInfo(tbl.Table[i]); 393 if (string.Compare(MACAddress, ninfo.PhysAddr, true) == 0) 394 { 395 return ninfo; 396 } 397 } 398 } 399 400 return null; 401 } 402 #endregion 403 404 #region 获取指定 ip 地址的网络信息 405 /// <summary> 406 /// 获取指定 ip 地址的网络信息 407 /// </summary> 408 /// <param name="IPAddress">ip 地址</param> 409 /// <returns>NetInfo 网络信息范型</returns> 410 public static NetInfo GetNetInfoByIp(string IPAddress) 411 { 412 string MACAddress = GetMacByIp(IPAddress); 413 if (string.IsNullOrEmpty(MACAddress)) 414 { 415 return null; 416 } 417 else 418 { 419 return GetNetInfoByMac(MACAddress); 420 } 421 } 422 #endregion 423 424 #region 查找所有应用程序标题 425 /// <summary> 426 /// 查找所有应用程序标题 427 /// </summary> 428 /// <returns>应用程序标题范型</returns> 429 public static List<string> FindAllApps(int Handle) 430 { 431 List<string> Apps = new List<string>(); 432 433 int hwCurr; 434 hwCurr = GetWindow(Handle, GW_HWNDFIRST); 435 436 while (hwCurr > 0) 437 { 438 int IsTask = (WS_VISIBLE | WS_BORDER); 439 int lngStyle = GetWindowLongA(hwCurr, GWL_STYLE); 440 bool TaskWindow = ((lngStyle & IsTask) == IsTask); 441 if (TaskWindow) 442 { 443 int length = GetWindowTextLength(new IntPtr(hwCurr)); 444 StringBuilder sb = new StringBuilder(2 * length + 1); 445 GetWindowText(hwCurr, sb, sb.Capacity); 446 string strTitle = sb.ToString(); 447 if (!string.IsNullOrEmpty(strTitle)) 448 { 449 Apps.Add(strTitle); 450 } 451 } 452 hwCurr = GetWindow(hwCurr, GW_HWNDNEXT); 453 } 454 455 return Apps; 456 } 457 #endregion 458 459 /// <summary> 460 /// Get IFTable 461 /// </summary> 462 /// <returns>MIB_IFTABLE Class</returns> 463 private static MIB_IFTABLE GetAllIfTable() 464 { 465 //缓冲区大小 466 uint dwSize = 0; 467 468 //获取缓冲区大小 469 uint ret = GetIfTable(null, ref dwSize, false); 470 if (ret == 50) 471 { 472 //此函数仅支持于 win98/nt 系统 473 return null; 474 } 475 476 //定义,获取 MIB_IFTABLE 对象 477 MIB_IFTABLE tbl = new MIB_IFTABLE((int)dwSize); 478 ret = GetIfTable(tbl.ByteArray, ref dwSize, false); 479 480 //如果不成功 481 if (ret != 0) 482 { 483 return null; 484 } 485 486 return tbl; 487 } 488 489 /// <summary> 490 /// Get NetInfo Class 491 /// </summary> 492 /// <param name="row">MIB_IFROW Class</param> 493 /// <returns>NetInfo Class</returns> 494 private static NetInfo GetNetInfo(MIB_IFROW row) 495 { 496 NetInfo ninfo = new NetInfo(); 497 ninfo.Index = row.dwIndex; 498 ninfo.Name = Encoding.ASCII.GetString(row.bDescr, 0, (int)row.dwDescrLen); 499 ninfo.PhysAddr = GetPhysAddr(row.bPhysAddr, (int)row.dwPhysAddrLen); 500 ninfo.Type = (NetType)row.dwType; 501 ninfo.Status = (NetState)row.dwOperStatus; 502 ninfo.Speed = row.dwSpeed; 503 ninfo.InErrors = row.dwInErrors; 504 ninfo.InOctets = row.dwInOctets; 505 ninfo.InUnknownProtos = row.dwInUnknownProtos; 506 ninfo.OutErrors = row.dwOutErrors; 507 ninfo.OutOctets = row.dwOutOctets; 508 return ninfo; 509 } 510 511 /// <summary> 512 /// 获取格式化的物理地址 513 /// </summary> 514 /// <param name="b">字节数组</param> 515 /// <param name="len">长度</param> 516 /// <returns>无聊地址</returns> 517 private static string GetPhysAddr(byte[] b, int len) 518 { 519 string[] pa = new string[len]; 520 for (int i = 0; i < len; i++) 521 { 522 pa[i] = ((int)b[i]).ToString("X2"); 523 } 524 return string.Join("-", pa); 525 } 526 527 528 } 529 }
DiskInfo.cs
1 using System; 2 using System.Collections.Generic; 3 using System.Text; 4 5 namespace Lemony.SystemInfo 6 { 7 /// <summary> 8 /// 硬盘信息类 9 /// </summary> 10 public class DiskInfo 11 { 12 public DiskInfo(string DiskName, long Size, long FreeSpace) 13 { 14 this.DiskName = DiskName; 15 this.Size = Size; 16 this.FreeSpace = FreeSpace; 17 } 18 19 private String m_DiskName; 20 public String DiskName 21 { 22 get { return m_DiskName; } 23 set { m_DiskName = value; } 24 } 25 26 private long m_Size; 27 public long Size 28 { 29 get { return m_Size; } 30 set { m_Size = value; } 31 } 32 33 private long m_FreeSpace; 34 public long FreeSpace 35 { 36 get { return m_FreeSpace; } 37 set { m_FreeSpace = value; } 38 } 39 } 40 }
因为只是查询cpu,和硬盘使用情况 只涉及到这两个类
是在控制台应用程序写的
Program.cs
1 //执行该主函数时 1.获取要发送的信息 2.发送邮件 2 //发件人 和收件人保存在配置文件中. 3 4 string Dstring = ""; //获得分区信息 5 string useCPU = ""; //获取CPU占用率 6 string useRAM = "";//获取物理内存 7 string userRAMs = "";//可使用的物理内存 8 string userMYSQLs = "";//获取数据库当前的容量 9 string useMYSQL = "";//获取数据库的连接数 10 string table = ""; 11 12 //1.获取要发送的信息(根据类库) 13 //1.1获取分区信息 14 SystemInfo sysinfo = new SystemInfo(); 15 List<DiskInfo> DInfo = sysinfo.GetLogicalDrives(); 16 foreach (DiskInfo a in DInfo) 17 { 18 Dstring += "<font style=‘color:red‘>"+a.DiskName + "</font> 总空间为" + Math.Round(a.Size / 1024.00000 / 1024.00000 / 1024.00000, 2)+"G,剩余"+Math.Round(a.FreeSpace / 1024.00000 / 1024.00000 / 1024.00000, 2)+"G "; 19 } 20 21 22 //CPU占用率 23 useCPU = sysinfo.CpuLoad.ToString()+"%"; 24 //总的物理内存 25 useRAM = Math.Round(sysinfo.PhysicalMemory / 1024.00000 / 1024.00000 / 1024.00000, 2) + "G"; 26 //可使用的物理内存 27 userRAMs = Math.Round(sysinfo.MemoryAvailable / 1024.00000 / 1024.00000, 2) + "M"; 28 29 //数据库连接 30 string sql = "select round(sum(data_length/1024/1024),2) from tables where TABLE_SCHEMA=‘ship_detail_data‘"; 31 userMYSQLs= DBHelper.GetScalar(sql).ToString() +"MB"; 32 string sql1 = "select variable_value from GLOBAL_STATUS where variable_name=‘THREADS_RUNNING‘"; 33 useMYSQL = DBHelper.GetScalar(sql1).ToString(); 34 35 //total = Dstring + "CPU占用率:" + useCPU + "; 总的物理内存:" + useRAM + "; 可使用的物理内存:" + userRAMs; 36 37 table = string.Format(@"<table><tr><td colspan=‘2‘ style=‘text-align:center‘><h3>"+DateTime.Now.ToString()+" 服务器的信息</h3></td></tr><tr> <td>硬盘信息</td><td>" + Dstring + "</td></tr><tr><td>内存信息</td><td>总物理内存:" + useRAM + ";可使用物理内存:" + userRAMs + "</td></tr><tr><td>CPU信息</td><td>CPU占用率:" + useCPU + "</td></tr><tr><td>数据库连接</td><td>数据库容量:"+userMYSQLs+"; 数据库当前连接数:"+useMYSQL+"</td></tr></table>"); 38 39 send sd = new send(); 40 sd.setmail(table); 41 Console.WriteLine("发送成功"); 42 Console.ReadLine();
有点乱,没去弄别的。
主函数中还涉及到了 数据库的信息,刚开始不懂,百度了好久也什么都不太懂,后来就找组织了,经组织训示 终于在mysql (公司用的)中找到了information_schema 这里面记录了整个数据库的信息,在里面找到了两个表 tables 和GLOBAL_STATUS 其他的也没多去看(最主要是不懂英语.)。可以用就行(不过感觉有点不靠谱,网上貌似有说)。
取到数据了之后就是 发邮件了
send.cs
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace sendmail 7 { 8 class send 9 { 10 public void setmail(string content) 11 { 12 System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(); 13 client.Host = "smtp.163.com";//使用163的SMTP服务器发送邮件 14 client.UseDefaultCredentials = true; 15 client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; 16 client.Credentials = new System.Net.NetworkCredential("feichonghuang", "wanxc.chong"); 17 System.Net.Mail.MailMessage Message = new System.Net.Mail.MailMessage(); 18 Message.From = new System.Net.Mail.MailAddress("feichonghuang@163.com"); 19 20 Message.To.Add("279789248@qq.com");//将邮件发送给QQ邮箱 21 Message.Subject = "电脑监测"; 22 Message.Body = content; 23 Message.SubjectEncoding = System.Text.Encoding.UTF8; 24 Message.BodyEncoding = System.Text.Encoding.UTF8; 25 Message.Priority = System.Net.Mail.MailPriority.High; 26 Message.IsBodyHtml = true; 27 28 client.Send(Message); 29 } 30 31 } 32 }
发邮件 在主函数中设置了表格。
到这里基本已经搞定了 其中有链接数据库的因为用到了Help类,也不难,就没贴出来了,自己加上去就行了。
好的功能已经完成了。。。。谢谢!
获取本机CPU,硬盘等使用情况,布布扣,bubuko.com
标签:des c style class blog code
原文地址:http://www.cnblogs.com/chongde/p/3759910.html