Introduction to Windows Command Line

 

                                         

                                                  Introduction to Windows Command Line    

The built-in command shell CMD.exe and PowerShell are two implementations included in all Windows hosts. These tools provide direct access to the operating system, automate routine tasks, and provide the user with granular control of any aspect of the computer and installed applications. This module will give us the knowledge, skills, and abilities to effectively administer Windows hosts via the command line.From a penetration testing perspective, we will learn how to utilize built-in Windows tools and commands and third-party scripts and applications to help with reconnaissance, exploitation, and exfiltration of data from within a Windows environment as we move into more advanced modules. 

                                       Command Prompt Vs. PowerShell

There are some key differences between Windows Command Prompt and PowerShell, which we will see throughout this module. One key difference is that you can run Command Prompt commands from a PowerShell console, but to run PowerShell commands from a Command Prompt, you would have to preface the command with powershell (i.e., powershell get-alias). The following table outlines some other key differences. 

PowerShell Command Prompt
Introduced in 2006 Introduced in 1981
Can run both batch commands and PowerShell cmdlets Can only run batch commands
Supports the use of command aliases Does not support command aliases
Cmdlet output can be passed to other cmdlets Command output cannot be passed to other commands
All output is in the form of an object Output of commands is text
Able to execute a sequence of cmdlets in a script A command must finish before the next command can run
Has an Integrated Scripting Environment (ISE) Does not have an ISE
Can access programming libraries because it is built on the .NET framework Cannot access these libraries
Can be run on Linux systems Can only be run on Windows systems

As we can see, the Command Prompt is a much more static way of interacting with the operating system, while PowerShell is a powerful scripting language that can be used for a wide variety of tasks and to create simple and very complex scripts.

                                          Command Prompt Basics

The Command Prompt, also known as cmd.exe or CMD, is the default command line interpreter for the Windows operating system. Originally based on the COMMAND.COM interpreter in DOS, the Command Prompt is ubiquitous across nearly all Windows operating systems. It allows users to input commands that are directly interpreted and then executed by the operating system. A single command can accomplish tasks such as changing a user's password or checking the status of network interfaces. This also reduces system resources, as graphical-based programs require more CPU and memory.

                                                     Accessing CMD

Before we can dig into the basic usage of Command Prompt, we have one fundamental question to answer first and foremost.

How do we access the Command Prompt?

There are multiple ways to access the Command Prompt on a Windows system. How you wish to access the prompt is up to personal preference as well as meeting specific criteria depending on the resources that are available at the time. Before explaining those criteria, there are some essential concepts to explain first.

                                                              Local Access vs. Remote Access

To help better explain these concepts, Several scenarios here are possible depending on the questions we ask ourselves. Is the user located in the same region as us? Is the user in the same building? Is the user's office within reasonable walking distance? Is the user actively connected and working on their machine? These questions will generally factor into our decision from a System Administrator's point of view regarding how we will attempt to access the machine in question. However, we are getting slightly ahead of ourselves, so let's describe what accessing a machine entails and the available access types.

Generally speaking, computer access can be categorized into two main categories:

Local Access

Local access is synonymous with having direct physical access ( or virtual in the instance of a Virtual Machine (VM)) to the machine itself. This level of access does not require the machine to be connected to a network, as it can be accessed directly through the peripherals(monitor, mouse, keyboard, etc.) connected to the machine. From the desktop, we can open up the command prompt by:

1. windows key + r

2. search bar type cmd. or

3. from the drive path C:\Windows\System32\cmd.exe.

We can run our commands, scripts, or other actions as needed.

Remote Access:

On the other hand, remote access is the equivalent of accessing the machine using virtual peripherals over the network. This level of access does not require direct physical access to the machine but requires the user to be connected to the same network or have a route to the machine they intend to access remotely. We can do this through the use of telnet(insecure and not recommended), Secure Shell (SSH), PsExec, WinRM, RDP, or other protocols as needed. For a sysadmin, remote management and access are a boon to our workflow.This convenience for sysadmins can also implant a security threat into our network. If these remote access tools are not configured correctly, or a threat gains access to valid credentials, an attacker can now have wide-ranging access to our environments. We must maintain the proper balance of availability and integrity of our networks for a proper security posture.

Now some basic command:

In the previous section, we were introduced to the general concepts of the Command Prompt and how we can access it. This section will expand upon the previous one by introducing the help functionality within Command Prompt, example output, and some additional resources and concepts.The Command Prompt has a built-in help function that can provide us with detailed information about the available commands on our system and how to utilize those functions. In this section, we are going to cover the following in greater detail:

  • How do we utilize the help functionality within Command Prompt?
  • Why utilizing the help functionality is essential?
  • Where can we find additional external resources for help?
  • How to utilize additional tips and tricks in the Command Prompt?

When first looking at the Command Prompt interface, it can be overwhelming to stare at a blank prompt. Some initial questions might emerge, such as:

  • What commands do I have access to?
  • How do I use these commands?

Let's work on answering the initial question first. While utilizing the Command Prompt, finding help is as easy as typing help. Without any additional parameters, this command provides a list of built-in commands and basic information about each displayed command's usage.


we can see that it prints out a list of system commands (built-ins) and provides a basic description of its functionality. This is important because we can quickly and efficiently parse the list of built-in functions provided by the command prompt to find the function that suits our needs. From here, we can transition into answering the second question on how these commands are used. To print out detailed information about a particular command, we can issue the following: help <command name>. like


just help then the module name . As we can see from the output above, when we issued the command help time, it printed the help details for time. This will work for any system command built-in but not for every command accessible on the system. Certain commands do not have a help page associated with them. However, they will redirect you to running the proper command to retrieve the desired information. For example, running help ipconfig will give us the following output. now see


the help feature let us know that it could not provide more information as the help utility does not directly support it. However, utilizing the suggested command ipconfig /? will provide us with the information we need to utilize the command correctly. Be aware that several commands use the /? modifier interchangeably with help. now let see what is utility and why important . That’s because  only knows about internal shell commands. To get help for external utilities like , you need to use: the command and what you want to know type this name. like

The help utility serves as an offline manual for CMD and DOS compatible Windows operating system commands. Offline refers to the fact that this utility can be used on a system without network access. 

The help utility is meant to bridge that gap when we need assistance with commands or specific syntax for said commands on our system and may not have the external resources available to ask for help. 

here's some online resources at our disposal for additional help regarding the Command Prompt. Microsoft Documentation has a complete listing of the commands that can be issued within the command-line interpreter as well as detailed descriptions of how to use them. Think of it as an online version of the Man pages. ss64 Is a handy quick reference for anything command-line related, including cmd, PowerShell, Bash, and more.We can use the command cls to clear our terminal window of our previous results. view previously ran commands in our Command Prompt's current active session view previously ran commands in our Command Prompt's current active session you can use the function keys F5 or this the command doskey /history. m0reover you will find many things F1 to F9 keys.

***Doskey is an MS-DOS utility that keeps a history of commands issued and allows them to be referenced again.

sometime there will be times when we will need to be able to interrupt an actively running process, effectively killing it. When running a command or process we want to interrupt, we can do so by pressing the ctrl+c key combination

                                                      System Navigation

In previous section we just basic understanding and feel of the Command Prompt. now we will see utilizing our Command Prompt to successfully navigate and move around on the system. like Listing A Directory ,Finding Our Place on the System, Moving Around using CD, Exploring the File System etc. for listing directory. command is : dir


dir is an easy-to-use and surprisingly versatile command. itwill give us a listing of our current directory and its contents. for more specificlly if want your result you  can just type help and find your desire command. it will provide us with a complete listing of the dir's functionality and any additional arguments that we can provide to utilize it is advanced searching capabilities. 

for changing our current directory or move to other directory just type cd or chdir. These commands will move us to whatever directory we specify after the command. 


Note: C:\ is the root directory of all Windows machines and has been determined so since it is inception in the MS-DOS and Windows 3.0 days. The "C:\" designation was used commonly as typically "A:\" and "B:\" were recognized as floppy drives, whereas "C:\" was recognized as the first internal hard drive of the machine.

when looking around the filesystem of a Windows host, it can get tedious to change our directory back and forth or to issue the dir command for each sub-directory. To save us a bit of time and gain some efficiency, we can get a printout of the entire path we specify and its subdirectories by utilizing the tree command. like 


We can utilize the /F parameter with the tree command to see a listing of each file and the directories along with the directory tree of the path. 

Let us take a minute to discuss some directories that can come in handy from an attacker's perspective on a system.Below is a table of common directories that an attacker can abuse to drop files to disk, perform reconnaissance, and help facilitate attack surface mapping on a target host.

Name: Location: Description:
%SYSTEMROOT%\Temp C:\Windows\Temp Global directory containing temporary system files accessible to all users on the system. All users, regardless of authority, are provided full read, write, and execute permissions in this directory. Useful for dropping files as a low-privilege user on the system.
%TEMP% C:\Users\<user>\AppData\Local\Temp Local directory containing a user's temporary files accessible only to the user account that it is attached to. Provides full ownership to the user that owns this folder. Useful when the attacker gains control of a local/domain joined user account.
%PUBLIC% C:\Users\Public Publicly accessible directory allowing any interactive logon account full access to read, write, modify, execute, etc., files and subfolders within the directory. Alternative to the global Windows Temp Directory as it's less likely to be monitored for suspicious activity.
%ProgramFiles% C:\Program Files folder containing all 64-bit applications installed on the system. Useful for seeing what kind of applications are installed on the target system.
%ProgramFiles(x86)% C:\Program Files (x86) Folder containing all 32-bit applications installed on the system. Useful for seeing what kind of applications are installed on the target system.

Creating a directory to add to our structure is a simple endeavor. We can utilize the md and mkdir commands. see here. 



Deleting directories can be accomplished using the rd or rmdir commands. The commands rd and rmdir are explicitly meant for removing directory trees and do not deal with specific files or attributes. 


you can force if it's not delete . by typing rd /s and if you type q with the command then it will never ask you just delete the folder.

RD /S and more for q ::> rd /s/q file path or  name.



Creating and modifying a file from the command line is relatively easy. We have several options that include echo, fsutil, ren, rename, and replace.
let first create a file with echo. just for this type echo  "your massage here" > "file name.txt"


Ren means rename the file allows us to change the name of a file to something new. like just type ren previous file than new file name 


With fsutil, we can do many things, like.... 

1. File Operations

fsutil file createnew  fsutil file createnew testfile.txt 2048
fsutil file setvaliddata  fsutil file setvaliddata testfile.txt 1024
fsutil file setzerodata  fsutil file setzerodata offset=0 length=512         testfile.txt
fsutil file queryfileid          fsutil file queryfileid testfile.txt
fsutil file layout                                 fsutil file layout testfile.txt

💾 2. Volume Management

fsutil volume diskfreefsutil volume diskfree C:
fsutil volume dismountfsutil volume dismount C:
fsutil volume setlabelfsutil volume setlabel C: CyberDrive
fsutil volume querycluster                 fsutil volume querycluster testfile.txt

📊 3. Disk Quotas

fsutil quota queryfsutil quota query C:
fsutil quota enforcefsutil quota enforce C:
fsutil quota disablefsutil quota disable C:
fsutil quota modify                        fsutil quota modify C: 1000000 2000000 Sojon

⚙️ 4. Filesystem Behavior

fsutil behavior set disablelastaccessfsutil behavior set disablelastaccess 1
fsutil behavior query disablelastaccessfsutil behavior query disablelastaccess
fsutil behavior set mftzone                fsutil behavior set mftzone 2

🧩 5. Sparse Files & Reparse Points

fsutil sparse setflagfsutil sparse setflag testfile.txt
fsutil sparse queryflagfsutil sparse queryflag testfile.txt
fsutil reparsepoint query                  fsutil reparsepoint query C:\LinkFolder

🔗 6. Hard Links

fsutil hardlink create                      fsutil hardlink create link.txt testfile.txt

🆔 7. Object Identifiers

fsutil objectid queryfsutil objectid query testfile.txt
fsutil objectid set                         fsutil objectid set testfile.txt

🧨 Bonus: Dirty Bit Control

fsutil dirty queryfsutil dirty query C:
fsutil dirty set                            fsutil dirty set C:

lets explain the example:

1. fsutil file createnew testfile.txt 1024 ===>>  What it does: Creates a file named  with 1024 bytes (1KB) of zeroed data.

2. fsutil volume diskfree C:                  ====>>  What it does: Shows total, free, and available space on the C: drive

3. fsutil behavior set disablelastaccess 1===>> What it does: Stops Windows from updating the "last accessed" timestamp on files — improves performance 

4. fsutil hardlink create link.txt testfile.txt===>> What it does: Creates a hard link named link.txt pointing to testfile.txt

5. fsutil file queryfileid testfile.txt =====>> What it does: Shows the unique file ID used by NTFS.

6.fsutil sparse setflag testfile.txt =======>> What it does: Marks the file as sparse — useful for large files with empty regions.

7.fsutil dirty query C:       ============>> What it does: Checks if the volume is marked dirty (which triggers chkdsk on reboot).

With fsutil, we can do many things, but in this instance, we will use it to create a file. for this just type fsutil file createnew filename.txt size kb.  see this


how to to add text inside the file?? nothinng to  do just type echo and wright your text......... > file.txt

and for clear the text file just type type nul  > file name. txt. if you want to add more line just type echo massge or text >> file name.  this >> used for start from the second line. 


Modifying a directory is more complicated than changing a file. The directory holds data within it for other files or directories. We have several options in any case. Move, Robocopy, and xcopy can copy and make changes to directories and their structures. let's start with move it use to move a file or folder . to move just type move file name destination like C:\Users\Rakib\OneDrive\




We will take a minute to look at xcopy since it still exists in current Windows operating systems, but it is essential to know that it has been deprecated for robocopy. Where xcopy shines is that it can remove the Read-only bit from files when moving them. The syntax for xcopy is xcopy source destination options. As it was with move, we can use wildcards for source files, not destination files. for xcopy just use this command xcopy \y source destination./Y suppresses the overwrite prompt . see 


 Common Options for xcopy::

/s   ===>  Copies subdirectories, but skips empty ones.
/e   ===>  Copies all subdirectories, including empty ones.
/y   ===>  Suppresses overwrite prompts—no "Are you sure?" messages.
/d   ===>  Copies only files that are newer than the destination ones.
/h   ===>  Includes hidden and system files in the copy.
/r   ===>  Overwrites read-only files in the destination.
/c   ===>  Continues copying even if errors occur—no crash on failure.
/v   ===>  Verifies each file after copying to ensure integrity.

Robocopy is xcopy's successor built with much more capability. We can think of Robocopy as merging the best parts of copy, xcopy, and move spiced up with a few extra capabilities. We need to be aware that Robocopy was made for large directories and drive syncing, so it does not like to copy or move singular files by default. It’s built for power users, sysadmins, and glowing deployers like you. you can switch it 

/E       ===>  Copies all subdirectories, including empty ones.
/S       ===>  Copies subdirectories, but skips empty ones.
/Z       ===>  Enables restartable mode—resumes if interrupted.
/COPYALL ===>  Copies all file info: data, attributes, timestamps, ACLs, owner, audit.
/R:n     ===>  Retry n times on failed copies (default is 1 million!).
/W:n     ===>  Wait n seconds between retries.
/MIR     ===>  Mirrors source to destination (includes /E + deletes extras).
/LOG:file ===> Saves output to a log file.
/MT:n    ===>  Multi-threaded copy (up to 128 threads).
/DCOPY:T ===>  Preserves directory timestamps.
/XD dir  ===>  Excludes specific directories.
/XF file ===>  Excludes specific files.

robocopy [source] [destination] [options] /E /Z /COPYALL /R:3 /W:5 .....................


Robocopy can also work with system, read-only, and hidden files. As a user, this can be problematic if we do not have the SeBackupPrivilege and auditing privilege attributes. This could stop us from duplicating or moving files and directories. There is a bit of a workaround, however. We can utilize the /MIR switch to permit ourselves to copy the files we need temporarily. 


We can utilize the more, openfiles, and type commands viewing view the contents of a file or the results of another command printed to it one screen at a time.  let start with more .

start with more It’s simple, powerful, and perfect for scrolling through big logs, config files, or piped command results without flooding your terminal.


as we hit enter or the space bar, it will scroll the document's text for us, showing an increasing amount of the file in view. With large files containing multiple blank lines or a large amount of empty space between data, we can use the /S option to crunch that blank space down to a single line at each point to make it easier to view. This will not modify the file, just like the more command outputs blank space. This is especially handy when dealing with large files or commands that generate a lot of text, such as systeminfo.


With openfiles, we can see what file on our local pc or a remote host has open and from which user. This command requires administrator privileges on the host you are trying to view. With this tool, we can view open files, disconnect open files, and even kick users from accessing specific files. The ability to use this command is not enabled by default on Windows systems. Common switches 

/query       ===>  Displays all open files (remote access only by default)
/disconnect  ===>  Forcefully closes open files by ID, user, or file name
/local       ===>  Enables tracking of locally opened files (requires reboot)
/s <server>  ===>  Run the command on a remote system
/u <user>    ===>  Specify user credentials for remote access
/p <pass>    ===>  Password for the user specified with /u
/fo <format> ===>  Output format: TABLE, LIST, or CSV
/v           ===>  Verbose output (includes process ID, access mode, etc.)

 
this  command—your backstage pass to seeing which files are actively open on your system, especially those accessed remotely through file shares. It’s a bit niche, but incredibly useful for sysadmin tasks, file server diagnostics, and glowing infrastructure control. 

Type can display the contents of multiple text files at once. It is also possible to utilize file redirection with type as well. It is a simple tool but extremely handy. One interesting thing about type is that it will not lock files, so there is no worry of messing something up. it also add two file text. see



Let's talk about talk about I/O ==>> input and output

Here's some symbole of inpute and output: ==> <, >, |, and &

With > we can push the output of a command to a file. Using > this way will create the file if it does not exist, or it will overwrite the specified file's contents. To append to an already populated file, we can utilize >>. these two usage we saw previous example. so I'm skipping this . let's go next.

We were feeding input from a command out before; let us feed input into a command now. We will accomplish that with <The  symbol is called input redirection. It tells the command to read input from a file instead of the keyboard. 


here find options will search this typing words if it's finds it will prints only the containing words line.Another route we can take is to feed the output from a command directly into another command with the | called pipe. it also used for find to search for a specific string.

Let us say we wish to have two commands executed in succession. We can issue the command and follow it with & and then our next command. This will ensure that in this instance, our command A runs first then the session will run command B. It does not care if the command succeeded or failed. It just issues them.


If we care about the result or state of the commands being run, we can utilize && to say run command A, and if it succeeds, run command B. This can be useful if you are doing something that is results dependent such as our cmd-session below. You can also accomplish the opposite of this with || .


Let us look at the del and erase commands.

When utilizing del or erase, remember that we can specify a directory, a filename, a list of names, or even a specific attribute to target when trying to delete files. Let us say we want to get rid of a read-only or hidden file. We can do that with the /A: switch. /A can delete files based on a specific attribute. to delete a read-only file, we can use A:R. This will remove anything within our path that is Read-only. To identify if there are any hidden files within the directory, we can use dir /A:H 


and for deleting directory just type rd directory name.

                                             Gathering System Information

Now that we are familiar with navigating our Windows host using nothing but the Command Prompt let us move on to a fundamental concept accessible to both Systems Administrators and Penetration Testers:  the red team(Penetration Testers, Red Team Operators, hackers, etc.) will find value in being able to scan their hosts and the environment to learn what vulnerable services and machines can be exploited. Whereas the blue team(System Administrators, SOC Analysts, etc.) can use the information to diagnose issues, secure hosts and services, and ensure integrity across the network. so let see what type of info we can gather from the system. 

How do we know what to look for? 

To answer this question, we need to have a basic understanding of all the different types of information available to us on a system. the types of information that we would be looking for can be broken down into the following categories:

Type Description
General System   Information Contains information about the overall target system. Target system information includes but is not limited to the hostname of the machine, OS-specific details (name, version, configuration, etc.), and installed hotfixes/patches for the system.
Networking Information     Contains networking and connection information for the target system and system(s) to which the target is connected over the network. Examples of networking information include but are not limited to the following: host IP address, available network interfaces, accessible subnets, DNS server(s), known hosts, and network resources.
Basic Domain Information Contains Active Directory information regarding the domain to which the target system is connected.
User Information Contains information regarding local users and groups on the target system. This can typically be expanded to contain anything accessible to these accounts, such as environment variables, currently running tasks, scheduled tasks, and known services.

This section will provide more of the why behind gathering information in the first place and the importance of thorough enumeration of a target.our goal with host enumeration here is to use the information gained from the target to provide us with a starting point and guide for how we wish to attack the system.our goal is to eventually escalate our privileges to an account with access to higher privileges or administrative permissions if we are lucky. To do this, we are going to need a thorough understanding of our environment, including the following:

  • What user account do we have access to?
  • What groups does our user belong to?
  • What current working set of privileges does our user have access to?
  • What resources can our user access over the network?
  • What tasks and services are running under our user account?

CMD provides a one-stop shop for information via the systeminfo command. It is excellent for finding relevant information about the host, such as hostname, IP address(es), if it belongs to a domain, what hotfixes have been installed, and much more. This information is super valuable for a sysadmin when trying to diagnose issues.For a hacker, this is a great way to quickly get the lay of the land when you first access a host while leaving a minimal footprint. Running one command is always better than running two or three just to get the same information. We are less likely to be detected this way. Having quick access to things such as the OS version, hotfixes installed, and OS build version can help us quickly determine from a quick Google or ExploitDB search. 


systeminfo contains a lot of information to sift through; however, if we need to retrieve some basic system information such as the hostname or OS version, we can use the name into the command prompt. or systeminfo | findstr /B /C:"OS Name" /C:"OS Version". like for hostname and version. 


some basic network information for our target. just type ipconfig.


If we need additional information or want to dig further into the specific settings applied to each adapter, we can use the following command: ipconfig /all.
The arp utility effectively displays the contents and entries contained within the Address Resolution Protocol (ARP) cache.


Whoami allows us to display the user, group, and privilege information for the user that is currently logged in.If the current user is not a domain-joined account, the NetBIOS name will be provided instead. The current hostname will be used in most cases.  whoami /priv Checking Out Our Privileges. 


Net User allows us to display a list of all users on a host, information about a specific user, and to create or delete users.Net Share allows us to display info about shared resources on the host and to create new shared resources as well.Net Group will display any groups that exist on the host from which we issued the command, create and delete groups, and add or remove users from groups.Keep in mind, net group must be run against a domain server such as the DC, while net localgroup can be run against any host to show us the groups it contains.Net View will display to us any shared resources the host you are issuing the command against knows of. This includes domain resources, shares, printers, and more. 

                                               Finding Files and Directories

 This section will cover how to search for particular files and directories utilizing CMD, why enumerating system files and directories are vital, and provide an essential list of what to look out for while enumerating the system. 

let's start with Using Where: you can use it easily just type where and file name .


you can use where * and the file extension it will show all the . 

sometimes it may happens that it couldn't find the file or folder that you have to move for R recursively seach and specify the path of the file like. where /R filename


 The /R switch forced the where command to search through every folder in the student user directory hive. 

Now, let us talk about Find. Find is used to search for text strings or their absence within a file or files. You can also use find against the console's output or another command. Where find is limited, however, is its capability to utilize wildcard patterns in its matching. We can modify the way find searches using several switches. like 

/v ==>> Displays all lines not containing the string
/c ==>> Displays only the count of matching lines
/n ==>>Displays line numbers with matching lines
/i ==>>Ignores case when searching




The findstr command is similar to find in that it searches through files but for patterns instead. It will look for anything matching a pattern, regex value, wildcards, and more. Think of it as find2.0. For those familiar with Linux, findstr is closer to grep. :

/b            ===> Matches pattern at the beginning of a line  
/e            ===> Matches pattern at the end of a line  
/l            ===> Uses search string literally (no regex)  
/r            ===> Uses search string as a regular expression (default)  
/s            ===> Searches current directory and all subdirectories  
/i            ===> Ignores case when searching  
/x            ===> Matches entire line exactly  
/v            ===> Displays lines that do NOT contain the match  
/n            ===> Displays line numbers with matching lines  
/m            ===> Displays only filenames with matches  
/o            ===> Displays character offset before each match  
/p            ===> Skips files with non-printable characters  
/f:<file>     ===> Reads list of files to search from another file  
/g:<file>     ===> Reads search strings from another file  
/d:<dir1;dir2>===> Searches in multiple directories (semicolon-separated)  
/c:"string"   ===> Searches for exact string, including spaces  
/a:<attr>     ===> Sets color attributes for output (like `color /?`)  
/off[line]    ===> Includes files with the offline attribute  

Let's see some example.

findstr /i "error failed" server.log  
===> Case-insensitive search for "error" or "failed" in server.log

findstr /s /i "disconnect" *.txt  
===> Recursive search for "disconnect" in all .txt files (case-insensitive)

findstr /n /c:"login failed" auth.log  
===> Show line numbers for exact phrase "login failed"

findstr /r "^ERROR.*timeout" *.log  
===> Regex match: lines starting with "ERROR" and containing "timeout"

findstr /m "timeout" *.log  
===> Show only filenames where "timeout" appears

findstr /v "success" results.txt  
===> Show lines that do NOT contain "success"

findstr /x "Operation completed successfully" status.log  
===> Match entire line exactly

findstr /o "disconnect" netlog.txt  
===> Show character offset of "disconnect" in each matching line

findstr /g:keywords.txt /f:filelist.txt  
===> Search for patterns from keywords.txt in files listed in filelist.txt

findstr /d:logs;archive /s "error" *.log  
===> Search for "error" in .log files across multiple directories recursively


we have also learned how to create and modify files. Now let us discuss a few options to evaluate those files and compare them against each other. The comp, fc, and sort commands are how we will accomplish this.

let's try with compare .It compares two files or sets of files byte-by-byte and reports:Whether they’re identical. If not, the offset (position) where differences begin.The differing byte values (in hexadecimal by default

/d            ===> Displays differences in decimal format (instead of hex)
/a            ===> Displays differences as ASCII characters
/l            ===> Displays line number where difference occurs
/n=<lines>    ===> Compares only the first <lines> lines of each file
/c            ===> Ignores case when comparing ASCII text
/off[line]    ===> Includes files with the offline attribute
/?            ===> Displays help for the command



Now let us look at FC for a minute. FC differs in that it will show you which lines are different, not just an individual character (/A) or byte that is different on each line. FC has quite a few more options than Comp has, so be sure to look at the help output to ensure you are using it in the manner you want.
 compares two files or sets of files and shows the differences. It can operate in:
ASCII mode (line-by-line comparison)
Binary mode (byte-by-byte comparison)

/B           ===> Performs a binary comparison (byte-by-byte)
/C           ===> Ignores case during comparison
/A           ===> Shows only first and last lines for each group of differences
/U           ===> Compares files as Unicode text
/L           ===> Compares files as ASCII text
/N           ===> Displays line numbers during ASCII comparison
/LBn         ===> Sets line buffer size (default is 100 lines)
/nnnn        ===> Requires nnnn matching lines after a mismatch to resync
/T           ===> Prevents tab expansion to spaces
/W           ===> Compresses whitespace (treats tabs/spaces as one)
/OFF         ===> Includes files with the offline attribute


Let us look at sort now to help us with that. With Sort, we can receive input from the console, pipeline, or a file, sort it and send the results to the console or into a file or another command. It is relatively simple to use and often will be used in conjunction with pipeline operators such as |, <, and >. We can give it a try now by feeding the contents of the file file to sort.Reads input (from a file or stdin), sorts it line by line, and outputs the result. You can control:
Sort order
Starting character position
Memory usage
Locale behavior
Output destination

/R             ===> Reverses sort order (Z to A, 9 to 0)
/+<N>          ===> Starts comparison at character position N (e.g., /+3 starts at 3rd character)
/T <dir>       ===> Specifies temp directory for sort's working storage
/L <locale>    ===> Overrides system locale for character sorting
/M <KB>        ===> Sets memory usage in kilobytes (min 160 KB)
/REC <N>       ===> Sets max record (line) length (default 4096, max 65535)
/O <file>      ===> Writes sorted output to specified file
/U             ===> Returns only unique lines (Windows 10+)
/?             ===> Displays help

                                                              Environment Variables

 let us discuss one of the more critical topics when thinking about how applications and scripting work in Windows, Environment Variables.Environment variables are settings that are often applied globally to our hosts. Before moving on, we should mention one crucial concept regarding environment variables known as ScopeScope is a programming concept that refers to where variables can be accessed or referenced. 'Scope' can be broadly separated into two categories: 

Global:
  • Global variables are accessible globally. IT means everyone can access it in everywhere.
  • Local:
    • Local variables are only accessible within a local context. Local means that the data stored within these variables can only be accessed and referenced within the function or context in which it has been declared.
  • These variables can be separated into their defined scopes known as System and User scopes. Additionally, there is one more defined scope known as the Process scope.To understand the changes to environment variables taking place, we need some way to view their contents via the command prompt. Thankfully, we have a couple of choices available to us: set and echo.Upon opening the command prompt, you can issue the command set to print all available environment variables on the system. this is because we are not defining the value of %SYSTEMROOT% using set. 

    Now that we have some way to view existing environment variables on our system, we need to be able to create, remove, and manage them from the comfort and safety of our prompt. We have two methods available to us to do so. We can either use set or setx to perform our intended actions.Both set and setx are command line utilities that allow us to display, set, and remove environment variables.The set utility only manipulates environment variables in the current command line session. This means that once we close our current session, any additions, removals, or changes will not be reflected the next time we open a command prompt. Suppose we need to make permanent changes to environment variables. In that case, we can use setx to make the appropriate changes to the registry, which will exist upon restart of our current command prompt session. 

    Note: Using setx, we also have some additional functionality added in, such as being able to create and tweak variables across computers in the domain as well as our local machine.

    Let us move on and create some actual variables we can use.


    As we can see, the environment variable %SYSTEMROOT% is now set and available for us to access. As stated above, this change is considered part of the process scope, as whenever we exit the command prompt and start a new session, this variable will cease to exist on the system. We can remedy this situation by permanently setting this variable in the environment using setx.


    Creating
    The syntax is as follows: setx <variable name> <value> <parameters>. After running this command, we see that our value was saved in the registry since we were provided with the SUCCESS message.

    Adding
    In addition to creating our own variables, we can edit existing ones. Since we are already familiar with creating them, editing is just as easy, except we will replace the existing values. see


    Deleting
    Much like creating and editing variables, we can also remove environment variables in a very similar manner. To remove variables, we cannot directly delete them like we would a file or directory; instead, we must clear their values by setting them equal to nothing.  This action will effectively delete the variable and prevent it from being used as intended due to the value being removed.


    Note: After the command you have to close the current prompt then check.

    Important Environment Variables

    Now that we are comfortable creating, editing, and removing our own environment variables, let us discuss some crucial variables we should be aware of when performing enumeration on a host's environment. Remember that all information found here is provided to us in clear text due to the nature of environment variables. As an attacker, this can provide us with a wealth of information about the current system and the user account accessing it.

    Variable Name Description
    %PATH% Specifies a set of directories(locations) where executable programs are located.
    %OS% The current operating system on the user's workstation.
    %SYSTEMROOT% Expands to C:\Windows. A system-defined read-only variable containing the Windows system folder. Anything Windows considers important to its core functionality is found here, including important data, core system binaries, and configuration files.
    %LOGONSERVER% Provides us with the login server for the currently active user followed by the machine's hostname. We can use this information to know if a machine is joined to a domain or workgroup.
    %USERPROFILE% Provides us with the location of the currently active user's home directory. Expands to C:\Users\{username}.
    %ProgramFiles% Equivalent of C:\Program Files. This location is where all the programs are installed on an x64 based system.
    %ProgramFiles(x86)% Equivalent of C:\Program Files (x86). This location is where all 32-bit programs running under WOW64 are installed. Note that this variable is only accessible on a 64-bit host. It can be used to indicate what kind of host we are interacting with. (x86 vs. x64 architecture)

    Provided here is only a tiny fraction of the information we can learn through enumerating the environment variables on a system. we can visit the following link. Using this information as a guide, we can start gathering any required information from these variables to help us learn about our host and its target environment inside and out.Environment variables are a part of the core functionality of the Windows OS and are considered very useful to both attackers and defenders. Any modifications that can affect system-wide variables should be handled with extreme caution. 

                                                  Managing Services

    Monitoring and controlling services on a host is integral to being an administrator. As an attacker, the ability to interrogate services, find solid points to hook into, and turn services on or off is a sought-after ability when landing on a host. Let's look at this from the perspective of an attacker. We have just landed on a victims host and need to:
    • Determine what services are running.
    • Attempt to disable antivirus.
    • Modify existing services on a system.
    SC is a Windows executable utility that allows us to query, modify, and manage host services locally and over the network. We have other tools, like Windows Management Instrumentation (WMIC) and Tasklist that can also query and manage services for local and remote hosts. Let's dive in and give sc a try. Being able to query services for information such as the process state, process id (pid), and service type is a valuable tool to have in our arsenal as an attacker. We can use this to check if certain services are running or check all existing services and drivers on the system for further information. Before we look specifically into checking the Windows Defender service, let's see what services are currently actively running on the system. We can do so by issuing the following command: sc query type= service.

    Note: The spacing for the optional query parameters is crucial. For example, type= service, type=service, and type =service are completely different ways of spacing this parameter. However, only type= service is correct in this case. 

    We can see a complete list of the actively running services on this system. let's see a specific one.


    We can attempt to stop services via the sc stop <service name> command. Let's try


    It seems we still do not have the proper access to stop this service in particular. This is a good lesson for us to learn, as certain processes are protected under stricter access requirements than what local administrator accounts have.the only thing that can stop and start the Defender service is the SYSTEM machine account. As an attacker, learning the restrictions behind what certain accounts have access or lack of access to is very important because blindly trying to stop services will fill the logs with errors and trigger any alerts showing that a user with insufficient privileges is trying to access a protected process on the system. This will catch the blue team's attention to our activities and begin a triage attempt to kick us off the system and lock us out permanently.  let's find ourselves a service we can take out as an Administrator. The good news is that we can stop the Print Spooler service.
    With such a versatile command, we have many options for manipulating services to do whatever we need them to. To configure services, we must use the config parameter in sc. This will allow us to modify the values of existing services, regardless if they are currently running or not. 


    Note: To revert everything back to normal, you can set start= auto to make sure that the services can be restarted and function appropriately.

    Tasklist is a command line tool that gives us a list of currently running processes on a local or remote host. 

    Net start is a very simple command that will allow us to quickly list all of the current running services on a system. In addition to net start, there is also net stop, net pause, and net continue. These will behave very similarly to sc

    we have WMIC. The Windows Management Instrumentation Command (WMIC) allows us to retrieve a vast range of information from our local host or host(s) across the network.

    every servers if you face problem you can just type help service name. 

                                                               scheduled tasks
    how we can utilize the schtasks command. 

    Query Syntax

    Action Parameter Description
    Query Performs a local or remote host search to determine what scheduled tasks exist. Due to permissions, not all tasks may be seen by a normal user.
    /fo Sets formatting options. We can specify to show results in the Table, List, or CSV output.
    /v Sets verbosity to on, displaying the advanced properties set in displayed tasks when used with the List or CSV output parameter.
    /nh Simplifies the output using the Table or CSV output format. This switch removes the column headers.
    /s Sets the DNS name or IP address of the host we want to connect to. Localhost is the default specified. If /s is utilized, we are connecting to a remote host and must format it as "\\host".
    /u This switch will tell schtasks to run the following command with the permission set of the user specified.
    /p Sets the password in use for command execution when we specify a user to run the task. Users must be members of the Administrator's group on the host (or in the domain). The u and p values are only valid when used with the s parameter.

    Create Syntax

    Action Parameter Description
    Create Schedules a task to run.
    /sc Sets the schedule type. It can be by the minute, hourly, weekly, and much more. Be sure to check the options parameters.
    /tn Sets the name for the task we are building. Each task must have a unique name.
    /tr Sets the trigger and task that should be run. This can be an executable, script, or batch file.
    /s Specify the host to run on, much like in Query.
    /u Specifies the local user or domain user to utilize
    /p Sets the Password of the user-specified.
    /mo Allows us to set a modifier to run within our set schedule. For example, every 5 hours every other day.
    /rl Allows us to limit the privileges of the task. Options here are limited access and Highest. Limited is the default value.
    /z Will set the task to be deleted after completion of its actions.

    Creating a new scheduled task is pretty straightforward. At a minimum, we must specify the following:

    • /create : to tell it what we are doing
    • /sc : we must set a schedule
    • /tn : we must set the name
    • /tr : we must give it an action to take

    Change the Properties of a Scheduled Task

    Change Syntax

    Action Parameter Description
    Change Allows for modifying existing scheduled tasks.
    /tn Designates the task to change
    /tr Modifies the program or action that the task runs.
    /ENABLE Change the state of the task to Enabled.
    /DISABLE Change the state of the task to Disabled.

    we can use the /run parameter to kick the task off immediately. We have queried, created, and changed tasks up to this point. 

    Delete the Scheduled Task(s)

    Delete Syntax

    Action Parameter Description
    Delete Remove a task from the schedule
    /tn Identifies the task to delete.
    /s Specifies the name or IP address to delete the task from.
    /u Specifies the user to run the task as.
    /p Specifies the password to run the task as.
    /f Stops the confirmation warning.





    0 Comments