检测是 Windows 服务何时被删除

Bil*_*Day 9 c# windows service logging

有没有办法检测 Windows 服务何时被删除?我检查了事件日志,但它没有选择仅添加的已删除操作。

我相信可能有一种使用审计日志的方法,但我不确定如何做到这一点?

任何帮助深表感谢。

谢谢

Cli*_*int 6

虽然是在没有服务缺失的跟踪事件审计日志,你可以做的是创建一个小控制台应用程序,如果一个服务存在检测和这个应用程序安装到Windows Task Scheduler这样的,它是计划执行基于对频率或触发你可以根据您的要求进行自定义,以便在添加删除服务等时您会收到警报。

控制台应用程序的设计使得在第一次运行时,它会记录系统上的所有服务,在随后的运行中,它将通过servicesRemoved和 跟踪对服务所做的更改servicesAdded,这样我们就可以决定当服务出现故障时要采取什么行动被修改

控制台应用程序:ServiceDetector.exe

static void Main(string[] args)
{
    var path = @"C:\AdminLocation\ServicesLog.txt";

    var currentServiceCollection = ServiceController.GetServices().Select(s => s.ServiceName).ToList(); //Queries the most current Services from the machine

    if (!File.Exists(path)) //Creates a Log file with current services if not present, usually means the first run
    {
        // Assumption made is that this is the first run
        using (var text = File.AppendText(path))
        {
            currentServiceCollection.ForEach((s) => text.WriteLine(s));
        }
        return;
    }

    // Fetches the recorded services from the Log
    var existingServiceCollection = File.ReadAllLines(path).ToList();

    var servicesRemoved = existingServiceCollection.Except(currentServiceCollection).ToList();
    var servicesAdded = currentServiceCollection.Except(existingServiceCollection).ToList();

    if (!servicesAdded.Any() && !servicesRemoved.Any())
    { Console.WriteLine("No services have been added or removed"); return; }

    //If any services has been added
    if (servicesAdded.Any())
    {
        Console.WriteLine("One or more services has been added");
        using (var text = File.AppendText(path))
        {
            servicesAdded.ForEach((s) => text.WriteLine(s));
        }
        return;
    }
    //Service(s) may have been deleted, you can choose to record it or not based on your requirements
    Console.WriteLine("One or more services has been removed");

}
Run Code Online (Sandbox Code Playgroud)

调度任务

Windows 开始 > 任务计划程序 > 创建基本任务 > 设置触发器 > 附加您的 exe > 完成