Windows process from command line

Command line process auditing

Applies To: Windows Server 2016, Windows Server 2012 R2

Author: Justin Turner, Senior Support Escalation Engineer with the Windows group

This content is written by a Microsoft customer support engineer, and is intended for experienced administrators and systems architects who are looking for deeper technical explanations of features and solutions in Windows Server 2012 R2 than topics on TechNet usually provide. However, it has not undergone the same editing passes, so some of the language may seem less polished than what is typically found on TechNet.

Overview

The pre-existing process creation audit event ID 4688 will now include audit information for command line processes.

It will also log SHA1/2 hash of the executable in the Applocker event log

  • Application and Services Logs\Microsoft\Windows\AppLocker

You enable via GPO, but it is disabled by default

  • «Include command line in process creation events»

Figure SEQ Figure \* ARABIC 16 Event 4688

Review the updated event ID 4688 in REF _Ref366427278 \h Figure 16. Prior to this update none of the information for Process Command Line gets logged. Because of this additional logging we can now see that not only was the wscript.exe process started, but that it was also used to execute a VB script.

Configuration

To see the effects of this update, you will need to enable two policy settings.

You must have Audit Process Creation auditing enabled to see event ID 4688.

To enable the Audit Process Creation policy, edit the following group policy:

Policy location: Computer Configuration > Policies > Windows Settings > Security Settings > Advanced Audit Configuration > Detailed Tracking

Policy Name: Audit Process Creation

Supported on: Windows 7 and above

Description/Help:

This security policy setting determines whether the operating system generates audit events when a process is created (starts) and the name of the program or user that created it.

These audit events can help you understand how a computer is being used and to track user activity.

Event volume: Low to medium, depending on system usage

Default: Not configured

In order to see the additions to event ID 4688, you must enable the new policy setting: Include command line in process creation events

Table SEQ Table \* ARABIC 19 Command line process policy setting

Policy Configuration Details
Path Administrative Templates\System\Audit Process Creation
Setting Include command line in process creation events
Default setting Not Configured (not enabled)
Supported on: ?
Description This policy setting determines what information is logged in security audit events when a new process has been created.

This setting only applies when the Audit Process Creation policy is enabled. If you enable this policy setting the command line information for every process will be logged in plain text in the security event log as part of the Audit Process Creation event 4688, «a new process has been created,» on the workstations and servers on which this policy setting is applied.

If you disable or do not configure this policy setting, the process’s command line information will not be included in Audit Process Creation events.

Default: Not configured

Note: When this policy setting is enabled, any user with access to read the security events will be able to read the command line arguments for any successfully created process. Command line arguments can contain sensitive or private information such as passwords or user data.

When you use Advanced Audit Policy Configuration settings, you need to confirm that these settings are not overwritten by basic audit policy settings. Event 4719 is logged when the settings are overwritten.

The following procedure shows how to prevent conflicts by blocking the application of any basic audit policy settings.

To ensure that Advanced Audit Policy Configuration settings are not overwritten

Open the Group Policy Management console

Right-click Default Domain Policy, and then click Edit.

Double-click Computer Configuration, double-click Policies, and then double-click Windows Settings.

Double-click Security Settings, double-click Local Policies, and then click Security Options.

Double-click Audit: Force audit policy subcategory settings (Windows Vista or later) to override audit policy category settings, and then click Define this policy setting.

Click Enabled, and then click OK.

Additional Resources

Try This: Explore command line process auditing

Enable Audit Process Creation events and ensure the Advance Audit Policy configuration is not overwritten

Create a script that will generate some events of interest and execute the script. Observe the events. The script used to generate the event in the lesson looked like this:

Enable the command line process auditing

Execute the same script as before and observe the events

Windows commands

All supported versions of Windows (server and client) have a set of Win32 console commands built in.

This set of documentation describes the Windows Commands you can use to automate tasks by using scripts or scripting tools.

Prerequisites

The information that is contained in this topic applies to:

  • Windows Server 2019
  • Windows Server (Semi-Annual Channel)
  • Windows Server 2016
  • Windows Server 2012 R2
  • Windows Server 2012
  • Windows Server 2008 R2
  • Windows Server 2008
  • Windows 10
  • Windows 8.1

Command shell overview

The Command shell was the first shell built into Windows to automate routine tasks, like user account management or nightly backups, with batch (.bat) files. With Windows Script Host you could run more sophisticated scripts in the Command shell. For more information, see cscript or wscript. You can perform operations more efficiently by using scripts than you can by using the user interface. Scripts accept all Commands that are available at the command line.

Windows has two command shells: The Command shell and PowerShell. Each shell is a software program that provides direct communication between you and the operating system or application, providing an environment to automate IT operations.

PowerShell was designed to extend the capabilities of the Command shell to run PowerShell commands called cmdlets. Cmdlets are similar to Windows Commands but provide a more extensible scripting language. You can run Windows Commands and PowerShell cmdlets in Powershell, but the Command shell can only run Windows Commands and not PowerShell cmdlets.

For the most robust, up-to-date Windows automation, we recommend using PowerShell instead of Windows Commands or Windows Script Host for Windows automation.

You can also download and install PowerShell Core, the open source version of PowerShell.

Incorrectly editing the registry may severely damage your system. Before making the following changes to the registry, you should back up any valued data on the computer.

To enable or disable file and directory name completion in the Command shell on a computer or user logon session, run regedit.exe and set the following reg_DWOrd value:

To set the reg_DWOrd value, use the hexadecimal value of a control character for a particular function (for example, 0 9 is Tab and 0 08 is Backspace). User-specified settings take precedence over computer settings, and command-line options take precedence over registry settings.

Command-line reference A-Z

To find information about a specific command, in the following A-Z menu, click the letter that the command starts with, and then click the command name.

How to show full command line of all processes in Windows

On Windows, in the Task Manager it is possible to see the command line of each processes but it is truncated.

How can I see the complete command line of each running process?

2 Answers 2

In cmd, run the following:

To filter for a particular program:

The other properties that you can query for processes are:

  • Caption
  • CommandLine
  • CreationClassName
  • CreationDate
  • CSCreationClassName
  • CSName
  • Description
  • ExecutablePath
  • ExecutionState
  • Handle
  • HandleCount
  • InstallDate
  • KernelModeTime
  • MaximumWorkingSetSize
  • MinimumWorkingSetSize
  • Name
  • OSCreationClassName
  • OSName
  • OtherOperationCount
  • OtherTransferCount
  • PageFaults
  • PageFileUsage
  • ParentProcessId
  • PeakPageFileUsage
  • PeakVirtualSize
  • PeakWorkingSetSize
  • Priority
  • PrivatePageCount
  • ProcessId
  • QuotaNonPagedPoolUsage
  • QuotaPagedPoolUsage
  • QuotaPeakNonPagedPoolUsage
  • QuotaPeakPagedPoolUsage
  • ReadOperationCount
  • ReadTransferCount
  • SessionId
  • Status
  • TerminationDate
  • ThreadCount
  • UserModeTime
  • VirtualSize
  • WindowsVersion
  • WorkingSetSize
  • WriteOperationCount
  • WriteTransferCount

Getting another process command line in Windows

I am trying to get another process commandline (on WinXP 32bit). I do the following:

After first call pbi.UniqueProcessID is correct. But after calling ZwReadVirtualMemory I get command line for my process, not requested one.

I also used ReadProcessMemore & NtQueryInformationProcess, but get the same result.

Can anybody help?

Here http://forum.sysinternals.com/get-commandline-of-running-processes_topic6510_page1.html is being said that this code works. Unfortunately, I do not have access to post on this forum to ask themselves.

5 Answers 5

Duplicate of How to query a running process for it’s parameters list? (windows, C++) , so I’ll just copy my answer from there over here:

You can’t reliably get that information. There are various tricks to try and retrieve it, but there’s no guarantee that the target process hasn’t already mangled that section of memory. Raymond Chen discussed this awhile back on The Old New Thing.

It looks like ZwReadVirtualMemory is called only once. That is not enough. It has to be called for each level of pointer indirection. In other words when you retrieve a pointer it points to other process’ address space. You cannot read it directly. You have to call ZwReadVirtualMemory again. For the case of those data structures ZwReadVirtualMemory has to be called 3 times: once to read PEB (that is what the code above does), once to read RTL_USER_PROCESS_PARAMETERS and once to read UNICODE_STRING’s buffer. The following code fragment worked for me (error handling omitted for clarity and I used documented ReadProcessMemory API instead of ZwReadVirtualMemory):

Why we see see the command line of our own process? That is because processes are laid out in a similar way. Command line and PEB-related structures are likely to have the same addresses. So if you missed ReadProcessMemory you end up exactly with local process’ command line.

Управление процессами из командной строки

Способов управлять процессами в Windows предостаточно, и командная строка занимает в них далеко не первое место. Однако иногда бывают ситуации, когда все остальные инструменты кроме командной строки недоступны, например некоторые вредоносные программы могут блокировать запуск Task Manager и подобных ему программ. Да и просто для общего развития полезно знать способы управления компьютером из командной строки.

Для управления процессами в командной строке есть две утилиты — tasklist и taskkill. Первая показывает список процессов на локальном или удаленном компьютере, вторая позволяет их завершить. Попробуем …

Если просто набрать команду tasklist в командной строке, то она выдаст список процессов на локальном компьютере.

По умолчанию информация выводится в виде таблицы, однако ключ /fo позволяет задать вывод в виде списка или в формате CSV, а ключ /v показывает более подробную информацию о процессах, например команда tasklist /v /fo list выведет подробное описание всех процессов в виде списка.

Список получится довольно большой, поэтому попробуем уточнить запрос. Для этого используем ключ /fi , который позволяет использовать фильтры для вывода данных, например команда tasklist /fi ″username eq user″ /fi ″memusage le 40000″ выводит список процессов пользователя user, которые потребляют не больше 40Мб памяти.

Найдя процессы, которые необходимо завершить, воспользуемся командой taskkill. Завершать процессы можно по имени, идентификатору процесса (PID) или задав условия с помощью фильтров. Для примера запустим несколько экземпляров блокнота (notepad.exe) и попробуем завершить его разными способами.

Ключ /f завершает процесс принудительно, а /t завершает все дочерние процессы.

Полную справку по командам tasklist и taskkill можно получить, введя их с ключом /?

Теперь пустим в ход тяжелую артиллерию PowerShell. Его можно запустить не выходя из командной строки. Для получения списка процессов используем командлет Get-Process.

Чтобы не выводить весь список процессов можем воспользоваться командлетом Where-Object, который задает фильтр для выводимой информации. Для примера выведем список процессов, которые загружают процессор и отсортируем их по возрастанию нагрузки с помощью команды:

Get-Process | where <$_.cpu -gt 0>| sort cpu

С помощью PowerShell мы можем получить любую информацию о любом процессе. В качестве примера возьмем процесс cmd и выведем список его свойств командой:

Get-Process -Name cmd | Get-Member -Membertype property

Выбираем те свойства, что нам интересны ( в примере имя и ID процесса, путь к файлу, используемые модули и время запуска) и выводим их в виде списка командой:

Get-Process -Name cmd | Format-List name, id, path, modules, starttime

Таким образом мы можем посмотреть когда и кем был запущен процесс, сколько он потребляет ресурсов, где находится исполняемый файл и еще много различной информации.

Для завершения процесса в PowerShell есть командлет Stop-Process. Он завершает указанный процесс по его имени или идентификатору. Однако мы поступим по другому и передадим результат выполнения командлета Get-Process по конвейеру:

Get-Process | where <$_.name -match ″notepad″>| Stop-Process

Get-Process не может показать процессы на удаленном компьютере, для этого воспользуемся командлетом Get-WmiObject , например посмотрим процессы на удаленном компьютере PC командой:

Get-WmiObject win32_process -computername PC | ft name, processid, description

Для боле полного ознакомления с PowerShell можно воспользоваться встроенной справкой, для вызова справки нужно набрать Get-Help ″имя командлета″

Ну и для полноты обзора рассмотрим еще одно средство для управления процессами из командной строки. Это утилиты Pslist и Pskill входящие в состав пакета PSTools от компании Sysinternals.

Эти утилиты не требуют специальной установки, достаточно просто скопировать их на диск. Для запуска нужно зайти в папку с утилитами и ввести в командной строке необходимую команду.

Pslist может выводить информацию о процессах по имени или ID, например командой pslist notepad -x выведем подробную информацию о нашем «многострадальном» блокноте.

Особенностью утилиты Pslist является режим task-manager. В этом режиме информация автоматически обновляется, причем можно задать время работы и интервал обновления. Запускается режим ключом -s , например командой tasklist -s -r 10 запускаем режим программу в режиме task-manager с обновлением раз в 10 сек.

Завершение процесса программой pskill предельно просто, вводим команду и имя (или ID) процесса и все.

Справку по утилитам Pslist и Pskill можно посмотреть, введя команду с ключом /?

И еще, все манипуляции с процессами необходимо выполнять с правами администратора, для этого командную строку требуется запускать с повышением привилегий.

Читайте также:  A4tech x7 xl 747h драйвера windows 10
Оцените статью