By the way, if you place this command in a batch script, remember to use “%%i” instead of “%i” for your parameters, or you’ll get an error message like
FOR /F documentation
Findstr documentation
Solution 2:
If the processes name difference is not very complex, e.g. if the name is always the same
you can use the /FI option of taskkill directly
==> taskkill documentation
Solution 3:
I used this in command line:
name variable can contains blank surround with ”
You should embed the value of the variable
into the command line:
If you use an older Python, try
Solution 2:
Maybe its because pid is a string,
idk if i am right but try
Solution 1:
Several changes:
The command_to_process needs back quotes (“) on both sides of the command.
This article is using wmic commands
. Wmic is a tool of the command prompt to get system information. The full form of wmic is the Windows Management Interface command
. The list of Commands for gathering information are mentioned below.
The command is used to get the computer’s serial number. This is very helpful to get the serial number of our bios. We will get our serial number instead of O. E. M.
wmic bios get serialnumber
wmic bios get serialnumber command
The command is used to get Mac Address is given below but there other be other ways also by which we can get our Mac Address.
wmic nic get macaddress :: Method 1 getmac :: Method
This command helps to gather all information about a CPU i.e. name, device id, number of cores, max clock speed, status. This can also help us in figuring out our CPU specs.
wmic cpu
We can also send attributes to get the particular details of a CPU in a better view. You may use a particular attribute to get particular details of CP.
wmic cpu get caption, name, deviceid, numberofcores, maxclockspeed, status
get cpu command
Given_Ram_Size (in bits) / 8 = New_Ram_Size (int bytes)
wmic computersystem get totalphysicalmemory
In many cases, we need to know the size of the disc as well as the partition of our/someone’s disk. Here is the command to get the details of the partition of the disc. Here also, like in CPU, we can get the particular detail of the disc, like getting the name or size or type or getting everything in one shot.
The size given here is also in terms of bits. We can convert it into byte by dividing the given size by 8.
Given_Ram_Size (in bits) / 8 = New_Ram_Size (int bytes)
wmic partition get name,size,type
wmic partition get name,size,type
These are the commands which can help us to get the list of all processes running on our computer, and we can also close them by using these commands. These commands are very useful to get to know what tasks are running on someone’s machine. It gives us a list of processes that are running in our background.
wmic process list
wmic process list command
We can terminate these tasks by using the command:
wmic process where name="name_of_file" call terminate
Note:
Put the name of the ‘.exe file’ in place of “name_of_file”
Example:
wmic process list
wmic process where name="Calculator.exe" call terminate
terminate calculator using cmd
wmic product ::OR wmic product get name,version
wmic product get name, version
Basic Volume Details
This command gives us the details of a particular volume of the disc. This also gives us the serial number of the volume of that disc.
vol volume_letter:
Note:
Replace volume_letter with the letter of the volume you wish to use.
This command gives us the window’s version. This helps us figure out that if the updates are installed in our system or what is our window’s version. The command pop up a new window about windows
where we can see our Windows version.
winver
This command gives us a list of all large files and files which are harmful. This can also help us to figure out which file is taking more space and we can also delete those files to clean some memory in the disc.
chkdsk
This command gives us all the basic information about our computer such as:
- Host Name
- OS Name
- OS Version
- OS Manufacturer
- OS Configuration
- Os Build Type
- Registered Owner
- Product ID
- Original Install Date
- Bios Version
- Processor
- Input Locale
- Time Zone
- & many more
systeminfo
This command gives us whole details of our hard disk where we can select volume get whole details of that volume.
diskpart ::'disk part' will get us to an infinite loop. list disk ::'list disk' will give us the status and the size of the hard disk partition select disk_name ::Enter our disk name instead of 'disk_name' and our disk will be selected detail disk ::This will give us option which we can use to manipulate our disk exit ::This will finally help us to exit the infinite loop
The WMIC tool was introduced in Windows XP Professional and has been included in every version of Windows since. Furthermore, it can be used to manage every Windows version since Window 95, although 9x and NT require the Microsoft WMI Core add-on to be installed.
In this post, I will discuss wmic commands I find very useful from a forensic standpoint.
<img data-original-height="348" data-original-width="620" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi30WCjY5B1hiTpcnoO_qJKTH38Q8Nb8pg40KclSyAZrjuyuIIdOKkP0mRyXPY-IyoKe63ZN0tBMhwazt2s4Mjko-T_9Hrm4QElqUkLC0irIj_04krLyjPOV3GrVcCaCedfofxFMEmz-ipwd8DdYNeB8QONQDrmC3vX7y4CCww1YB8sGHmRt0xvSx3O/w496-h279/images%20.jpeg”>
To get information about the computer system under investigation.
wmic computersystem list brief
To get information about the operating system
To obtain information about the CPU.
wmic cpu get processorID
wmic cpu List instance
wmic cpu get Name, Caption, MaxClockSpeed, DeviceID, status
To find applications that start on boot
To retrieve BIOS information
wmic bios get smbiosbiosversion
wmic bios get name, version, serialnumber
To get information about boot configuration
wmic bootconfig get BootDirectory, Caption, TempDirectory, Lastdrive
To find services that are set to start automatically
wmic service where StartMode="Auto" get Name, State
To get information about the hard disk drive
wmic diskdrive get Name, Manufacturer, Model, InterfaceType, MediaLoaded, MediaType
To get information about the partitions in the hard disk.
wmic logicaldisk get Name, Compressed, Description, DriveType, FileSystem, FreeSpace, SupportsDiskQuotas, VolumeDirty, VolumeName
wmic partition get Caption, Size, PrimaryPartition, Status, Type
To obtain information about disk quota
To obtain information about the Network Interface Card
wmic nic get AdapterType, AutoSense, Name, Installed, MACAddress, PNPDeviceID, PowerManagementSupported, Speed, StatusInfo
To obtain information about network configuration
wmic nicconfig get MACAddress, DefaultIPGateway, IPAddress, IPSubnet, DNSHostName, DNSDomain
wmic nicconfig get MACAddress, IPAddress, DHCPEnabled, DHCPLeaseExpires, DHCPLeaseObtained, DHCPServer
wmic nicconfig get MACAddress, IPAddress, DNSHostName, DNSDomain, DNSDomainSuffixSearchOrder, DNSEnabledForWINSResolution, DNSServerSearchOrder
wmic nicconfig get MACAddress, IPAddress, WINSPrimaryServer, WINSSecondaryServer, WINSEnableLMHostsLookup, WINSHostLookupFile
To get information about CDROM
wmic cdrom get Name, Drive, Volumename
To obtain information about environment variables
wmic environment get Description, Name, SystemVariable, VariableValue
To obtain information about groups
wmic group Caption, InstallDate, LocalAccount, Domain, SID, Status
To get a list of IP interfaces
wmic nicconfig where IPEnabled='true'
To get information about the lists of all running processes
wmic process get Caption, CommandLine, Handle, HandleCount, PageFaults, PageFileUsage, PArentProcessId, ProcessId, ThreadCount
wmic process get name, processid, parentprocessid, executablepath
To identify and analyse a particular process, say, svchost.exe typically manipulated by malicious actors
wmic process where (Name='svchost.exe') get name, processid, parentprocessid, executablepath
To get a list of all available attributes of all running process.
wmic process list full
To spot odd executables
wmic process WHERE "NOT ExecutablePath LIKE '%WINDOWS%'"
To obtain the executable paths of the above
wmic process WHERE "NOT ExecutablePath LIKE '%WINDOWS%'" Get ExecutablePath
etermine the maximum RAM capacity.
wmic memphysical get Manufacturer, Model, SerialNumber, MaxCapacity, MemoryDevices
To determine where the pagefile.sys file is, along with some information about it.
wmic pagefile get Caption, CurrentUsage, Status, TempPageFile
To oobtain information about
memory object caching system
Identify any local system accounts that are enabled (guest, etc.)
To obtain information about network protocol
wmic netprotocol get Caption, Description, GuaranteesSequencing, SupportsBroadcasting, SupportsEncryption, Status
To retrieve information about the desktop
wmic desktop get Name, ScreenSaverExecutable, ScreenSaverActive, Wallpaper /format:list
To retrieve information about desktop monitor
wmic desktopmonitor get screenheight, screenwidth
For event log queries
wmic ntevent where (LogFile='system' and SourceName='W32Time') get Message, TimeGenerated
wmic ntevent where (LogFile='system' and SourceName='W32Time' and Message like '%timesource%') get Message, TimeGenerated
wmic ntevent where (LogFile='system' and SourceName='W32Time' and EventCode!='29') get TimeGenerated, EventCode, Message
To obtain information about printers connected
wmic printer get DeviceID, DriverName, Hidden, Name, PortName, PowerManagementSupported, PrintJobDataType, VerticalResolution, Horizontalresolution
To obtain information about the registry
wmic Registry get CurrentSize, MaximumSize, ProposedSize, Status
To obtain information about system accounts
wmic sysaccount get Caption, Domain, Name, SID, SIDType, Status
To obtain information about time zone
wmic timezone get Caption, Bias, DaylightBias, DaylightName, StandardName
To obtain information about Memory chip
wmic memorychip get BankLabel, Capacity, Caption, CreationClassName, DataWidth, Description, Devicelocator, FormFactor, HotSwappable, InstallDate, InterleaveDataDepth, InterleavePosition, Manufacturer, MemoryType, Model, Name, OtherIdentifyingInfo, PartNumber, PositionInRow, PoweredOn, Removable, Replaceable, SerialNumber, SKU, Speed, Status, Tag, TotalWidth, TypeDetail, Version
This is by no means an exhaustive list of useful WMIC commands. You can do just about anything with it with respect to querying a machine or starting and stopping processes and services. The commands discussed here can be combined with those of an earlier post
for a more robust incident response
Windows Management Instrumentation
(WMI)
— это базовая технология как для управления так и для слежения за работой платформы Windows.
Только пользователи локальной группы «Администраторы» имеют право запускать WMIC.
В основе структуры данных в WBEM лежит Common Information Model (CIM), реализующая объектно-ориентированный подход к представлению компонентов системы. C IM является расширяемой моделью, что позволяет программам, системам и драйверам добавлять в неё свои классы, объекты, методы и свойства.
Важной особенностью WMI является то, что хранящиеся в нём объекты соответствуют динамическим ресурсам, то есть параметры этих ресурсов постоянно меняются, поэтому параметры таких объектов не хранятся постоянно, а создаются по запросу потребителя данных. Хранилище свойств объектов WMI называется репозиторием и расположено в системной папке операционной системы Windows:
Так как WMI построен по объектно-ориентированному принципу, то все данные операционной системы представлены в виде объектов и их свойств и методов.
Все классы группируются в пространства имен, которые иерархически упорядочены и логически связаны друг с другом по определенной технологии или области управления. В WMI имеется одно корневое пространство имен Root, которое в свою очередь имеет 4 подпространства: CIMv2, Default, Security и WMI.
Классы имеют свойства и методы и находятся в иерархической зависимости друг от друга, то есть классы-потомки могут наследовать или переопределять свойства классов-родителей, а также добавлять свои свойства.
Свойства классов используются для однозначной идентификации экземпляра класса и для описания состояния используемого ресурса. Обычно все свойства классов доступны только для чтения, хотя некоторые из них можно модифицировать определенным методом. Методы классов позволяют выполнить действия над управляемым ресурсом.
Каждому экземпляру класса можно обратиться по полному пути, который имеет следующую структуру:
ComputerName
– имя компьютера
NameSpace
– название пространства имен
ClassName
– имя класса
KeyProperty1=Value1, KeyProperty2=Value2
– свойства объекта и значения, по
которому он идентифицируется.
Пример обращения к процессу с именем «Calc.exe», который запущен на локальной машине:
Экземпляры классов могут генерировать события, к которым можно подписываться. При наступлении события WMI автоматически создает экземпляр того класса, которому соответствует это событие. Такой механизм удобно использовать для выполнения определенной команды при наступлении определенного события, то есть следить за состоянием объектов операционной системы.
Общая безопасность в WMI реализуется на уровне операционной системы, а дополнительная политика безопасности основана на уровнях пространств имен и протокола DCOM. То есть если пользователь не имеет права делать какое-то действие через операционную систему, он не сможет это сделать и через WMI
. Если же пользователю дано какое-то право в операционной системе, то это ещё не означает, что это право будет и в WMI, так как в WMI действуют дополнительные параметры безопасности на уровне пространств имен.
Для вызова удаленных процедур WMI использует модель DCOM. В случае если возникает ошибка «Dcom Access Denied» то действия будут следующими: меня «Выполнить»->»dcomcnfg»->»Службы компонентов(Component Services)->Компьютеры->Мой компьютер->Свойства(правая кнопка мыши)->вкладка Безопасность COM Уровни олицетворения могут принимать следующие значения:
Уровни аутентификации (подлинности) могут принимать следующие значения:
wmimgmt.msc
— оснастка консоли управления MMC для настройки WMI на локальном компьютере.
winmgmt.exe
— консольная утилита управления WMI локального компьютера.
wbemtest.exe
— графическая утилита для взаимодействия со структурой WMI на локальном или удаленном компьютере.
wmic.exe
— консольная утилита для взаимодействия со структурой WMI на локальном компьютере.
mofcomp.exe
– MOF compiler for extending the WMI structure, managing the WMI class library, and restoring the repository.
Now I will show practical examples used in my daily work:
Deleting large .log files
wmic datafile where “drive=’c:’ and Extension=’.log’ and FileSize>’100000′” call delete
List of blocked accounts (output to a file on disk with:)
Architecture Definition (As an example on
Server
2008)
wmicOS get OSArchitecture
Specifies the server type (Server 2008)
The command returns a numeric value. For
Windows 2008 Server
they
next
:
7 = Windows Server 2008 Standard Edition (full installation)
8 = Windows Server 2008 Datacenter Edition (full installation
10 = Windows Server 2008 Enterprise Edition (full installation)
12 = Windows Server 2008 Datacenter Edition (core installation)
13 =
Windows Server 2008 Standard Edition (core installation)
14 = Windows Server 2008 Enterprise Edition (core installation)
42 = Hyper-V Server 2008
wmic OS get OperatingSystemSKU
How to connect to remote systems.
End the process by name.
wmic.exe process where name=”calc.exe” delete
Wmic process where (caption=”notepad.exe”) call terminate
Get more detailed help on running commands.
process call /?:full
If you need to get information about the notification service on your computer
/node: service where name=”alerter” list
V
displaying information on the screen
process where (name=”explorer.exe”) get caption,commandline,handle
To present the output to a file in tabular mode
/output:c:\table.htm process get /format:htable
path win32_process.name=”explorer.exe” get caption,commandline,handle
When connecting to remote systems, you can take computer names from a text file (
server
1,
server
2,
server
3)
Store in external
XML
– history file launched in the current session
wmic
-commands and results of their execution.
H
to start a new process
process call create cmd.exe
Connecting to another computer is also possible in this way
H
to restart the computer
H
to turn off the computer
V
print operating system properties
os get /value
Display information about the status of all registered services on computers
server
1,
server
2,
server
3
/node:server1,server2,server3 /output:c:\service.htm service get name,displayname,state /format:htable
Z
start and stop services
/node:server1 service where (name=”squid.exe”) call startservice
P
forcefully shut down the computer
wmic os where primary=”TRUE” call win32shutdown 6
In order to start the service it is necessary to (display the list of services in the system)
service list brief
/output:c:\service.html service list full /format:htable
H
for wmic to work
, must
The WMI service must be set to autostart and DCOM connections must be allowed:
1) In the registry key HKLM\SOFTWARE\MICROSOFT\OLE, set the EnableDCOM value to “Y” and EnableRemoteConnect to “Y”. The default value for EnableRemoteConnect is “N”.
2) In the registry key \HKLM\SOFTWARE\Microsoft\wbem\cimom, set the AutostartWin9X value to “2”. Set the EnableAnonConnections value to “1”.
3) Add the Winmgmt.exe file to startup. The file is located in the \Windows\WBEM directory.
Models
DCOM
matchedTCP
-port 135.netsh firewall add portopening TCP 135 DCOM_TCP135
Remotely turn on the Remote Desktop service (
Remote
Desktop
)
Output of services that run with rights
LocalSystem
/output:c:\id\cns.html service where startname=”LocalSystem” get Caption,name,started
List share on local machine
Enumeration of all paths to folders from which programs are launched
wmic.exe process get “ExecutablePath”, “ProcessID”
Drivers in the system can be stopped or started for example:
net stop beepnet start beep
sc stop beep
sc start beep
wmic sysdriver where name=’beep’ call PauseService
Methods of the Win32_SystemDriver class
StartService -> start service or driver
StopService -> stops a service or driver
PauseService -> puts a service or driver into a paused state
ResumeService -> restores the state of a driver or service
InterrogateService -> causes a service or driver to update its state in the SCM
Create -> creates a new service or driver
Change -> changes services or driver
ChangeStartMode -> changes the startup mode of a service or driver
Delete Delete -> delete service or driver
Turn off the local machine.ping -n seconds 127.0.0.1>nul&wmic OS WHERE Primary=”TRUE” CALL Win32Shutdown 6
where
seconds
— desired number of seconds +1;Win
32
Shutdown
6 – 6 = 2 (
reboot) + 4 (
force). There will be no visible reboot message.
Useful information collections of parameters.
wmic bios get Caption, Manufacturer, SMBIOSBIOSVersion, Version
wmic baseboard get Manufacturer, Model, Product, SerialNumber, Version
wmic cpu get deviceID, Addresswidth, MaxClockSpeed, Name, Manufacturer, ProcessorID
wmic logicaldisk where drivetype=3 get name, freespace, systemname, filesystem, size, volumeserialnumber
= 1 NoRootDirectory The drive does not have a root directory.
= 2 Removable The drive is a removable storage device, such as a floppy disk drive or a USB flash drive.
= 3 Fixed The drive is a fixed disk.
= 4 Network The drive is a network drive.
= 5 CDRom The drive is an optical disc device, such as a CD or DVD-ROM.
= 6 Ram The drive is a RAM disk.
Z
Give processor prioritywmic process where “name=’notepad.exe'” call setpriority 64
V
executing commands via wmicJust paste it into the command line
wmic process call create ‘cmd.exe /c ping 10.30.10.101’
P
writing DNS suffixes remotelywmic /node: /failfast:on nicconfig call SetDNSSuffixSearchOrder (ford-i.ru,tc-toyota.local,lexus.local)
nicconfig where index=8 call setdnsserversearchorder(“10.30.5.2″,”10.30.5.3”)
*
K
commands loaded at system loginwmic startup list full && system
wmic:root\cli>/output:c:\startup_full.html startup list full /format:htable
wmic:root\cli>/output:c:\startup_system.html startup list system /format:htable
How do I Taskkill a PID that keeps changing?
cmd /c FOR /F “usebackq tokens=2 skip=3” %%i IN (
tasklist /fi "services eq NlaSvc"
) DO taskkill /PID %%i
Pass PIDs from tasklist and kill processes with tasklist
FOR /F "usebackq tokens=2" %i IN (`tasklist ^| findstr /r /b "[0-9][0-9]*[.]exe"`) DO taskkill /pid %i
- The command_to_process needs back quotes (“) on both sides of the command.
- Pipes (“|”) inside of the command_to_process need to be escaped with a caret (“^”).
- Your findstr command would match all processes that have a digit before the “.exe”. For example, “myapp4.exe” would also have been killed. The version I provide will match process names solely containing numbers.
- The “skip=2” option would skip the first two lines output from findstr, not tasklist. Since the regular expression won’t match anything in the first two lines output from tasklist, you’re safe to remove the skip option.
By the way, if you place this command in a batch script, remember to use “%%i” instead of “%i” for your parameters, or you’ll get an error message like
i was unexpected at this time.
- FOR /F documentation
- Findstr documentation
If the processes name difference is not very complex, e.g. if the name is always the same
you can use the /FI option of taskkill directly
taskkill /FI "IMAGENAME eq your_image_name_here.exe"
==> taskkill documentation
I used this in command line:
name variable can contain blank surround with ”
How to find a process pid with wmic and kill it with taskkill
for /F "skip=2 tokens=2 delims=," %a in (
'wmic process where " .... " get ProcessID^,Status /format:csv'
) do taskkill /pid %a
Now you have an output from
wmic
with an aditional line at the start (from here the skip), with fields separated with commas (the delim), and three fields included: the node (computername) that is automatically added, the processid (the second token) and a final status field that will not be used but allows us to retrieve the second token in the line without the ending CR
Or you can add an extraditional
for
command to your initial line
for /f ... %a in ( ... ) do for %b in (%a) do taskkil /pid %b
This traditional
for
loop will remove the CR character from the retrieved wmic data that is in %a.
I had a similar problem where I had to stop a task only knowing the name of the running file. The solution was:
for /f "tokens=2 delims=," %%a in (
'wmic service get name^,pathname^,state /format:csv ^| findstr /i /r /c:"SomeServer\.exe.*Running$"'
) do sc stop "%%a"
This will stop the process by name. Maybe you can use the file name instead of the PID?!?
Python program that force kills current program using PID, In Windows, os.kill (pid, signal) is implemented via TerminateProcess (hProcess, signal), but only for values of signal other than 0 and 1. The value of signal is used as the process exit status. We’d like this to be 1 typically for a forced termination, but os.kill is badly designed, so just use 3.
Python program that force kills current program using PID [duplicate]
"pid"
is just a string that consists of three characters. You should embed the value of the variable
pid
into the command line:
os.system(f"ftaskkill /f /pid {pid}")
If you use an older Python, try
os.system("ftaskkill /f /pid {}".format(pid))
Maybe its because pid is a string,
idk if i am right but try
os.system("taskkill /f " + pid)