C#编写WINNT服务

C#编写WINNT服务,随便解决安卓开发遇到的5037被众多程序无节操占用的问题

需求分析

最近重新开始学习安卓开发,好久不用的ADT集成开发环境频繁遇到不能在仿真机和真机上调试的问题,也就是本人另一篇博文描述的ADB(Android Debug Bridge)监控的5037被金山词霸暗自集成的金山手机助手、腾讯手机管家、豌豆荚等众多软件围攻的情形。需要详细了解,请移步:金山词霸你占我5037端口干嘛,费了你。那些流氓软件给我们安卓开发人员带来了很多烦恼啊,它们凭什么那么没节操?手动结束进程还真麻烦,有时还不知道是那个程序在作怪呢。所以想了下,写个WINNT服务检查当前活动的进程,如果有?adb这样的进程,且进程的运行目录有adb的必须依赖的几个dll文件时,就说明一定要费了它。

WINNT服务科普

NT服务程序可随操作系统启动而启动,没有图形界面,资源占用小。注册安装好服务后可在系统服务控制台启动、停止等。

关键代码说明: 

1、工作线程每隔1秒检查一下,系统当前活动的进程,把非adb的假adb进程终止掉。

复制代码
        /// <summary>
        /// 检测当前进程
        /// </summary>
        private void Guard_adb_Work()
        {
            while (true)
            {
                var processes = Process.GetProcesses().Where(p => p.ProcessName.Contains("adb") && p.ProcessName.Length > 3).ToList();
                if (processes.Count > 0)
                {
                    processes.ForEach(delegate(Process p)
                    {
                        var fileInfo = new FileInfo(p.MainModule.FileName);
                        //检查程序目录是否有adb的api dll类库,防止误杀
                        bool apiLibExists = fileInfo.Directory.GetFiles().Where(f => f.Name.Equals("AdbWinApi.dll")).Count() > 0;
                        if (apiLibExists)
                        {
                            WinCommand.startcmd(fileInfo.FullName, "kill-server");                                               
                            //p.Kill();
                            //你可恶我比你更可恶,但是Win7一般拿不到管理员权限,可能会删除失败
                            try
                            {
                                if (!EventLog.SourceExists(ServiceName))
                                {
                                    EventLog.CreateEventSource(ServiceName, "应用程序");
                                }
                                EventLog.WriteEntry(string.Format("进程【{0}】非法占用5037端口。已经被消灭。", fileInfo.Name), EventLogEntryType.Warning);
                                fileInfo.Delete();
                            }
                            catch
                            {
                            
                            }
                        }
                    });
                }
                System.Threading.Thread.Sleep(1000);
            }
        }
复制代码

2、adb命名终止adb server端,狡猾的众流氓软件会检查adb.exe是否运行,如果运行了,就直接使用adb的api获取当前已经通过USB等接口连接到PC的安卓手机。

可是ADT就不行了,它只认adb.exe这个进程。所以奇怪的是我把腾讯的手机管家的tadb.exe进程干掉了之后,插上手机腾讯手机管家还是会弹框说已经连接了安卓手机,是否启用手机管家这样的提示框。

C#运行命名行:

/// <summary>
   /// 执行命令行
   /// </summary>
   public class WinCommand
   {
       public static string startcmd(string command)
       {
           string output = "";
           try
           {
               Process cmd = new Process();
               cmd.StartInfo.FileName = command;
               cmd.StartInfo.UseShellExecute = false;
               cmd.StartInfo.RedirectStandardInput = true;
               cmd.StartInfo.RedirectStandardOutput = true;
               cmd.StartInfo.CreateNoWindow = true;
               cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
               cmd.Start();
               output = cmd.StandardOutput.ReadToEnd();
               Console.WriteLine(output);
               cmd.WaitForExit();
               cmd.Close();
           }
           catch (Exception e)
           {
               Console.WriteLine(e);
           }
           return output;
       }
       public static string startcmd(string command, string argument)
       {
           string output = "";
           try
           {
               Process cmd = new Process();
               cmd.StartInfo.FileName = command;
               cmd.StartInfo.Arguments = argument;
               cmd.StartInfo.UseShellExecute = false;
               cmd.StartInfo.RedirectStandardInput = true;
               cmd.StartInfo.RedirectStandardOutput = true;
               cmd.StartInfo.CreateNoWindow = true;
               cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
               cmd.Start();
               output = cmd.StandardOutput.ReadToEnd();
               Console.WriteLine(output);
               cmd.WaitForExit();
               cmd.Close();
           }
           catch (Exception e)
           {
               Console.WriteLine(e);
           }
           return output;
       }
   }

 执行adb kill-server命名之后,流氓软件启动的?adb.exe的进程会停止。

3、WINNT服务程序的调试

a.使用“附加到进程”功能来调试以及部署的服务程序,这里不解释。这个比较烦。

b.将服务的OnStart()方法改成public new 关键字标识,然后在Program应用程序入口处将 "ServiceBase.Run(ServicesToRun)"相关代码注释掉,改为new ????Service().OnStart()。这样就是变成普通控制台程序的调试了。

4、WINNT服务程序的安装

a、启动服务程序带传递参数的办法:

/// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        static void Main(string[] args)
        {
            #region 处理传参数,安装、卸载服务
            if (args.Length > 0)
            {
                AssemblyInstaller myAssemblyInstaller;
                myAssemblyInstaller = new AssemblyInstaller();
                myAssemblyInstaller.UseNewContext = true;
                myAssemblyInstaller.Path = System.AppDomain.CurrentDomain.BaseDirectory + "\" + System.AppDomain.CurrentDomain.FriendlyName;
                System.Collections.Hashtable mySavedState = new System.Collections.Hashtable();
                switch (args[0].ToLower())
                {
                    case "-i":
                        myAssemblyInstaller.Install(mySavedState);
                        myAssemblyInstaller.Commit(mySavedState);
                        myAssemblyInstaller.Dispose();
                        return;
                    case "-u":
                        myAssemblyInstaller.CommandLine = new string[1] { "/u" };
                        myAssemblyInstaller.Uninstall(null);
                        myAssemblyInstaller.Dispose();
                        return;
                    default:
                        System.Console.WriteLine("------参数说明------");
                        System.Console.WriteLine("- i 安装服务!");
                        System.Console.WriteLine("- u 卸载服务!");
                        System.Console.ReadKey();
                        return;
                }
            }
            #endregion
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {
                new AdbGuardWinntService()
            };
            ServiceBase.Run(ServicesToRun);
            //new AdbGuardWinntService().OnStart(null);
        }

 b、Installutil.exe:安装程序(Installer)工具,该工具允许你在一个指定的程序集中执行安装程序组件来安装和卸载服务器资源。Installutil命令方式安装也很麻烦不推荐。

 c、使用bat加传参数方法:

安装服务就是“服务程序.exe -i”,卸载就是“服务程序.exe -u”,启动服务是:“net start 服务名。”,停止服务是::“net stop 服务名。"将这些命令写成bat文件即可。如果是Win7需要以管理员权限运行。

补充(服务程序支持安装操作还需要执行的步骤):

设置服务运行时的系统账户类型,自动启动还是手动启动还是禁用等。

最后晒成果:

全部源码及可执行文件下载(需要.net 4 vs2010环境):

猛击这里下载。

 

 

 

 

 

分类: 程序设计
标签: C#

原文地址:https://www.cnblogs.com/Leo_wl/p/3312703.html