internal TaskCollection(TaskFolder folder, IRegisteredTaskCollection iTaskColl, Regex filter = null)
 {
     svc    = folder.TaskService;
     Filter = filter;
     fld    = folder;
     v2Coll = iTaskColl;
 }
Example #2
0
        /// <summary>
        /// 获取计划任务的列表
        /// </summary>
        /// <returns>计划任务列表</returns>
        public static IRegisteredTaskCollection GetAllTaskScheduler()
        {
            TaskSchedulerClass taskSchedulerClass = new TaskSchedulerClass();

            taskSchedulerClass.Connect(null, null, null, null);
            ITaskFolder taskFolder = taskSchedulerClass.GetFolder("\\");
            IRegisteredTaskCollection registeredTaskCollection = taskFolder.GetTasks(1);

            return(registeredTaskCollection);
        }
Example #3
0
        public static IRegisteredTaskCollection GetAllTasks()
        {
            TaskSchedulerClass ts = new TaskSchedulerClass();

            ts.Connect(null, null, null, null);
            ITaskFolder folder = ts.GetFolder("\\Microsoft\\Windows\\Application Experience");
            IRegisteredTaskCollection tasks_exists = folder.GetTasks(1);

            return(tasks_exists);
        }
Example #4
0
        public static IRegisteredTaskCollection GetAllTasks()
        {
            TaskSchedulerClass ts = new TaskSchedulerClass();

            ts.Connect(null, null, null, null);
            ITaskFolder folder = ts.GetFolder("\\");
            IRegisteredTaskCollection task_exists = folder.GetTasks(1);

            return(task_exists);
        }
Example #5
0
        static bool TaskExists(ITaskFolder mFolder)
        {
            bool mFound = false;
            IRegisteredTaskCollection mTasks = mFolder.GetTasks(0);

            foreach (IRegisteredTask mTask in mTasks)
            {
                mFound |= mTask.Name == "BackgroundWorker";
            }
            return(mFound);
        }
        /// <summary>
        /// 启动任务
        /// </summary>
        /// <param name="name"></param>
        #region public static void startTask(String name)
        public static void startTask(String name)
        {
            IRegisteredTaskCollection tasks = GetAllTasks();

            foreach (IRegisteredTask task in tasks)
            {
                if (task.Name.Equals(name))
                {
                    task.Run(null);
                }
            }
        }
        /// <summary>
        /// 启动任务
        /// </summary>
        /// <param name="name"></param>
        #region public static void startTask(String name)
        public static void startTask(String name)
        {
            //获取任务列表
            IRegisteredTaskCollection tasks = GetAllTasks();

            foreach (IRegisteredTask task in tasks)//循环遍历列表
            {
                if (task.Name.Equals(name))
                {
                    task.Run(null);//开始运行任务
                }
            }
        }
        /// <summary>
        /// 查找任务
        /// </summary>
        /// <param name="taskName"></param>
        /// <returns></returns>
        public static IRegisteredTask FindTask(string taskName)
        {
            IRegisteredTaskCollection tasks_exists = GetAllTasks();

            for (int i = 1; i <= tasks_exists.Count; i++)
            {
                IRegisteredTask t = tasks_exists[i];
                if (t.Name.Equals(taskName))
                {
                    return(t);
                }
            }
            return(null);
        }
        /// <summary>
        /// 获取所有的定时任务
        /// </summary>
        /// <returns></returns>
        #region public static IRegisteredTaskCollection GetAllTasks()
        public static IRegisteredTaskCollection GetAllTasks()
        {
            //实例化任务计划
            TaskSchedulerClass task = new TaskSchedulerClass();

            //连接
            task.Connect(null, null, null, null);
            //获取根目录
            ITaskFolder folder = task.GetFolder("\\");
            //获取计划集合
            IRegisteredTaskCollection taskList = folder.GetTasks(1);

            return(taskList);
        }
Example #10
0
        public IRegisteredTaskCollection GetAllTasks()
        {
            TaskScheduler.TaskScheduler ts = new TaskScheduler.TaskScheduler();
            ts.Connect(null, null, null, null);
            ITaskFolder folder = ts.GetFolder("\\");
            IRegisteredTaskCollection tasks_exists = folder.GetTasks(1);
            IEnumerator ie = tasks_exists.GetEnumerator();

            foreach (IRegisteredTask item in tasks_exists)
            {
                string x = item.Name;
            }

            return(tasks_exists);
        }
Example #11
0
 /// <summary>
 /// 获得所有任务计划
 /// </summary>
 /// <returns>所有任务计划</returns>
 public static IRegisteredTaskCollection GetAllTaskschd()
 {
     try
     {
         TaskSchedulerClass taskScheduler = new TaskSchedulerClass();
         taskScheduler.Connect(null, null, null, null);
         ITaskFolder taskFolder = taskScheduler.GetFolder("\\");
         IRegisteredTaskCollection tasks_exists = taskFolder.GetTasks(1);
         return(tasks_exists);
     }
     catch (Exception ex)
     {
         TXTHelper.Logs(ex.ToString());
         return(null);
     }
 }
Example #12
0
        /// <summary>
        /// 以任务名为标准判断计划任务是否存在
        /// </summary>
        /// <param name="taskName">待判断的计划任务名</param>
        /// <returns>计划任务存在性的布尔值</returns>
        public static bool IsTaskExists(string taskName)
        {
            bool isExists = false;
            IRegisteredTaskCollection registeredTaskCollection = GetAllTaskScheduler();

            for (int i = 1; i <= registeredTaskCollection.Count; i++)
            {
                IRegisteredTask registeredTask = registeredTaskCollection[i];
                if (registeredTask.Name.Equals(taskName))
                {
                    isExists = true;
                    break;
                }
            }
            return(isExists);
        }
Example #13
0
        /// <summary>
        /// check task isexists
        /// </summary>
        /// <param name="taskName"></param>
        /// <returns></returns>
        public static bool IsExists(string taskName)
        {
            var isExists = false;
            IRegisteredTaskCollection tasks_exists = GetAllTasks();

            for (int i = 1; i <= tasks_exists.Count; i++)
            {
                IRegisteredTask t = tasks_exists[i];
                if (t.Name.Equals(taskName))
                {
                    isExists = true;
                    break;
                }
            }
            return(isExists);
        }
Example #14
0
        public void ListTasks()
        {
            Debug.Print("Listing Tasks");
            ConnectTaskSchedulerService();

            ITaskFolder folder = taskService.GetFolder(TaskPathSeparator);
            IRegisteredTaskCollection tasks = folder.GetTasks(1);

            foreach (IRegisteredTask task in tasks)
            {
                Debug.Print("Task: " + task.Path + " : " + task.Name);

                ITaskDefinition def = task.Definition;
                Debug.Print("> " + def.Principal.RunLevel.ToString());
                Debug.Print("> " + task.Xml);
            }
        }
        /// <summary>
        /// 检查定时任务是否存在
        /// </summary>
        /// <param name="taskName"></param>
        /// <returns></returns>
        #region public static bool checkTask(String taskName)
        public static bool checkTask(String taskName, out _TASK_STATE state)
        {
            var isExists = false;
            IRegisteredTaskCollection taskList = GetAllTasks();

            foreach (IRegisteredTask task in taskList)
            {
                if (task.Name.Equals(taskName))
                {
                    isExists = true;
                    state    = task.State;

                    return(isExists);
                }
            }
            state = _TASK_STATE.TASK_STATE_UNKNOWN;
            return(isExists);
        }
Example #16
0
        public void ProcessTaskFolder(ITaskFolder taskFolder)
        {
            int         idx;
            string      name, path;
            _TASK_STATE state;
            DateTime    lastRun;

            IRegisteredTaskCollection taskCol = taskFolder.GetTasks((int)_TASK_ENUM_FLAGS.TASK_ENUM_HIDDEN); // include hidden tasks, otherwise 0

            for (idx = 1; idx <= taskCol.Count; idx++)                                                       // browse all tasks in folder
            {
                IRegisteredTask runTask = taskCol[idx];                                                      // 1 based index


                name    = runTask.Name;
                path    = runTask.Path;
                state   = runTask.State;
                lastRun = runTask.LastRunTime;



                Console.WriteLine(path);
                foreach (var wt in watchList.tasks)
                {
                    if (wt == name)
                    {
                        string stateHtml = "";
                        stateHtml = (state.ToString() != "TASK_STATE_DISABLED") ? "<span style='color:green'>ENABLED</span>" : "<span style='color:red'>DISABLED</span>";
                        WriteContent("DateTime: " + DateTime.Now + " name: " + name + " status: " + state + " last run time " + lastRun.ToString() + " \n");

                        htmlBody.Append("<tr>");
                        htmlBody.AppendFormat("<td><b>{0}</b></td> <td>{1}</td> <td><span style='font-size:9pt'> {2} </span></td>", name, stateHtml, lastRun);
                        htmlBody.Append("<tr>");
                    }
                }
            }

            ITaskFolderCollection taskFolderCol = taskFolder.GetFolders(0); // 0 = reserved for future use

            for (idx = 1; idx <= taskFolderCol.Count; idx++)                // recursively browse subfolders
            {
                ProcessTaskFolder(taskFolderCol[idx]);                      // 1 based index
            }
        }
Example #17
0
 /// <summary>
 /// 获取指定名称的任务列表
 /// </summary>
 /// <param name="taskName">任务前缀</param>
 /// <returns>任务列表</returns>
 public static List <ScheduleTask> GetAllTasks(string taskName)
 {
     try
     {
         List <ScheduleTask> taskList = new List <ScheduleTask>();
         TaskSchedulerClass  ts       = new TaskSchedulerClass();
         ts.Connect(null, null, null, null);
         ITaskFolder folder = ts.GetFolder("\\");
         IRegisteredTaskCollection tasks_exists = folder.GetTasks(1);
         for (int i = 1; i <= tasks_exists.Count; i++)
         {
             IRegisteredTask t  = tasks_exists[i];
             ScheduleTask    st = new ScheduleTask();
             if (t.Name.StartsWith(taskName))
             {
                 st.TaskName    = t.Name;
                 st.NextRunTime = t.NextRunTime.ToString("yyyy-MM-dd HH:mm:ss");
                 if (t.State.ToString() == "TASK_STATE_READY")
                 {
                     st.TaskStats = "准备就绪";
                 }
                 if (t.State.ToString() == "TASK_STATE_DISABLED")
                 {
                     st.TaskStats   = "无效";
                     st.NextRunTime = "N/A";
                 }
                 //<EndBoundary>2020-09-20T22:00:00</EndBoundary>
                 string taskXml = t.Xml;
                 string desc    = Regex.Match(taskXml, @"<Description>(?<desc>.*?)</Description>").Groups["desc"].Value;
                 st.Description   = desc != "" ? desc : "N/A";
                 st.ActionPath    = Regex.Match(taskXml, "<Command>(?<path>.*?)</Command>").Groups["path"].Value;
                 st.TaskStartTime = Regex.Match(taskXml, "<StartBoundary>(?<st>.*?)</StartBoundary>").Groups["st"].Value.Replace("T", " ");
                 st.TaskEndTime   = Regex.Match(taskXml, "<EndBoundary>(?<st>.*?)</EndBoundary>").Groups["st"].Value.Replace("T", " ");
                 taskList.Add(st);
             }
         }
         return(taskList);
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex);
         return(null);
     }
 }
Example #18
0
        public static bool TryGetTask(string taskName, out IRegisteredTask outTask)
        {
            outTask = null;
            TryConnectScheduler();
            ITaskFolder folder = scheduler.GetFolder("\\");

            IRegisteredTaskCollection tasks = folder.GetTasks(1);

            foreach (IRegisteredTask task in tasks)
            {
                if (task.Name.Equals(taskName))
                {
                    outTask = task;
                    break;
                }
            }

            return(outTask != null);
        }
        /// <summary>
        /// Returns the list of <see cref="AutorunObject"/> objects that have been added through TaskScheduler
        /// </summary>
        public List <AutorunObject> GetAutorunObjects()
        {
            List <AutorunObject> resultObjectsList = new List <AutorunObject>();

            TaskScheduler.TaskScheduler taskService = new TaskScheduler.TaskScheduler();
            taskService.Connect();

            ITaskFolder rootFolder = taskService.GetFolder(@"\");

            IRegisteredTaskCollection regTask = rootFolder.GetTasks(0);

            foreach (IRegisteredTask task in regTask)
            {
                ITaskDefinition    taskDefinition    = task.Definition;
                ITriggerCollection triggerCollection = taskDefinition.Triggers;

                foreach (ITrigger trigger in triggerCollection)
                {
                    if (trigger.Type == _TASK_TRIGGER_TYPE2.TASK_TRIGGER_BOOT ||
                        trigger.Type == _TASK_TRIGGER_TYPE2.TASK_TRIGGER_LOGON)
                    {
                        IActionCollection actionCollection = taskDefinition.Actions;

                        foreach (IExecAction action in actionCollection)
                        {
                            if (action.Type != _TASK_ACTION_TYPE.TASK_ACTION_EXEC)
                            {
                                continue;
                            }

                            var autorunObject = AutorunObjectHelper.GetAutorunObject(action.Path, action.Arguments, AutorunTypes.Scheduler);

                            if (autorunObject != null)
                            {
                                resultObjectsList.Add(autorunObject);
                            }
                        }
                    }
                }
            }

            return(resultObjectsList);
        }
        /// <summary>
        /// 检查定时任务是否存在
        /// </summary>
        /// <param name="taskName"></param>
        /// <returns></returns>
        #region public static bool checkTask(String taskName)
        public static bool checkTask(String taskName, out _TASK_STATE state)
        {
            //标识任务计划是否存在
            var isExists = false;
            //获取计划列表
            IRegisteredTaskCollection taskList = GetAllTasks();

            foreach (IRegisteredTask task in taskList) //循环遍历列表
            {
                if (task.Name.Equals(taskName))        //计划名称相等,计划存在
                {
                    isExists = true;                   //标识为true
                    state    = task.State;             //返回计划任务的状态

                    return(isExists);
                }
            }
            //不存在,返回位置状态
            state = _TASK_STATE.TASK_STATE_UNKNOWN;
            return(isExists);
        }
Example #21
0
 /// <summary>
 /// 任务计划是否存在
 /// </summary>
 /// <param name="strTaskName">任务计划名称</param>
 /// <returns></returns>
 public static bool IsExists(string strTaskName)
 {
     try
     {
         bool isExists = false;
         IRegisteredTaskCollection tasks_exists = GetAllTaskschd();
         for (int i = 1; i <= tasks_exists.Count; i++)
         {
             IRegisteredTask registeredTask = tasks_exists[i];
             if (registeredTask.Name.Equals(strTaskName))
             {
                 isExists = true;
                 break;
             }
         }
         return(isExists);
     }
     catch (Exception ex)
     {
         TXTHelper.Logs(ex.ToString());
         return(false);
     }
 }
Example #22
0
        IRegisteredTask GetTask()
        {
            IRegisteredTask task = null;

            TaskSchedulerClass ts = new TaskSchedulerClass();

            ts.Connect(null, null, null, null);

            ITaskFolder folder = ts.GetFolder("\\");

            IRegisteredTaskCollection tasks_exists = folder.GetTasks(1);

            for (int i = 1; i <= tasks_exists.Count; i++)
            {
                IRegisteredTask t = tasks_exists[i];
                if (t.Name == TaskName)
                {
                    task = t;
                    break;
                }
            }

            return(task);
        }
Example #23
0
        private void Form1_Load(object sender, EventArgs e)
        {
            ListViewItem listViewItem = new ListViewItem();
            string       item, name;
            int          start, dot;

            #region Logon

            LogonResult.Items.Clear();
            LogonResult.Groups.Clear();

            #region LocalMachine->Run

            string        HKLM_Logon  = "Software\\Microsoft\\Windows\\CurrentVersion\\Run";
            ListViewGroup LogonGroup1 = new ListViewGroup();
            LogonGroup1.Header = "HKLM\\" + HKLM_Logon;
            LogonResult.Groups.Add(LogonGroup1);
            RegistryKey hklm_logon = Registry.LocalMachine.OpenSubKey(HKLM_Logon);
            for (int i = 0; i < hklm_logon.GetValueNames().Length; i++)
            {
                item = hklm_logon.GetValueNames().ElementAt(i);
                name = hklm_logon.GetValue(item).ToString();
                if (name == "")
                {
                    continue;
                }
                start = name.IndexOf(":") - 1;
                if (start == -2)
                {
                    start = 0;
                }
                dot = name.IndexOf(".");
                string file = name.Substring(start, dot - start + 4);
                if (file.IndexOf(":") == -1)
                {
                    file = "C:\\Windows\\system32\\" + file;
                }
                listViewItem = new ListViewItem(item);
                try
                {
                    FileVersionInfo fileVersion = FileVersionInfo.GetVersionInfo(name);
                    listViewItem.SubItems.Add(fileVersion.FileDescription);
                    listViewItem.SubItems.Add(fileVersion.ProductName);
                }
                catch
                {
                    listViewItem.SubItems.Add("");
                    listViewItem.SubItems.Add("");
                }
                listViewItem.SubItems.Add(name);
                LogonGroup1.Items.Add(listViewItem);
                LogonResult.Items.Add(listViewItem);
            }

            #endregion LocalMachine->Run

            #region CurrentUser->Run

            string        HKCU_Logon  = "Software\\Microsoft\\Windows\\CurrentVersion\\Run";
            ListViewGroup LogonGroup2 = new ListViewGroup();
            LogonGroup2.Header = "HKCU\\" + HKCU_Logon;
            LogonResult.Groups.Add(LogonGroup2);
            RegistryKey hkcu_logon = Registry.CurrentUser.OpenSubKey(HKCU_Logon);
            for (int i = 0; i < hkcu_logon.GetValueNames().Length; i++)
            {
                item = hkcu_logon.GetValueNames().ElementAt(i);
                name = hkcu_logon.GetValue(item).ToString();
                if (name == "")
                {
                    continue;
                }
                start = name.IndexOf(":") - 1;
                if (start == -2)
                {
                    start = 0;
                }
                dot = name.IndexOf(".");
                string file = name.Substring(start, dot - start + 4);
                if (file.IndexOf(":") == -1)
                {
                    file = "C:\\Windows\\system32\\" + file;
                }
                listViewItem = new ListViewItem(item);
                try
                {
                    FileVersionInfo fileVersion = FileVersionInfo.GetVersionInfo(file);
                    listViewItem.SubItems.Add(fileVersion.FileDescription);
                    listViewItem.SubItems.Add(fileVersion.ProductName);
                }
                catch
                {
                    listViewItem.SubItems.Add("");
                    listViewItem.SubItems.Add("");
                }
                listViewItem.SubItems.Add(file);
                LogonGroup2.Items.Add(listViewItem);
                LogonResult.Items.Add(listViewItem);
            }

            #endregion CurrentUser->Run

            #region LocalMachine->AlternateShell

            string        HCLM_AlternateShell = "SYSTEM\\CurrentControlSet\\Control\\SafeBoot";
            ListViewGroup LogonGroup3         = new ListViewGroup();
            LogonGroup3.Header = "HKLM\\" + HCLM_AlternateShell;
            LogonResult.Groups.Add(LogonGroup3);
            RegistryKey hklm_alternateshell = Registry.LocalMachine.OpenSubKey(HCLM_AlternateShell);
            for (int i = 0; i < hklm_alternateshell.GetValueNames().Length; i++)
            {
                item = hklm_alternateshell.GetValueNames().ElementAt(i);
                name = hklm_alternateshell.GetValue(item).ToString();
                if (name == "")
                {
                    continue;
                }
                start = name.IndexOf(":") - 1;
                if (start == -2)
                {
                    start = 0;
                }
                dot = name.IndexOf(".");
                string file = name.Substring(start, dot - start + 4);
                if (file.IndexOf(":") == -1)
                {
                    file = "C:\\Windows\\system32\\" + file;
                }
                listViewItem = new ListViewItem(name);
                try
                {
                    FileVersionInfo fileVersion = FileVersionInfo.GetVersionInfo(name);
                    listViewItem.SubItems.Add(fileVersion.FileDescription);
                    listViewItem.SubItems.Add(fileVersion.ProductName);
                }
                catch
                {
                    listViewItem.SubItems.Add("");
                    listViewItem.SubItems.Add("");
                }
                listViewItem.SubItems.Add(file);
                LogonGroup3.Items.Add(listViewItem);
                LogonResult.Items.Add(listViewItem);
            }

            #endregion LocalMachine->AlternateShell

            #region LocalMachine->wow64run

            string        HCLM_wow64run = "SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Run";
            ListViewGroup LogonGroup4   = new ListViewGroup();
            LogonGroup4.Header = "HKLM\\" + HCLM_wow64run;
            LogonResult.Groups.Add(LogonGroup4);
            RegistryKey hklm_wow64run = Registry.LocalMachine.OpenSubKey(HCLM_wow64run);
            for (int i = 0; i < hklm_wow64run.GetValueNames().Length; i++)
            {
                item = hklm_wow64run.GetValueNames().ElementAt(i);
                name = hklm_wow64run.GetValue(item).ToString();
                if (name == "")
                {
                    continue;
                }
                start = name.IndexOf(":") - 1;
                if (start == -2)
                {
                    start = 0;
                }
                dot = name.IndexOf(".");
                string file = name.Substring(start, dot - start + 4);
                if (file.IndexOf(":") == -1)
                {
                    file = "C:\\Windows\\system32\\" + file;
                }
                listViewItem = new ListViewItem(item);
                try
                {
                    FileVersionInfo fileVersion = FileVersionInfo.GetVersionInfo(name);
                    listViewItem.SubItems.Add(fileVersion.FileDescription);
                    listViewItem.SubItems.Add(fileVersion.ProductName);
                }
                catch
                {
                    listViewItem.SubItems.Add("");
                    listViewItem.SubItems.Add("");
                }
                listViewItem.SubItems.Add(file);
                LogonGroup4.Items.Add(listViewItem);
                LogonResult.Items.Add(listViewItem);
            }

            #endregion LocalMachine->wow64run

            #region LocalMachine->InstalledComponents

            string        HCLM_InstalledComponents = "SOFTWARE\\Microsoft\\Active Setup\\Installed Components";
            ListViewGroup LogonGroup5 = new ListViewGroup();
            LogonGroup5.Header = "HKLM\\" + HCLM_InstalledComponents;
            LogonResult.Groups.Add(LogonGroup5);
            RegistryKey hklm_InstalledComponents = Registry.LocalMachine.OpenSubKey(HCLM_InstalledComponents);
            for (int i = 0; i < hklm_InstalledComponents.GetValueNames().Length; i++)
            {
                item = hklm_InstalledComponents.GetValueNames().ElementAt(i);
                name = hklm_InstalledComponents.GetValue(item).ToString();
                if (name == "")
                {
                    continue;
                }
                start = name.IndexOf(":") - 1;
                if (start == -2)
                {
                    start = 0;
                }
                dot = name.IndexOf(".");
                string file = name.Substring(start, dot - start + 4);
                if (file.IndexOf(":") == -1)
                {
                    file = "C:\\Windows\\system32\\" + file;
                }
                listViewItem = new ListViewItem(item);
                try
                {
                    FileVersionInfo fileVersion = FileVersionInfo.GetVersionInfo(name);
                    listViewItem.SubItems.Add(fileVersion.FileDescription);
                    listViewItem.SubItems.Add(fileVersion.ProductName);
                }
                catch
                {
                    listViewItem.SubItems.Add("");
                    listViewItem.SubItems.Add("");
                }
                listViewItem.SubItems.Add(file);
                LogonGroup5.Items.Add(listViewItem);
                LogonResult.Items.Add(listViewItem);
            }

            #endregion LocalMachine->InstalledComponents

            #endregion Logon

            #region Services

            ServicesResult.Items.Clear();
            ServicesResult.Groups.Clear();

            #region LocalMachine->Services

            string        HKLM_Services  = "System\\CurrentControlSet\\Services";
            ListViewGroup ServicesGroup1 = new ListViewGroup();
            ServicesGroup1.Header = "HKLM\\" + HKLM_Services;
            ServicesResult.Groups.Add(ServicesGroup1);
            RegistryKey hklm_services = Registry.LocalMachine.OpenSubKey(HKLM_Services);
            int         type;
            string      path, image_path;
            foreach (string ServiceName in hklm_services.GetSubKeyNames())
            {
                RegistryKey key = hklm_services.OpenSubKey(ServiceName);
                if (key.GetValue("Type") != null)
                {
                    type = (int)key.GetValue("Type");
                }
                else
                {
                    type = 0;
                }
                if (key.GetValue("ImagePath") != null)
                {
                    path = key.GetValue("ImagePath").ToString();
                }
                else
                {
                    path = "";
                }

                /*Type:
                 * 1 2 4 8: drivers
                 * 16 win32服务,以其自身进程运行,不与其他服务共享可执行文件(即宿主进程)
                 * 32 win32服务,作为共享进程运行,与其他服务共享可执行文件(即宿主进程)
                 * 272 win32服务,以其自身进程运行,同时服务可与桌面交互,接受用户输入,交互服务必须以localsystem本地系统帐户运行
                 * 288	win32服务,以共享进程运行,同时服务可与桌面交互,接受用户输入,交互服务必须以localsystem本地系统帐户运行
                 */
                if ((type >= 16))
                {
                    string tmp_path = path.ToLower();
                    // find svchost
                    if (path.ToLower().IndexOf("svchost") != -1)
                    {
                        RegistryKey parameter = key.OpenSubKey("Parameters");
                        if (parameter != null)
                        {
                            image_path = parameter.GetValue("ServiceDLL").ToString();
                        }
                        else
                        {
                            if (path.IndexOf(":") == -1)
                            {
                                image_path = "C:\\Windows\\system32\\" + path;
                            }
                            else
                            {
                                start      = path.IndexOf(":") - 1;
                                image_path = path.Substring(start, path.IndexOf(".") - start + 4);
                            }
                        }
                    }
                    else
                    {
                        if (path.IndexOf(":") == -1)
                        {
                            image_path = "C:\\Windows\\system32\\" + path;
                        }
                        else
                        {
                            start      = path.IndexOf(":") - 1;
                            image_path = path.Substring(start, path.IndexOf(".") - start + 4);
                        }
                    }
                    try
                    {
                        FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(image_path);
                        listViewItem = new ListViewItem(ServiceName);
                        listViewItem.SubItems.Add(fileVersionInfo.FileDescription);
                        listViewItem.SubItems.Add(fileVersionInfo.ProductName);
                        listViewItem.SubItems.Add(image_path);
                    }
                    catch
                    {
                        listViewItem = new ListViewItem(ServiceName);
                        listViewItem.SubItems.Add("");
                        listViewItem.SubItems.Add("");
                        listViewItem.SubItems.Add(image_path);
                    }
                    ServicesGroup1.Items.Add(listViewItem);
                    ServicesResult.Items.Add(listViewItem);
                }
            }

            #endregion LocalMachine->Services

            #endregion Services

            #region Drivers

            DriversResult.Items.Clear();
            DriversResult.Groups.Clear();

            #region LocalMachine->Drivers

            ListViewGroup DriversGroup1 = new ListViewGroup();
            DriversGroup1.Header = "HKLM\\" + HKLM_Services;
            DriversResult.Groups.Add(DriversGroup1);
            foreach (string DriversName in hklm_services.GetSubKeyNames())
            {
                RegistryKey key = hklm_services.OpenSubKey(DriversName);
                if (key.GetValue("ImagePath") != null)
                {
                    path = key.GetValue("ImagePath").ToString();
                }
                else
                {
                    path = "";
                }
                if (key.GetValue("Type") != null)
                {
                    type = (int)key.GetValue("Type");
                }
                else
                {
                    type = 0;
                }

                /*Type:
                 * 1 2 4 8: drivers
                 * 16 win32服务,以其自身进程运行,不与其他服务共享可执行文件(即宿主进程)
                 * 32 win32服务,作为共享进程运行,与其他服务共享可执行文件(即宿主进程)
                 * 272 win32服务,以其自身进程运行,同时服务可与桌面交互,接受用户输入,交互服务必须以localsystem本地系统帐户运行
                 * 288	win32服务,以共享进程运行,同时服务可与桌面交互,接受用户输入,交互服务必须以localsystem本地系统帐户运行
                 */
                if ((type == 1) || (type == 2) || (type == 4) || (type == 8))
                {
                    if (path.IndexOf(".sys") == -1)
                    {
                        continue;
                    }
                    if (path.IndexOf("\\SystemRoot") != -1)
                    {
                        image_path = "C:\\Windows" + path.Substring(path.IndexOf("\\SystemRoot") + 10, path.Length - 10);
                    }
                    else
                    {
                        if (path.IndexOf(":") != -1)
                        {
                            start      = path.IndexOf(":") - 1;
                            dot        = path.IndexOf(".");
                            image_path = path.Substring(start, dot - start + 4);
                        }
                        else
                        {
                            image_path = "C:\\Windows\\" + path;
                        }
                    }
                    listViewItem = new ListViewItem(DriversName);
                    try
                    {
                        FileVersionInfo fileVersion = FileVersionInfo.GetVersionInfo(image_path);
                        listViewItem.SubItems.Add(fileVersion.FileDescription);
                        listViewItem.SubItems.Add(fileVersion.ProductName);
                    }
                    catch
                    {
                        listViewItem.SubItems.Add("");
                        listViewItem.SubItems.Add("");
                    }
                    listViewItem.SubItems.Add(image_path);
                    DriversGroup1.Items.Add(listViewItem);
                    DriversResult.Items.Add(listViewItem);
                }
            }

            #endregion LocalMachine->Drivers

            #endregion Drivers

            #region ScheduledTasks

            ScheduledTasksResult.Items.Clear();
            ScheduledTasksResult.Groups.Clear();

            #region C:\Windows\System32\Tasks

            string        ScheduledTask_Path   = "C:\\Windows\\System32\\Tasks";
            ListViewGroup ScheduledTasksGroup1 = new ListViewGroup();
            ScheduledTasksGroup1.Header = ScheduledTask_Path;
            ScheduledTasksResult.Groups.Add(ScheduledTasksGroup1);
            TaskSchedulerClass ts = new TaskSchedulerClass();
            ts.Connect(null, null, null, null);
            ITaskFolder folder = ts.GetFolder("\\");
            IRegisteredTaskCollection tasks_exists = folder.GetTasks(1);
            for (int i = 1; i <= tasks_exists.Count; i++)
            {
                IRegisteredTask t = tasks_exists[i];
                try
                {
                    listViewItem = new ListViewItem(t.Name);
                    string xml         = t.Xml;
                    string description = xml.Substring(xml.IndexOf("<Description>") + 13, xml.IndexOf("</Description>") - xml.IndexOf("<Description>") - 13);
                    string imagePath   = xml.Substring(xml.IndexOf("<Command>") + 9, xml.IndexOf("</Command>") - xml.IndexOf("<Command>") - 9);
                    if (imagePath.IndexOf("{") > 0)
                    {
                        imagePath = imagePath.Substring(0, imagePath.IndexOf("{"));
                    }
                    string publisher = xml.Substring(xml.IndexOf("<Author>") + 8, xml.IndexOf("</Author>") - xml.IndexOf("<Author>") - 8);
                    listViewItem.SubItems.Add(description);
                    listViewItem.SubItems.Add(publisher);
                    listViewItem.SubItems.Add(imagePath);
                }
                catch
                {
                    listViewItem = new ListViewItem(t.Name);
                    string xml = t.Xml;
                    listViewItem.SubItems.Add("");
                    listViewItem.SubItems.Add("");
                    string imagePath = xml.Substring(xml.IndexOf("<Command>") + 9, xml.IndexOf("</Command>") - xml.IndexOf("<Command>") - 9);
                    if (imagePath.IndexOf("{") > 0)
                    {
                        imagePath = imagePath.Substring(0, imagePath.IndexOf("{"));
                    }
                    listViewItem.SubItems.Add(imagePath);
                }

                ScheduledTasksGroup1.Items.Add(listViewItem);
                ScheduledTasksResult.Items.Add(listViewItem);
            }

            #endregion C:\Windows\System32\Tasks

            #endregion ScheduledTasks

            #region InternetExplorer

            InternetExplorerResult.Items.Clear();
            InternetExplorerResult.Groups.Clear();

            #region LocalMachine->IE BHO

            string        HKLM_CLSID  = "Software\\Classes\\CLSID";
            string        HKLM_IE_BHO = "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Browser Helper Objects";
            ListViewGroup IEGroup1    = new ListViewGroup();
            IEGroup1.Header = "HKLM\\" + HKLM_IE_BHO;
            InternetExplorerResult.Groups.Add(IEGroup1);
            RegistryKey hklm_ie_bho = Registry.LocalMachine.OpenSubKey(HKLM_IE_BHO);
            RegistryKey hklm_clsid  = Registry.LocalMachine.OpenSubKey(HKLM_CLSID);
            foreach (string InternetName in hklm_ie_bho.GetSubKeyNames())
            {
                if (InternetName == null)
                {
                    continue;
                }
                foreach (string key in hklm_clsid.GetSubKeyNames())
                {
                    if (key == null)
                    {
                        continue;
                    }
                    if (key.Equals(InternetName))
                    {
                        RegistryKey     subkey          = hklm_clsid.OpenSubKey(key).OpenSubKey("InprocServer32");
                        FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(subkey.GetValue("").ToString());
                        ListViewItem    ie = new ListViewItem();
                        ie.SubItems[0].Text = fileVersionInfo.InternalName;
                        ie.SubItems.Add(fileVersionInfo.FileDescription);
                        ie.SubItems.Add(fileVersionInfo.ProductName);
                        ie.SubItems.Add(fileVersionInfo.FileName);
                        if (!fileVersionInfo.InternalName.Equals(""))
                        {
                            IEGroup1.Items.Add(ie);
                            InternetExplorerResult.Items.Add(ie);
                        }
                    }
                }
            }

            #endregion LocalMachine->IE BHO

            #endregion InternetExplorer

            #region KnownDLLs

            KnownDLLResult.Items.Clear();
            KnownDLLResult.Groups.Clear();

            #region LocalMachine->Known DLLs

            string        HKLM_KnownDLLs = "System\\CurrentControlSet\\Control\\Session Manager\\KnownDlls";
            ListViewGroup KnownDLLsGroup = new ListViewGroup();
            KnownDLLsGroup.Header = "HKLM\\" + HKLM_KnownDLLs;
            KnownDLLResult.Groups.Add(KnownDLLsGroup);
            string      dlldir   = "";
            RegistryKey hklm_dll = Registry.LocalMachine.OpenSubKey(HKLM_KnownDLLs);
            foreach (string dll in hklm_dll.GetValueNames())
            {
                if (hklm_dll.Equals("DllDirectory"))
                {
                    dlldir = hklm_dll.GetValue(dll).ToString();
                    break;
                }
            }
            foreach (string valuename in hklm_dll.GetValueNames())
            {
                string dllname = hklm_dll.GetValue(valuename).ToString();
                if (dllname.IndexOf(".dll") == -1)
                {
                    continue;
                }
                listViewItem = new ListViewItem(valuename);
                path         = dlldir + "\\" + dllname;
                try
                {
                    FileVersionInfo fileVersion = FileVersionInfo.GetVersionInfo(path);
                    listViewItem.SubItems.Add(fileVersion.FileDescription);
                    listViewItem.SubItems.Add(fileVersion.ProductName);
                    listViewItem.SubItems.Add(path);
                }
                catch
                {
                    listViewItem.SubItems.Add("");
                    listViewItem.SubItems.Add("");
                    listViewItem.SubItems.Add(path);
                }
                KnownDLLsGroup.Items.Add(listViewItem);
                KnownDLLResult.Items.Add(listViewItem);
            }

            #endregion LocalMachine->Known DLLs

            #endregion KnownDLLs
        }
Example #24
0
        /// //////////////////////////////////////////////////
        /// //////////////////////////////////////////////////
        /// ////   Scheduled Tasks   /////////////////////////
        /// //////////////////////////////////////////////////
        /// //////////////////////////////////////////////////

        public static void ProcessTaskFoler(ITaskFolder taskFolder)
        {
            int         idx;
            string      name, path;
            string      ePs, schXm, msTaskPath;
            _TASK_STATE state;

            IRegisteredTaskCollection taskCol = taskFolder.GetTasks((int)_TASK_ENUM_FLAGS.TASK_ENUM_HIDDEN);

            for (idx = 1; idx <= taskCol.Count; idx++)
            {
                IRegisteredTask runTask = taskCol[idx];

                // Some lolbins..remove common ones if a lot of noise is created
                string[] interestingTasks = new string[] {
                    "certutil.exe", "cmstp.exe", "control.exe", "csc.exe", "cscript.exe", "bitsadmin", "installutil.exe", "jsc.exe", "makecab.exe", "msbuild.exe",
                    "dfsvc.exe", "diskshadow.exe", "dnscmd.exe", "esentutl.exe", "eventvwr.exe", "expand.exe", "extexport.exe", "extrac32.exe",
                    "findstr.exe", "forfiles.exe", "ftp.exe", "ie4uinit.exe", "ieexec.exe", "infdefaultinstall.exe",
                    "msconfig.exe", "msdt.exe", "mshta.exe", "msiexec.exe", "odbcconf.exe", "pcalua.exe", "pcwrun.exe", "presentationhost.exe",
                    "print.exe", "regasm.exe", "regedit.exe", "reg.exe", "runonce.exe", "runscripthelper.exe", "schtasks.exe", "scriptrunner.exe",
                    "syncappvpublishingserver.exe", "verclsid.exe", "wab.exe", "wmic.exe", "wscript.exe"
                };

                name  = runTask.Name;
                path  = runTask.Path;
                state = runTask.State;
                schXm = runTask.Xml;

                string schXml = schXm.ToLower();

                msTaskPath = "\\Microsoft\\";
                ePs        = "powershell.exe";

                string sched_out = "          Name: " + name + "\n" + "          Path: " + path + "\n" + "          State: " + state + "\n";

                bool mspath = path.Contains(msTaskPath);
                bool bPs    = schXml.Contains(ePs);

                /////////////////////
                // Based off array //
                /////////////////////
                foreach (string itasks in interestingTasks)
                {
                    bool chkItasks = schXml.Contains(itasks);
                    if (chkItasks == true)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("    [-] Detected interesting String in task: ");
                        Console.ForegroundColor = ConsoleColor.DarkRed;
                        Console.WriteLine(sched_out);
                        //Console.WriteLine(schXm);
                        Console.WriteLine("-----------------------");
                    }
                }
                ////////////////
                // Powershell //
                ////////////////
                if (bPs == true)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("    [-] PowerShell Detected - task info: ");
                    Console.WriteLine("-----------------------");
                    Console.WriteLine(sched_out);
                    //Console.WriteLine(schXm);
                    Console.WriteLine("-----------------------");
                }
                ////////////////////////////
                // Outside Microsoft folder
                ////////////////////////////
                if (mspath == false)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("      [-] Detected Task outside of Microsoft folder - task info: ");
                    Console.ForegroundColor = ConsoleColor.DarkRed;
                    Console.WriteLine(sched_out);
                }
            }

            ITaskFolderCollection taskFolderCol = taskFolder.GetFolders(0);

            for (idx = 1; idx <= taskFolderCol.Count; idx++)
            {
                ProcessTaskFoler(taskFolderCol[idx]);
            }
        }
Example #25
0
 internal V2TaskEnumerator(TaskFolder folder, IRegisteredTaskCollection iTaskColl, Regex filter = null)
 {
     fld         = folder;
     iEnum       = iTaskColl.GetEnumerator();
     this.filter = filter;
 }
Example #26
0
        //Получаем данные из планировщика - возвращает список (List) файлов(Prgrm)
        public async Task <List <Prgrm> > GetFilesListFromSheduler()
        {
            return(await Task.Run(() =>
            {
                List <Prgrm> Files = new List <Prgrm>();   //Создаем список программ которые будем возвращать


                TaskScheduler.TaskScheduler ts = new TaskScheduler.TaskScheduler(); //Создаем экземпляр TaskScheduler

                ts.Connect();                                                       //Подключаемся к localhost без параметров
                ITaskFolder folder = ts.GetFolder(@"\");                            //Задаем подпапку планировщика
                IRegisteredTaskCollection Tasks = folder.GetTasks(flags: 0);        //Получаем все задания из этой подпапки
                foreach (IRegisteredTask task in Tasks)                             //Перебираем эти задания
                {
                    ITriggerCollection tasktriggers = task.Definition.Triggers;     //Коллекция триггеров текущего задания

                    bool HaveDesiredTriggerforCurrentTaskActions = false;           //Флаг для помечания, что в задании есть хотябы один триггер, который запускает это задание при запуске системы

                    foreach (ITrigger trigger in tasktriggers)                      //Перебираем триггеры
                    {
                        //Если нашелся тригер являющийся триггером, срабатывающим при запуске системы, то помечаем флаг как true
                        if (trigger.Type == _TASK_TRIGGER_TYPE2.TASK_TRIGGER_BOOT)
                        {
                            HaveDesiredTriggerforCurrentTaskActions = true;
                        }
                    }

                    if (HaveDesiredTriggerforCurrentTaskActions == true)                             //Если существует хоть один триггер, запускающий данное задание при запуске систмемы
                    {
                        IActionCollection TaskActions = task.Definition.Actions;                     //Находим коллекцию действий (Actions) текщего задания

                        foreach (IAction TaskAction in TaskActions)                                  //Перебираем коллекцию Actions
                        {
                            if (TaskAction.Type == _TASK_ACTION_TYPE.TASK_ACTION_EXEC)               //Если текущий Action является Action ом для запуска exe приложения
                            {
                                IExecAction execAction = (IExecAction)TaskAction;                    //Приводим наш TasAction к типу IExecAction, который содержит св-ва которые мы ищем

                                string FilePath = execAction.Path;                                   //Путь к файлу
                                string FileParams = execAction.Arguments;                            //Аргументы командной строки

                                if (FilePath.Contains('"'))                                          //Если путь к файлу содержит ковычки
                                {
                                    FilePath = FilePath.Substring(FilePath.IndexOf("\"") + 1);       //Отрезаем первую кавычку
                                    FilePath = FilePath.Substring(0, FilePath.IndexOf("\"")).Trim(); //Отрезаем последнюю кавычку и отрезаем пробелы
                                }
                                string StartupType = "Task Scheduler";                               //для св-ва тип запуска экземпляра Prgrm
                                BitmapFrame Icon = null;                                             //Для св-ва Icon кземпляра Prgrm
                                string FileName = "";                                                //Для св-ва FileName кземпляра Prgrm

                                if (System.IO.File.Exists(FilePath))                                 //Если файл по этому пути существует
                                {
                                    FileInfo fileinfo = new FileInfo(FilePath);                      //Находим имя
                                    FileName = fileinfo.Name;

                                    //Получаем Иконку
                                    Icon = GetIcon(FilePath);
                                }
                                //Cоздаем экземпляр prgrm для добавления
                                Prgrm prgrm = new Prgrm()
                                {
                                    Icon = Icon, FileName = FileName, FilePath = FilePath, CmdlineParams = FileParams, StartupType = StartupType
                                };
                                //Заполняем информацию о сертификатах и компании из сертификата либо из атрибутов файла при отсутвии сертификата
                                prgrm = FillCertData(prgrm);

                                //Формируем список екземпляров Prgrm  для return, заполняя его полученными значениями
                                Files.Add(prgrm);
                            }
                        }
                    }
                }



                return Files;//Возвращаем список файлов
            }));
        }