CMD un PowerShell komandas
Windows komandu (cmd) un PowerShell cmdlet saraksts ar argumentiem un kategoriju filtru.
| Komanda | Kategorija | Līmenis | Apraksts | Galvenie argumenti |
|---|---|---|---|---|
| dir | Faili | core | List directory contents with attributes and sizes | /a show files with all attributes /s recurse into subdirectories /b bare format - filenames only /o sort order (n=name s=size d=date) /p pause after each screen /q display owner |
| cd / chdir | Faili | core | Change current working directory | cd .. move up one level cd \ go to drive root cd /d D:\path also switch drive cd (no args) print current directory |
| copy | Faili | core | Copy one or more files to another location | /y overwrite without prompt /-y prompt before overwrite /b binary copy /a ASCII copy /v verify copy after write |
| xcopy | Faili | core | Extended copy of files and directory trees | /s copy non-empty subdirs /e copy all subdirs (including empty) /i assume destination is directory /h copy hidden and system files /y overwrite without prompt /d copy only newer files /exclude skip patterns from file |
| robocopy | Faili | modern | Robust file copy - mirror, resume, multi-thread | /mir mirror tree (delete extra at dest) /e copy subdirs including empty /z restartable mode (resume on break) /mt:N multi-threaded copy (default 8) /r:N retry count on failure /w:N wait seconds between retries /log:file write log to file /xo exclude older files /eta show estimated time of arrival |
| move | Faili | core | Move or rename files and directories | /y overwrite without prompt /-y prompt on overwrite move file new rename file move *.txt D:\arc batch move |
| del / erase | Faili | core | Delete files permanently (not to Recycle Bin) | /p prompt before each delete /f force delete read-only /s recurse subdirectories /q quiet (no prompt) for wildcards /a filter by attributes (h, s, r, a) |
| mkdir / md | Faili | core | Create one or more directories | mkdir a\b\c create nested path in one call md "My Folder" quote names with spaces |
| rmdir / rd | Faili | core | Remove an empty directory or whole tree | /s remove directory and all contents /q quiet mode (no confirmation) rd dir remove empty directory only |
| mklink | Faili | core | Create symbolic links, hard links, or junctions | /d directory symbolic link /h hard link (file only) /j directory junction mklink link target default file symlink |
| attrib | Faili | core | Display or change file attributes (R H S A) | +r / -r set/clear read-only +h / -h set/clear hidden +s / -s set/clear system /s apply recursively /d also process folders |
| Get-ChildItem | Faili | modern | PowerShell - list filesystem (or registry) items with rich properties | -Path target path or wildcard -Recurse enumerate subdirectories -Filter fast filesystem-level filter -Force include hidden/system items -File / -Directory type filter -Hidden hidden items only |
| Copy-Item | Faili | modern | PowerShell - copy files, directories, or registry items | -Path / -Destination source and target -Recurse copy entire tree -Force overwrite read-only -Exclude pattern to skip -Filter fast provider filter -PassThru emit copied object |
| Remove-Item | Faili | modern | PowerShell - delete files, folders, registry keys | -Recurse delete subtree -Force delete read-only/hidden -Include / -Exclude pattern filters -Confirm prompt before deletion -WhatIf dry-run preview only |
| where | Faili | core | Locate executables in PATH (Linux 'which' equivalent) | where program find first match in PATH /r dir recurse from directory /q quiet (only exit code) /f quote returned paths /t show size and timestamp |
| assoc / ftype | Faili | core | Display or modify file extension associations and command handlers | assoc list all associations assoc .txt show association for ext assoc .txt=txtfile set association ftype list all file types ftype txtfile=notepad %1 set handler |
| Test-Path | Faili | modern | PowerShell - test if a file, folder, registry path, or variable exists | -Path target path -PathType Leaf/Container/Any -IsValid check syntax only -IsAbsolute absolute path check -OlderThan / -NewerThan time predicate |
| type | Teksts | core | Display the contents of a text file on the console | type file.txt print file type a.txt b.txt concatenate type *.log prints filenames + contents |
| more | Teksts | core | Display output one screen at a time (pager) | /c clear screen before each page /s squeeze multiple blank lines +N start at line N SPACE next page ENTER next line |
| findstr | Teksts | core | Search for text patterns in files (regex capable) | /i case-insensitive match /r treat strings as regular expressions /s recurse subdirectories /n prefix output with line numbers /v print lines that do NOT match /c:"phrase" literal multi-word search /g:file read patterns from file |
| find | Teksts | core | Search for a literal text string in files | /i case-insensitive /v invert (lines not containing string) /c count matching lines /n show line numbers |
| fc | Teksts | core | Compare two files and show differences | /a abbreviated text output /b binary compare /n show line numbers (text) /u Unicode compare /w ignore whitespace |
| comp | Teksts | core | Byte-by-byte file comparison | /a display differences as characters /l show line numbers of differences /n=N compare first N lines only /c case-insensitive |
| sort | Teksts | core | Sort lines from input or files alphabetically | /r reverse sort order /+N start sort at column N /m N use N megabytes of memory /o file write output to file |
| Select-String | Teksts | modern | PowerShell - regex search across files (grep equivalent) | -Pattern regex to match -Path / -LiteralPath files to search -CaseSensitive exact case -Context A,B N lines before/after -NotMatch invert (non-matching lines) -List one match per file only -AllMatches all matches per line |
| Get-Content | Teksts | modern | PowerShell - read file content (cat/tail/head equivalent) | -TotalCount N first N lines (head) -Tail N last N lines -Wait follow file (tail -f) -Encoding UTF8, ASCII, Unicode -Raw read as single string -Stream read alternate data streams |
| Set-Content | Teksts | modern | PowerShell - write or replace file content with given string | -Path target file -Value content to write -Encoding UTF8, ASCII, UTF8BOM -Force overwrite read-only -NoNewline do not append CRLF |
| ConvertFrom-Json / ConvertTo-Json | Teksts | modern | PowerShell - parse JSON into objects and back to text | ConvertFrom-Json string → object -Depth N nesting depth (default 2) ConvertTo-Json object → string -Compress no whitespace -AsHashtable parse into hashtable |
| doskey | Teksts | core | Recall and edit command history; define command macros (cmd.exe) | /history print command history /listsize=N history buffer size name=command define macro alias /macros list all macros /macrofile=file load macros from file |
| clip | Teksts | core | Pipe stdout into the Windows clipboard | echo hello | clip copy text to clipboard dir | clip capture command output type file | clip copy file contents |
| tasklist | Procesi | core | Display all running processes with PID and memory | /v verbose (user, status) /svc show services in each process /fi apply filter (e.g. "imagename eq chrome.exe") /fo output format (table, csv, list) /m show DLLs loaded by process |
| taskkill | Procesi | core | Terminate a running process by PID or name | /pid N terminate by process ID /im name.exe terminate by image name /f force terminate (no graceful close) /t also terminate child processes /fi apply filter (e.g. "status eq not responding") |
| start | Procesi | core | Start a separate window to run a program or command | /b start without new window /wait wait for program to exit /min / /max start minimized/maximized /d path starting directory /affinity N CPU affinity mask start "" notepad empty title required |
| Get-Process | Procesi | modern | PowerShell - retrieve process objects with rich properties | -Name filter by name pattern -Id N filter by PID -IncludeUserName show owner (admin) -Module show loaded modules -FileVersionInfo show exe version | Sort-Object CPU -Desc top by CPU |
| Stop-Process | Procesi | modern | PowerShell - terminate one or more processes | -Id N terminate by PID -Name name terminate by name -Force skip confirmation -PassThru emit terminated object -Confirm prompt before kill |
| Start-Process | Procesi | modern | PowerShell - launch program with detailed control | -FilePath executable to run -ArgumentList command-line arguments -Verb RunAs elevated (UAC prompt) -WindowStyle Hidden/Minimized/Maximized -Wait block until exit -RedirectStandardOutput capture stdout |
| Wait-Process | Procesi | modern | PowerShell - block until one or more processes exit | -Name wait for processes by name -Id N wait for PID -Timeout N give up after N seconds -ErrorAction SilentlyContinue ignore missing |
| Get-Service | Procesi | modern | PowerShell - list and inspect Windows services | -Name filter by service short name -DisplayName filter by display name -Status Running, Stopped, Paused -Include / -Exclude pattern filter -RequiredServices show dependencies |
| Procmon (Sysinternals) | Procesi | modern | Real-time file, registry, network, and process activity monitor | /AcceptEula skip EULA prompt /Quiet start tracing immediately /BackingFile log to file /LoadConfig load filter set /Terminate stop running instance |
| shutdown | Procesi | core | Shut down, restart, or log off the local or remote computer | /s shut down /r restart /l log off /g shutdown + restart apps /t N delay in seconds /m \\host target remote host /c "msg" comment shown to users /f force close apps /a abort pending shutdown |
| logoff | Procesi | core | End a user session (local or terminal services) | sessionid log off specific session /server:name target server /v verbose note: combine with quser to find session ID |
| Restart-Computer | Procesi | modern | PowerShell - reboot one or more computers (local or remote) | -ComputerName host1,host2 -Force force shutdown despite locked sessions -Credential alternate credentials -Wait -For PowerShell wait until WinRM up -Delay N retry interval -Protocol DCOM/WSMan |
| Stop-Computer | Procesi | modern | PowerShell - power off one or more computers | -ComputerName host -Force force shutdown -Credential alternate credentials -WsmanAuthentication Default/Basic/Kerberos |
| Invoke-Command | Procesi | modern | PowerShell remoting - run commands on one or many remote hosts | -ComputerName host1,host2 -ScriptBlock { } -FilePath script.ps1 run local script remotely -Credential alternate credentials -AsJob run as background job -ThrottleLimit N max concurrent |
| Enter-PSSession | Procesi | modern | PowerShell remoting - open interactive remote session | -ComputerName host -Credential alternate credentials -Authentication Kerberos/CredSSP -ConfigurationName name -UseSSL WinRM over HTTPS Exit-PSSession leave session |
| sc | Sistēma | core | Control and query the Windows Service Control Manager | query list services and status queryex include PID and flags start / stop control service config change start type or path create name binPath= create new service delete remove service |
| systeminfo | Sistēma | core | Display detailed configuration of the local system | /s host query remote computer /u user authenticate as user /fo output format (table, csv, list) /nh suppress headers (csv/table) |
| ver | Sistēma | core | Display the Windows version string | ver prints OS version |
| hostname | Sistēma | core | Print the computer NetBIOS hostname | hostname prints current hostname |
| set | Sistēma | core | Display, set, or remove environment variables | set VAR=value set in current session set VAR= remove from session set list all variables set /p VAR=Prompt: read from user input set /a VAR=2*3 arithmetic evaluation |
| setx | Sistēma | core | Persistently set environment variables (user or machine) | setx VAR value set for current user /m set system-wide (admin) /s host set on remote computer /k regkey read from registry note: new value not visible in current shell |
| wmic | Sistēma | core | Windows Management Instrumentation command-line (legacy) | os get caption,version cpu get name,numberofcores logicaldisk get size,freespace,caption process where name='chrome.exe' get processid computersystem get manufacturer,model note: WMIC is deprecated and not installed by default since Windows 11 24H2 - use Get-CimInstance |
| Get-CimInstance | Sistēma | modern | PowerShell - query WMI/CIM objects (WMIC replacement) | -ClassName WMI class (Win32_*) -Filter WQL filter clause -Property return only listed properties -ComputerName query remote system -Namespace alternate CIM namespace |
| Get-ComputerInfo | Sistēma | modern | PowerShell - retrieve consolidated system information object | -Property * show all properties Os* filter to OS-related properties Bios* BIOS/firmware info Cs* computer system info |
| Set-Service | Sistēma | modern | PowerShell - configure a Windows service | -Name service to modify -Status Running/Stopped -StartupType Automatic/Manual/Disabled -Description set service description -DisplayName set display name |
| schtasks | Sistēma | core | Schedule, run, query, or delete tasks (Task Scheduler CLI) | /create define new scheduled task /run trigger immediately /end stop running task /query list all tasks /delete remove task /sc schedule type (DAILY, ONLOGON, ONSTART) /tn task name /tr command to run |
| git | Sistēma | modern | Distributed version control - track and collaborate on code | status show working tree state log --oneline --graph compact history diff HEAD changes since last commit stash push/pop shelve and restore changes rebase -i interactive squash/reorder bisect start/good/bad find bug commit blame show line-by-line authorship |
| winget | Sistēma | modern | Windows Package Manager - install, upgrade, remove apps | search name find package install id install package upgrade --all update all packages list show installed packages uninstall id remove package source add add repository export / import reproduce setup |
| choco | Sistēma | modern | Chocolatey - community Windows package manager | install pkg -y install silently upgrade all -y update all packages list --local-only installed packages uninstall pkg -y remove package pin add -n=pkg freeze version feature enable -n enable feature |
| gpupdate | Sistēma | core | Refresh Group Policy settings on the local computer | /force reapply all settings /target:user|computer scope /wait:N seconds to wait /logoff log off if needed by policies /boot reboot if needed by policies /sync synchronous foreground refresh |
| reg | Sistēma | core | Read, write, import, export, and compare Windows Registry entries | query KEY /s recursive list query KEY /v VALUE add KEY /v name /t REG_SZ /d val delete KEY /v name /f export KEY file.reg import file.reg save KEY file.hiv raw hive load HKLM\Tmp file.hiv |
| regedit | Sistēma | core | Registry Editor - GUI for browsing and modifying the registry | regedit open GUI regedit /s file.reg silently apply .reg /e file.reg HKLM\path export branch note: prefer 'reg' for scripting |
| msiexec | Sistēma | core | Install, uninstall, or repair MSI/MSP packages | /i pkg.msi install /x pkg.msi uninstall /qn silent (no UI) /qb basic UI /norestart do not auto-reboot /l*v log.txt verbose logging ALLUSERS=1 machine-wide TRANSFORMS= apply .mst |
| sfc | Sistēma | core | System File Checker - scan and repair protected OS files | /scannow scan and repair all system files /verifyonly scan without repair /scanfile=path check single file /offbootdir / /offwindir offline image scan note: run from elevated shell |
| dism | Sistēma | core | Deployment Image Servicing and Management - online and image servicing | /Online target running OS /Image:path target offline WIM /Cleanup-Image /RestoreHealth repair /Get-Features list features /Enable-Feature /FeatureName:name /Get-Packages list installed updates /Add-Driver /Driver:path /Export-Image export WIM |
| bcdedit | Sistēma | core | Boot Configuration Data store editor - boot loader configuration | /enum list boot entries /default {GUID} set default OS /timeout N set menu timeout /set {GUID} description "name" /copy {GUID} /d "copy" /export file back up BCD /import file restore BCD note: requires admin |
| driverquery | Sistēma | core | List installed device drivers and their properties | /v verbose /si signed driver info /fo output format (table, list, csv) /nh suppress headers /s host /u user remote query |
| pnputil | Sistēma | core | Manage driver packages in the driver store | /enum-drivers list staged drivers /add-driver inf add and install /delete-driver oem##.inf /uninstall /scan-devices rescan for new devices /disable-device / /enable-device /restart-device |
| powercfg | Sistēma | core | Query and configure power plans, sleep, hibernation, battery | /list list power schemes /setactive GUID switch scheme /h on|off hibernate toggle /lastwake show last wake source /devicequery wake_armed who can wake /batteryreport HTML battery report /energy power efficiency audit /requests active power requests |
| net share / net use | Sistēma | core | Manage SMB shares and mapped network drives | net share list local shares net share name=C:\path create share /grant:user,read|change|full net use Z: \\srv\share map drive net use Z: /delete remove mapping /user:DOM\u pass alternate creds /persistent:yes|no persist |
| net start / net stop | Sistēma | core | Start or stop a Windows service by name | net start list running services net start name start service net stop name stop service note: use sc for advanced control |
| Restart-Service / Start-Service / Stop-Service | Sistēma | modern | PowerShell - lifecycle control for Windows services | -Name service short name -Force override dependencies -PassThru emit resulting object -Confirm prompt before action -WhatIf dry-run preview |
| Get-HotFix | Sistēma | modern | PowerShell - list installed Windows updates (KB articles) | -Id KB###### -ComputerName host remote -Description Hotfix/Update/Security | Sort-Object InstalledOn by date |
| Get-ItemProperty | Sistēma | modern | PowerShell - read property values (e.g. registry values) | -Path HKLM:\Software\name -Name value Set-ItemProperty write value New-ItemProperty create value Remove-ItemProperty delete value |
| Get-WindowsFeature / Install-WindowsFeature | Sistēma | modern | PowerShell - Server Manager - manage roles and features (Windows Server) | Get-WindowsFeature list all features -Name Web-Server filter Install-WindowsFeature -Name name -IncludeManagementTools -IncludeAllSubFeature -Restart reboot if needed Uninstall-WindowsFeature remove |
| icacls | Tiesības | core | Display, modify, and back up NTFS access control lists (ACLs) | /grant user:perm grant permission (F, M, RX, R, W) /deny user:perm explicit deny /remove user remove all ACEs for user /t recurse into subdirectories /c continue on errors /inheritance:e/d/r enable/disable/reset /save file back up ACLs /restore file restore ACLs |
| takeown | Tiesības | core | Take ownership of a file or folder (typically as admin) | /f file target file or directory /r recursive /d Y/N default answer for prompt /a give ownership to Administrators group /skipsl skip symlinks |
| runas | Tiesības | core | Run a program under a different user account | /user:DOMAIN\user specify user /profile load user profile /savecred save credentials in Vault /netonly remote-only credentials /noprofile no profile (faster) |
| net user | Tiesības | core | Manage local user accounts (create, modify, delete, list) | net user list all local accounts net user name show details net user name pass /add create user /delete remove user /active:yes|no enable/disable /passwordchg:yes|no allow password change |
| net localgroup | Tiesības | core | Manage local groups and their members | net localgroup list groups net localgroup Administrators list members Administrators user /add add to group /delete remove from group group /add create new group |
| whoami | Tiesības | core | Display current user, SID, groups, and privileges | /user show username and SID /groups group memberships /priv enabled privileges /all show everything /fo output format (table, csv, list) /upn show UPN form /login show logon ID |
| cipher | Tiesības | core | Manage EFS encryption and securely wipe free disk space | /e encrypt files /d decrypt files /s:dir recurse directory /w:dir wipe deleted data on volume /k create new EFS key for user /u update encrypted files with new key |
| Get-Acl / Set-Acl | Tiesības | modern | PowerShell - read or write security descriptor of files, folders, registry | Get-Acl path retrieve ACL object Set-Acl path -AclObject apply ACL -Audit also include audit ACEs | Format-List inspect entries $acl.SetAccessRule() add ACE programmatically |
| net user /domain | Tiesības | core | Query and manage domain user accounts (joined to AD) | net user name /domain show user info /domain query domain controller /add /domain create domain account (admin) note: requires AD-joined machine |
| gpresult | Tiesības | core | Display applied Group Policy (RSoP) for user and computer | /r summary report /v verbose /z super-verbose /h file.html HTML report /scope user|computer limit scope /user name another user's policy |
| auditpol | Tiesības | modern | View and configure Windows audit policy categories | /get /category:* show current policy /set /subcategory:"Logon" /success:enable /list /subcategory:* list all subcategories /backup /file:audit.csv export policy /restore /file:audit.csv import policy /clear clear audit policy |
| Get-LocalUser / New-LocalUser | Tiesības | modern | PowerShell - manage local user accounts (modern net user replacement) | Get-LocalUser list local accounts -Name name filter New-LocalUser -Name -Password (Read-Host -AsSecure) Set-LocalUser modify account Remove-LocalUser delete account Enable-LocalUser / Disable-LocalUser Add-LocalGroupMember -Group Administrators -Member name |
| Get-ADUser (RSAT) | Tiesības | modern | PowerShell - query Active Directory user objects (requires RSAT) | -Identity sam by SAMAccountName -Filter 'Enabled -eq $true' -SearchBase 'OU=Sales,DC=…' -Properties * return all attributes -Server dc.example target DC Set-ADUser modify attributes Unlock-ADAccount unlock locked account |
| Add-ADGroupMember (RSAT) | Tiesības | modern | PowerShell - manage Active Directory group membership | -Identity GroupName -Members user1,user2 Remove-ADGroupMember remove member Get-ADGroupMember list members -Recursive flatten nested groups Get-ADGroup -Filter * enumerate groups |
| klist | Tiesības | core | View and purge Kerberos tickets (TGT and service tickets) | klist list current tickets tickets service tickets tgt Ticket Granting Ticket purge delete all tickets purge_bind purge bindings cache sessions list logon sessions -li 0x3e7 computer session |
| ipconfig | Tīkls | core | Display TCP/IP configuration for all network adapters | /all show full info incl. MAC, DNS, DHCP /release [adapter] release DHCP lease /renew [adapter] request new DHCP lease /flushdns clear DNS resolver cache /displaydns show cached DNS entries /registerdns re-register with DNS |
| netstat | Tīkls | core | Display TCP/UDP connections, listening ports, and statistics | -a all connections and listening -n numeric addresses (no DNS) -o show PID owning connection -b show executable name (admin) -r routing table -s protocol statistics -p tcp|udp protocol filter |
| ping | Tīkls | core | Test host reachability using ICMP echo | -n N number of echo requests -l N payload size in bytes -t ping continuously -i N set IP TTL -w ms timeout per reply -4 / -6 force IPv4 or IPv6 |
| tracert | Tīkls | core | Trace the network path packets take to a host | -d do not resolve hostnames -h N max hops -w ms timeout per probe -4 / -6 force IPv4 or IPv6 tracert host default trace |
| pathping | Tīkls | core | Combine traceroute with per-hop packet loss statistics | -n no name resolution -h N max hops -q N queries per hop -w ms timeout per reply -p ms wait between pings -4 / -6 force protocol |
| nslookup | Tīkls | core | Interactive and non-interactive DNS lookup | nslookup host basic lookup nslookup host server use specific resolver set type=MX change query type set type=ANY request any record -debug show full response |
| route | Tīkls | core | Display and modify the IP routing table | print show routing table add dest mask gw add static route delete dest remove route change dest modify route -p make route persistent -4 / -6 IPv4 or IPv6 table |
| arp | Tīkls | core | Display and modify the ARP cache (IP↔MAC mappings) | -a show ARP table -d ip delete entry -s ip mac add static entry -N iface filter by interface |
| netsh | Tīkls | core | Configure network interfaces, firewall, WLAN, and more | interface ip show config view IP settings wlan show profiles list saved Wi-Fi wlan show profile name key=clear reveal password advfirewall set allprofiles state on int tcp show global TCP tuning winsock reset reset Winsock catalog |
| Test-NetConnection | Tīkls | modern | PowerShell - port reachability, traceroute, ping diagnostics | -ComputerName host target -Port N test specific TCP port -TraceRoute show route hops -CommonTCPPort HTTP/HTTPS/RDP -InformationLevel Detailed full output tnc host -p 443 shorthand |
| Get-NetIPAddress | Tīkls | modern | PowerShell - retrieve IP address configuration objects | -InterfaceAlias name filter by adapter -AddressFamily IPv4 / IPv6 -PrefixOrigin Dhcp/Manual -SkipAsSource filter source preference | Format-Table tabular view |
| ssh (OpenSSH) | Tīkls | modern | Secure Shell client - remote login, exec, port forwarding | -i identity (private key) file -p N remote port -L local port forwarding -R remote port forwarding -J jump through bastion host -N do not execute remote command -v verbose debug output |
| Resolve-DnsName | Tīkls | modern | PowerShell - query DNS records with full record-type support | -Type A/AAAA/MX/TXT/ANY -Server ip use specific resolver -DnsOnly skip Hosts file -NoHostsFile ignore static hosts -LlmnrFallback also try LLMNR |
| nbtstat | Tīkls | core | Display NetBIOS over TCP/IP statistics and name cache | -a host remote name table by name -A ip remote name table by IP -n local name table -c NetBIOS name cache -r resolved names -R purge and reload from LMHOSTS -S sessions table |
| nltest | Tīkls | core | Test and configure NETLOGON, domain trusts, and DC discovery | /dsgetdc:DOMAIN locate DC for domain /sc_query:DOMAIN query secure channel /sc_reset:DOMAIN reset secure channel /domain_trusts list trust relationships /dclist:DOMAIN list DCs in domain /parentdomain show parent domain |
| netsh advfirewall | Tīkls | core | Configure Windows Defender Firewall - rules, profiles, logging | set allprofiles state on firewall add rule name=R protocol=TCP dir=in localport=8080 action=allow firewall show rule name=all firewall delete rule name=R monitor show consec active connections set logging filename file.log reset restore default policy |
| New-NetFirewallRule | Tīkls | modern | PowerShell - create Windows Firewall rules (netsh advfirewall replacement) | -DisplayName name -Direction Inbound/Outbound -Action Allow/Block -Protocol TCP/UDP/ICMPv4 -LocalPort N -RemoteAddress ip/subnet -Profile Domain/Private/Public Get-NetFirewallRule / Remove-NetFirewallRule |
| curl | Pārsūtīšana | core | Transfer data over HTTP, HTTPS, FTP, and many other protocols | -o write output to file -X HTTP method (GET POST PUT…) -H add request header -d POST body data -L follow redirects -k skip TLS verification --retry N retry on transient failure -u user:pass basic auth --form multipart/form-data -s silent (no progress) |
| Invoke-WebRequest | Pārsūtīšana | modern | PowerShell - HTTP client returning parsed response object | -Uri target URL -Method GET/POST/PUT/DELETE -Headers @{} request headers -Body request body -OutFile save response to file -UseBasicParsing no IE engine -SkipCertificateCheck ignore TLS errors -Credential pass PSCredential |
| Invoke-RestMethod | Pārsūtīšana | modern | PowerShell - HTTP client for REST APIs (parses JSON/XML) | -Uri endpoint -Method HTTP verb -Headers request headers -Body body (auto-serializes JSON if hashtable) -ContentType set content-type -Authentication Bearer -Token modern auth | ConvertTo-Json inspect result |
| bitsadmin | Pārsūtīšana | core | Background Intelligent Transfer Service - resumable downloads (legacy) | /transfer name url file download URL to file /list show active jobs /cancel jobid abort job /info jobid /verbose job state note: deprecated in favor of Start-BitsTransfer |
| Start-BitsTransfer | Pārsūtīšana | modern | PowerShell - resumable background HTTP/HTTPS/SMB transfer | -Source url source URL -Destination path target file -Asynchronous non-blocking job -Priority Foreground/High/Normal/Low -Authentication Basic/NTLM/Negotiate -RetryInterval N seconds between retries |
| scp (OpenSSH) | Pārsūtīšana | core | Securely copy files between hosts over SSH | -r recursive copy of directories -P N specify remote port -i identity (private key) file -p preserve timestamps and modes -v verbose debug output |
| sftp (OpenSSH) | Pārsūtīšana | core | Interactive secure file transfer over SSH | -P N specify port -i identity file get / put download / upload file ls / lls list remote / local files mget / mput batch transfer |
| perfmon | Uzraudzība | core | Performance Monitor - real-time and recorded counters (GUI/CLI) | perfmon open Performance Monitor perfmon /res open Resource Monitor perfmon /rel open Reliability Monitor perfmon /report generate System Diagnostic report |
| typeperf | Uzraudzība | core | Sample performance counters and write to stdout or CSV | "\Processor(_Total)\% Processor Time" -sc N sample count -si N sample interval (seconds) -f csv/tsv/bin output format -o file write to file -cf file read counter list from file -q list all counters |
| Get-Counter | Uzraudzība | modern | PowerShell - sample performance counters with rich objects | -Counter "\path" counter path -SampleInterval N seconds between samples -MaxSamples N number of samples -Continuous sample until Ctrl+C -ComputerName remote host -ListSet * enumerate counter sets |
| Get-EventLog | Uzraudzība | modern | PowerShell - read classic Windows event logs (legacy API) | -LogName Application/System/Security -Newest N most recent N entries -EntryType Error/Warning/Information -Source name filter by source -After / -Before time range note: superseded by Get-WinEvent |
| Get-WinEvent | Uzraudzība | modern | PowerShell - read modern (ETW) Windows event logs with XPath/XML filters | -LogName Microsoft-Windows-* / Security -FilterHashtable @{LogName='Security'; Id=4625} -MaxEvents N cap output -Oldest oldest first -FilterXPath XPath query -ListLog * enumerate logs |
| wevtutil | Uzraudzība | core | Windows Event Log command-line utility | el enumerate log names qe Security /c:10 /rd:true /f:text query cl Security clear log gli Security log info epl Security file.evtx export log sl LogName /e:true|false enable/disable |
| resmon | Uzraudzība | core | Resource Monitor - GUI for CPU, memory, disk, network in real time | resmon launch GUI note: drill down per-process I/O and network connections |
| Get-NetTCPConnection | Uzraudzība | modern | PowerShell - list active TCP connections (modern netstat) | -State Listen/Established -LocalPort N filter by local port -RemoteAddress ip filter by remote IP -OwningProcess PID filter by process | Join with Get-Process Id |
| Sysmon (Sysinternals) | Uzraudzība | modern | System Monitor - rich endpoint telemetry into Event Log | -i config.xml install with config -c config.xml update running config -u force uninstall -h sha256,imphash set hash algorithms -n log network connections note: events appear in Microsoft-Windows-Sysmon/Operational |
| quser / query user | Uzraudzība | core | Display interactive and RDP user sessions on local or remote host | quser list sessions on local quser /server:host remote host note: shows session ID, state, idle time, logon time |
| qwinsta / rwinsta | Uzraudzība | core | Query and reset terminal services (RDP) sessions | qwinsta list sessions qwinsta /server:host rwinsta sessionid reset session rwinsta /server:host id note: equivalent to 'query session' / 'reset session' |
| diskpart | Diski | core | Manage disks, partitions, and volumes (scriptable disk utility) | list disk / partition / volume select disk N clean wipe partition table create partition primary format fs=ntfs quick assign letter=X extend / shrink desired=N note: requires admin shell |
| chkdsk | Diski | core | Check disk for filesystem errors and bad sectors | /f fix filesystem errors /r also locate bad sectors /x force dismount before scan /scan online scan (NTFS) /spotfix targeted fix on next boot /b re-evaluate bad clusters (with /r) |
| fsutil | Diski | core | Filesystem utility for advanced NTFS, USN, links, and quotas | fsinfo drives list drives volume diskfree C: free/total bytes behavior set tune NTFS behavior usn USN journal management hardlink create create hard link file createnew name N create N-byte file |
| format | Diski | core | Format a disk volume with a filesystem | /fs:NTFS|FAT32|exFAT filesystem type /q quick format /v:label set volume label /a:size allocation unit size /l large FRS (NTFS) /p:N pass count for zero-fill |
| mountvol | Diski | core | Mount or unmount a volume at a drive letter or NTFS folder | mountvol list mounted volumes mountvol X: \\?\Volume{GUID}\ mount mountvol X: /d unmount drive /r remove orphaned points /n / /e disable/enable auto-mount |
| Get-Disk | Diski | modern | PowerShell - retrieve physical disk objects and health | -Number N filter by disk number -FriendlyName name | Initialize-Disk -PartitionStyle GPT | Set-Disk -IsOffline $false HealthStatus disk health summary |
| Get-Volume | Diski | modern | PowerShell - retrieve volumes with size, filesystem, health | -DriveLetter C -FileSystem NTFS/ReFS/FAT32 -FileSystemLabel name | Repair-Volume -OfflineScanAndFix | Optimize-Volume -Defrag |
| New-Partition / Format-Volume | Diski | modern | PowerShell - create partitions and format volumes | New-Partition -DiskNumber N -UseMaximumSize -DriveLetter X assign letter -AssignDriveLetter auto-assign Format-Volume -FileSystem NTFS -NewFileSystemLabel label -Confirm:$false no prompt |
| defrag | Diski | core | Analyze and defragment volumes | C: defragment drive /a analyze only /o optimize (defrag + slab consolidate) /l retrim SSD /x free-space consolidation /v verbose output |
| convert | Diski | core | Convert FAT/FAT32 volume to NTFS in-place | C: /fs:ntfs basic conversion /v verbose /cvtarea:file reserve MFT space /nosecurity no security descriptors /x force dismount first note: one-way; cannot revert to FAT |
| vssadmin | Diski | core | Manage Volume Shadow Copies and storage providers | list shadows show all snapshots list shadowstorage storage allocation create shadow /for=C: delete shadows /for=C: /oldest resize shadowstorage /on=C: /maxsize=10GB list writers list VSS writers |
| Get-PhysicalDisk | Diski | modern | PowerShell - retrieve physical disk objects (Storage Spaces era) | -FriendlyName name -MediaType SSD/HDD/SCM -HealthStatus Healthy/Warning | Get-StoragePool associated pool Reset-PhysicalDisk bring back online |
| tar | core | Built-in BSD tar - create/extract archives (.tar, .tar.gz, .zip) | -c create archive -x extract archive -f file archive filename -z gzip filter -v verbose listing -t list contents without extracting --strip-components N strip path levels note: built into Windows 10 1803+ |
|
| compact | core | View and change NTFS file compression | /c compress files /u uncompress files /s recurse subdirectories /a display hidden/system files /i ignore errors /exe:LZX|XPRESS algorithm choice |
|
| expand | core | Expand compressed CAB/MSU/cabinet archives | -r rename expanded files -i ignore directory structure -f:* files to expand (wildcards) -d display contents only source dest basic expansion |
|
| Compress-Archive | modern | PowerShell - create or append to .zip archives | -Path files/dirs to include -DestinationPath file.zip -Update add/update entries -Force overwrite existing zip -CompressionLevel Fastest/Optimal/NoCompression |
|
| Expand-Archive | modern | PowerShell - extract .zip archive contents | -Path file.zip -DestinationPath dir -Force overwrite existing files -PassThru emit extracted items |
|
| 7z (7-Zip CLI) | modern | 7-Zip - high-ratio compression with 7z, zip, tar, gz support | a archive.7z files add to archive x archive.7z extract preserving paths e archive.7z extract flat l archive.7z list contents t archive.7z test integrity -p set password -mx=9 max compression -mhe=on encrypt headers |
|
| nmap | Ielaušanās tests | security | Network scanner - host discovery, port scan, service detection | -sV detect service versions -sC run default NSE scripts -O enable OS fingerprinting -p specify port range (e.g. 1-65535) -A aggressive: OS+version+scripts+traceroute --script run specific NSE script -oN / -oX output to file -Pn skip host discovery (assume up) -sS SYN stealth scan (admin) |
| certutil | Ielaušanās tests | security | Certificate Services tool - inspect certs, hash files, base64 encode | -hashfile file SHA256 hash a file -encode in out base64 encode -decode in out base64 decode -store -enterprise Root list Root certs -verify -urlfetch cert.cer -dump inspect certificate note: also used by attackers as LOLBin |
| openssl | Ielaušanās tests | security | TLS/SSL toolkit - certificates, keys, encryption, and testing | s_client -connect host:443 test TLS x509 -in cert.pem -text inspect cert genrsa -out key.pem 4096 generate RSA key req -new generate CSR enc -aes-256-cbc encrypt/decrypt verify -CAfile validate chain speed benchmark ciphers |
| ssh-keygen | Ielaušanās tests | security | Generate, manage, and convert SSH authentication keys | -t ed25519 modern key type (recommended) -b 4096 bit length (for RSA) -C 'comment' add identifying comment -f file output file path -p change or remove passphrase -l print key fingerprint |
| gpg | Ielaušanās tests | security | GNU Privacy Guard for Windows - encrypt, sign, verify | --gen-key generate key pair -e -r recipient encrypt file --decrypt decrypt .gpg file -s create detached signature --verify verify signature file --armor ASCII-armored output --export / --import key management |
| PsExec (Sysinternals) | Ielaušanās tests | security | Execute processes on remote systems with full I/O redirection | \\host -u user -p pass cmd -s run as SYSTEM -i interactive (show GUI) -d do not wait for process -c copy local exe to remote -h elevated token note: often used in attack chains - monitor |
| mimikatz | Ielaušanās tests | security | Windows credential extraction toolkit (RED TEAM / LAB ONLY) | privilege::debug acquire SeDebug sekurlsa::logonpasswords dump LSASS creds lsadump::sam dump local SAM kerberos::list list tickets note: blocked by Defender; LAB USE ONLY legal: use only on systems you own/authorize |
| hashcat | Ielaušanās tests | security | GPU-accelerated password hash cracking tool | -m hash type (1000=NTLM, 13100=Kerberos TGS) -a attack mode (0=dict, 3=bruteforce) -w workload profile (1–4) -r rules apply rules file --show show already cracked hashes --status live progress update |
| john (JtR) | Ielaušanās tests | security | CPU-based password hash cracker with auto-detection | --wordlist dictionary file path --rules apply mangling rules --format=ntlm specify hash type --show display cracked passwords --fork N parallel processes note: Cygwin or native Win64 build |
| Defender (Set-MpPreference) | Ielaušanās tests | security | PowerShell - configure Microsoft Defender Antivirus | Get-MpPreference show current settings Set-MpPreference -DisableRealtimeMonitoring Add-MpPreference -ExclusionPath path Start-MpScan -ScanType QuickScan/FullScan Update-MpSignature update definitions Get-MpThreatDetection recent detections |
| docker | Konteineri | modern | Build, ship, and run application containers (Docker Desktop) | run -d run container detached run --rm auto-remove on exit exec -it open shell in running container logs -f follow container log stream inspect detailed JSON metadata ps -a list all containers build -t build image with tag network ls / inspect manage networks volume ls / inspect manage volumes system prune remove unused resources |
| kubectl | Konteineri | modern | CLI to manage Kubernetes clusters and workloads | get pods/svc/nodes list resources describe pod name detailed event log apply -f manifest.yaml deploy/update exec -it pod -- powershell shell into pod logs -f pod follow log stream top node / top pod resource usage rollout status/undo deployment control port-forward forward local port to pod config use-context switch cluster |
| podman | Konteineri | modern | Rootless daemonless OCI engine - Windows port via WSL | run --rm auto-remove after exit --user 1000 run as non-root UID --pod attach to pod group -v bind mount host volume generate kube export as Kubernetes YAML play kube run from Kubernetes YAML |
| helm | Konteineri | modern | Kubernetes package manager for templated chart deployments | install release chart deploy chart upgrade --install upsert deploy rollback release N revert to revision list show all deployed releases values chart show default values repo add / update manage chart repos template render manifests locally |
| wsl | Konteineri | modern | Windows Subsystem for Linux - run Linux distros and containers | --list --verbose show distros and state --install -d Ubuntu install distro --set-default name --set-version name 2 switch to WSL2 --shutdown stop all distros --export / --import backup/restore note: required for Docker Desktop on Windows |
Sistēmas audits
Pārbaudes ir sagrupētas pēc auditora jautājumiem: kas notika, kam ir piekļuve, kas startē pats, kas ir atvērts tīklam, vai sistēma ir atjaunināta un aizsargāta un vai konfigurācija atbilst ieteiktajai. Visas komandas tikai lasa, neko nemainot. Palaid PowerShell kā administrators. Ja Get-WinEvent atbild "No events were found", atbilstošu notikumu žurnālā nav. Saglabā rezultātu kā bāzlīniju - nākamajā auditā izmaiņas pret to ir redzamākas par pašām vērtībām.
Kā audits notiek no plānošanas līdz ziņojumam, skaidro drošības audita ceļvedis.
Žurnāli un pieteikšanās
-
Kas vispār tiek žurnalēts
auditpol /get /category:*Uz ko skatīties: No Auditing pie Logon/Logoff, Account Management, Policy Change vai Detailed Tracking nozīmē, ka attiecīgo notikumu žurnālā nebūs, un turpmākās pārbaudes neko neatradīs. Ieteicams Success and Failure.
-
Neveiksmīgas pieteikšanās (4625)
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4625; StartTime=(Get-Date).AddDays(-1)} | ForEach-Object { $_.Properties[19].Value } | Group-Object | Sort-Object Count -DescendingUz ko skatīties: Rezultāts ir sagrupēts pēc avota adreses. Simtiem mēģinājumu no vienas adreses ir paroļu minēšana, daudz adrešu ar vienu lietotājvārdu - sadalīta minēšana (password spraying).
-
Sekmīgas attālinātas pieteikšanās (4624)
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4624; StartTime=(Get-Date).AddDays(-1)} | Where-Object { $_.Properties[8].Value -in 3, 10 } | Select-Object TimeCreated, @{n='User'; e={$_.Properties[5].Value}}, @{n='IP'; e={$_.Properties[18].Value}}Uz ko skatīties: Tips 10 ir RDP, tips 3 - tīkla pieteikšanās (koplietotās mapes, attālināta pārvaldība). Meklē kontus un adreses, kam nevajadzētu pieslēgties, un pieteikšanās nakts stundās.
-
Kontu un grupu izmaiņas
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4720,4726,4732,4738} -MaxEvents 50 | Format-List TimeCreated, Id, MessageUz ko skatīties: 4720 - konts izveidots, 4726 - dzēsts, 4738 - mainīts, 4732 - konts pievienots lokālajai grupai (piem., Administrators). Katrai izmaiņai jābūt zināmam pieprasījumam.
-
Jauni servisi (7045)
Get-WinEvent -FilterHashtable @{LogName='System'; Id=7045} -MaxEvents 30 | Format-List TimeCreated, MessageUz ko skatīties: Jauns serviss ir bieža pastāvības un attālinātas izpildes pēda (piem., PsExec izveido servisu). Aizdomīgi: ceļš uz Temp vai ProgramData un komandrinda ar powershell -enc.
-
Notīrīti žurnāli (1102, 104)
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=1102}Get-WinEvent -FilterHashtable @{LogName='System'; Id=104}Uz ko skatīties: 1102 - notīrīts drošības žurnāls, 104 - notīrīts cits žurnāls. Ārpus plānotas apkopes tas gandrīz vienmēr nozīmē pēdu slēpšanu.
-
PowerShell skriptu bloki (4104)
Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-PowerShell/Operational'; Id=4104} -MaxEvents 50 | Format-List TimeCreated, MessageUz ko skatīties: Rāda izpildīto skriptu saturu, arī atkodētu no -EncodedCommand. Aizdomīgi: DownloadString, IEX, FromBase64String, AMSI apiešana. Pilnu žurnalēšanu ieslēdz grupas politika Turn on PowerShell Script Block Logging, bez tās tiek ierakstīti tikai aizdomīgi bloki.
-
Žurnālu izmērs un glabāšana
Get-WinEvent -ListLog Security, System, 'Microsoft-Windows-PowerShell/Operational' | Format-Table LogName, MaximumSizeInBytes, RecordCount, LogModeUz ko skatīties: Noklusējuma 20 MB drošības žurnāls aizņemtā serverī pārrakstās dažās dienās vai pat stundās. Izmeklēšanai vajag nedēļas, tāpēc palielini izmēru vai sūti žurnālus uz centrālu sistēmu (SIEM).
Konti un tiesības
-
Lokālie konti
Get-LocalUser | Select-Object Name, Enabled, LastLogon, PasswordLastSet, PasswordRequiredUz ko skatīties: Ieslēgti konti, ko neviens nelieto, un konti ar PasswordRequired False. Iebūvētajam Guest kontam jābūt izslēgtam.
-
Administratori
Get-LocalGroupMember -SID S-1-5-32-544Uz ko skatīties: S-1-5-32-544 ir Administrators grupa jebkurā Windows valodā. Katram dalībniekam jābūt pamatojumam, ikdienas darbam lieto parastu kontu.
-
Paroļu un bloķēšanas politika
net accountsUz ko skatīties: Lockout threshold Never nozīmē, ka paroles var minēt bez ierobežojuma. Minimālais paroles garums zem 12 zīmēm ir vājš.
-
Lietotāju tiesības (User Rights)
secedit /export /cfg $env:TEMP\secpol.inf /areas USER_RIGHTSSelect-String -Path $env:TEMP\secpol.inf -Pattern 'SeDebugPrivilege|SeBackupPrivilege|SeRemoteInteractiveLogonRight'Uz ko skatīties: SeDebugPrivilege un SeBackupPrivilege ļauj nolasīt citu procesu atmiņu un jebkuru failu, tāpēc tām jābūt tikai administratoriem (*S-1-5-32-544). SeRemoteInteractiveLogonRight nosaka, kas drīkst pieslēgties ar RDP.
Palaišana un plānotie uzdevumi
-
Run atslēgas reģistrā
Get-ItemProperty 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Run', 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run'Uz ko skatīties: Programmas, kas startē pie pieteikšanās. Aizdomīgi: ceļš uz AppData vai Temp, nejaušs nosaukums, powershell vai mshta komandrindā.
-
Plānotie uzdevumi ārpus Microsoft
Get-ScheduledTask | Where-Object TaskPath -notlike '\Microsoft\*' | Select-Object TaskName, TaskPath, State(Get-ScheduledTask -TaskName <nosaukums>).ActionsUz ko skatīties: Katram uzdevumam jābūt zināmam nolūkam. Otrā komanda rāda, ko uzdevums palaiž - skripts lietotāja mapē vai kodēta PowerShell komanda ir jāizmeklē.
-
Automātiski startējoši servisi ārpus Windows mapes
Get-CimInstance Win32_Service | Where-Object { $_.StartMode -eq 'Auto' -and $_.PathName -notmatch '\\Windows\\' } | Select-Object Name, PathName, StartNameUz ko skatīties: Servisi no Program Files parasti ir instalētas programmas. Ceļš uz lietotāja mapi vai Temp un ceļš ar atstarpēm bez pēdiņām (unquoted service path) ir jāizmeklē.
-
Visas palaišanas vietas vienā sarakstā
autorunsc -accepteula -a * -c -h -s -m > autoruns.csvUz ko skatīties: Sysinternals Autoruns pārbauda vairāk nekā simts palaišanas vietu. Karogs -m paslēpj Microsoft ierakstus, -s pārbauda parakstus - neparakstīts ieraksts ir pirmais, ko apskatīt.
Servisi
-
Strādājošie servisi
Get-Service | Where-Object Status -eq 'Running' | Sort-Object DisplayName | Select-Object Name, DisplayName, StartTypeUz ko skatīties: Katram servisam jābūt zināmam nolūkam. Trešo pušu attālinātās piekļuves rīki (TeamViewer, AnyDesk), ko neviens neatzīst, ir atradums.
-
Automātiski startējoši, bet apturēti
Get-CimInstance Win32_Service -Filter "StartMode='Auto' AND State<>'Running'" | Select-Object Name, State, ExitCodeUz ko skatīties: Daļa servisu startē ar aizturi vai pēc notikuma, tāpēc apturēts vēl nav kļūda. ExitCode, kas nav 0, nozīmē avāriju - īpaši svarīgi Defender, žurnalēšanas un rezerves kopiju servisiem.
-
Ar kādu kontu serviss strādā
Get-CimInstance Win32_Service | Select-Object Name, StartName, State | Sort-Object StartNameUz ko skatīties: LocalSystem ir visplašākās tiesības. Serviss ar domēna administratora kontu atstāj šī konta akreditācijas datus uz katra datora, kur tas darbojas.
-
Kurš serviss tur portu
Get-NetTCPConnection -LocalPort <ports> -State Listen | ForEach-Object { Get-CimInstance Win32_Service -Filter "ProcessId=$($_.OwningProcess)" } | Select-Object Name, PathNameUz ko skatīties: Ports bez servisa nozīmē procesu, kas palaists citādi - pārbaudi tā ceļu un parakstu.
Tīkla virsma
-
Porti, kas gaida savienojumus
Get-NetTCPConnection -State Listen | Select-Object LocalAddress, LocalPort, @{n='Process'; e={(Get-Process -Id $_.OwningProcess).ProcessName}} | Sort-Object LocalPortUz ko skatīties: 0.0.0.0 vai :: nozīmē, ka ports ir pieejams no tīkla. RDP (3389), SMB (445) un WinRM (5985, 5986) nedrīkst būt atvērti internetam.
-
Ugunsmūra profili
Get-NetFirewallProfile | Select-Object Name, Enabled, DefaultInboundAction, LogBlockedUz ko skatīties: Visiem trim profiliem jābūt ieslēgtiem, un ienākošā datplūsma pēc noklusējuma jābloķē (NotConfigured nozīmē Block). LogBlocked False nozīmē, ka bloķētie savienojumi nekur nav redzami.
-
Koplietotās mapes un SMBv1
Get-SmbShareGet-SmbServerConfiguration | Select-Object EnableSMB1ProtocolUz ko skatīties: Koplietotās mapes, par kurām neviens nezina. SMBv1 jābūt izslēgtam - to izmantoja WannaCry (MS17-010).
-
Attālinātā darbvirsma (RDP)
Get-ItemProperty 'HKLM:\System\CurrentControlSet\Control\Terminal Server' -Name fDenyTSConnectionsGet-ItemProperty 'HKLM:\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp' -Name UserAuthenticationUz ko skatīties: Vērtība fDenyTSConnections 0 nozīmē, ka RDP ir ieslēgts. Ja tas vajadzīgs, UserAuthentication jābūt 1 (NLA - pieteikšanās pirms sesijas izveides).
Integritāte un atjauninājumi
-
Pēdējie atjauninājumi
Get-HotFix | Sort-Object InstalledOn -Descending | Select-Object -First 10Uz ko skatīties: Ja pēdējais atjauninājums ir vecāks par mēnesi, sistēmā ir publiski zināmas ievainojamības. Get-HotFix nerāda visu, piem., Defender un draiveru atjauninājumus.
-
Microsoft Defender stāvoklis un izņēmumi
Get-MpComputerStatus | Select-Object AMServiceEnabled, RealTimeProtectionEnabled, AntivirusSignatureLastUpdatedGet-MpPreference | Select-Object ExclusionPath, ExclusionProcessGet-MpThreatDetectionUz ko skatīties: Reāllaika aizsardzībai jābūt ieslēgtai un signatūrām ne vecākām par dienu vai divām. Uzbrucējs bieži pievieno savu mapi izņēmumiem. Get-MpThreatDetection rāda arī pagātnes atradumus, ko lietotājs varēja nepamanīt.
-
Diska šifrēšana
Get-BitLockerVolume | Select-Object MountPoint, VolumeStatus, ProtectionStatusUz ko skatīties: ProtectionStatus Off klēpjdatorā nozīmē, ka nozagts disks ir nolasāms bez paroles.
-
Sistēmas failu integritāte
sfc /verifyonlyUz ko skatīties: Pārbauda aizsargātos sistēmas failus, neko nelabojot. Atradumi ir žurnālā C:\Windows\Logs\CBS\CBS.log.
-
Neparakstīti izpildāmie faili lietotāju mapēs
sigcheck -accepteula -u -e -s C:\UsersUz ko skatīties: Sysinternals Sigcheck parāda izpildāmos failus bez digitālā paraksta. Programma lietotāja mapē bez paraksta nav pierādījums, bet ir pirmais, ko pārbaudīt.
Konfigurācija
-
Piemērotās grupas politikas
gpresult /h $env:TEMP\gpresult.htmlUz ko skatīties: Pārskats rāda, kuras politikas un no kura objekta ir tiešām spēkā. Ja gaidītā politika tur nav, tā uz šo datoru neattiecas.
-
LSASS aizsardzība un Credential Guard
Get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\Lsa' -Name RunAsPPL -ErrorAction SilentlyContinue(Get-CimInstance -ClassName Win32_DeviceGuard -Namespace root\Microsoft\Windows\DeviceGuard).SecurityServicesRunningUz ko skatīties: RunAsPPL 1 vai 2 aizsargā LSASS procesu pret paroļu nolasīšanu no atmiņas (piem., ar mimikatz). SecurityServicesRunning vērtība 1 nozīmē, ka darbojas Credential Guard.
-
Novecojušie autentifikācijas protokoli
Get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\Lsa' -Name LmCompatibilityLevel -ErrorAction SilentlyContinueGet-ItemProperty 'HKLM:\Software\Policies\Microsoft\Windows NT\DNSClient' -Name EnableMulticast -ErrorAction SilentlyContinueUz ko skatīties: LmCompatibilityLevel 5 atļauj tikai NTLMv2. EnableMulticast 0 izslēdz LLMNR, ko uzbrucējs lokālajā tīklā izmanto paroļu jaucējvērtību pārtveršanai. Ja vērtības nav, spēkā ir noklusējums, un LLMNR ir ieslēgts.
Problēmu novēršana
Sāc ar diviem jautājumiem: kas mainījās un vai problēma skar vienu lietotāju vai visus. Tad ej pa slāņiem no apakšas uz augšu - saskarne un adrese, maršruts, DNS un tikai tad serviss. Komandas tikai nolasa stāvokli, ko mainīt, pasaka piezīme.
Tīkls
-
Vai saskarne ir augšā un tai ir adrese un vārteja
Get-NetAdapter | Select-Object Name, Status, LinkSpeedGet-NetIPConfigurationipconfig /allKo darīt: Statuss Disconnected nozīmē, ka nav saites. 169.254.x.x adrese nozīmē, ka DHCP neatbildēja, un bez IPv4DefaultGateway dators sasniedz tikai savu apakštīklu.
-
Vai mērķis un ports ir sasniedzams
Test-NetConnection <mērķis>Test-NetConnection <mērķis> -Port 443Ko darīt: PingSucceeded False, bet TcpTestSucceeded True nozīmē, ka bloķēts ir tikai ping. Abi False - problēma ir tīklā vai ugunsmūrī. Ja ping atbild, bet TCP nē, portā neviens neklausās vai to bloķē mērķa ugunsmūris.
-
Kur ceļš pārtrūkst
tracert -d <mērķis>Get-NetRoute -DestinationPrefix 0.0.0.0/0Ko darīt: Pēdējais atbildošais posms rāda, līdz kurienei pakete tiek. Vairāki noklusējuma maršruti (piemēram, VPN) var sūtīt datplūsmu nepareizā virzienā - uzvar tas ar mazāko RouteMetric.
-
Vai ugunsmūris bloķē
Get-NetConnectionProfile | Select-Object Name, InterfaceAlias, NetworkCategoryGet-NetFirewallProfile | Select-Object Name, Enabled, DefaultInboundActionGet-NetFirewallRule -Enabled True -Direction Inbound | Where-Object Action -eq 'Block' | Select-Object DisplayNameKo darīt: Public profilā ienākošie savienojumi ir ierobežoti visstingrāk, un domēna tīkls, kas atpazīts kā Public, ir bieža vaina. Ieslēdz vajadzīgo kārtulu, nevis atslēdz ugunsmūri.
-
Starpniekserveris (proxy)
netsh winhttp show proxyGet-ItemProperty 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings' | Select-Object ProxyEnable, ProxyServer, AutoConfigURLKo darīt: Pārlūks lieto lietotāja proxy iestatījumus, bet servisi un Windows Update - WinHTTP. Ja pārlūks strādā, bet serviss vai atjauninājumi nē (vai otrādi), atšķiras tieši šie divi iestatījumi.
DNS
-
Kurš DNS serveris tiek lietots
Get-DnsClientServerAddress -AddressFamily IPv4Ko darīt: Ja serveris ir nepareizs vai nesasniedzams, domēni netiek atrasti, kaut tīkls strādā. Domēnam pievienotam datoram DNS jānorāda uz domēna kontrolieriem, ne uz publisku serveri - citādi neizdodas pieteikšanās un grupu politikas.
-
Ko atbild DNS serveris
Resolve-DnsName <domēns> -NoHostsFileResolve-DnsName <domēns> -Server 1.1.1.1Ko darīt: DNS_ERROR_RCODE_NAME_ERROR nozīmē, ka domēns neeksistē, DNS_ERROR_RCODE_SERVER_FAILURE - ka serveris nevarēja atbildēt. Ja publiskais serveris atbild, bet vietējais nē, vaina ir vietējā DNS. Iekšējos domēnus publiskais serveris nezina, tur atšķirība ir normāla.
-
Kešs, hosts fails un VPN noteikumi
Get-DnsClientCache | Select-Object -First 20Get-Content $env:windir\System32\drivers\etc\hostsGet-DnsClientNrptPolicyKo darīt: Novecojis ieraksts kešā vai hosts failā pārraksta DNS, kešu iztīra ipconfig /flushdns. NRPT noteikumi (VPN, DirectAccess) sūta konkrētus domēnus uz citu serveri - ja tikai daži domēni neatbild, meklē tur.
Servisi
-
Stāvoklis, startēšanas veids un atkarības
Get-Service <serviss> | Select-Object Name, Status, StartTypeGet-Service <serviss> -RequiredServicessc.exe qc <serviss>Ko darīt: sc.exe qc parāda kontu un izpildāmā faila ceļu - nepareizs ceļš vai beigusies servisa konta parole ir biežākie cēloņi. Ja kāds no RequiredServices ir apturēts, serviss nestartējas ar kļūdu 1068.
-
Service Control Manager kļūdas
Get-WinEvent -FilterHashtable @{LogName='System'; ProviderName='Service Control Manager'; Level=2} -MaxEvents 20 | Format-List TimeCreated, Id, MessageKo darīt: 7000 - neizdevās startēt, 7009 - taimauts, 7023 un 7024 - serviss apstājās ar kļūdu, 7031 un 7034 - avārija. Ziņojumā ir Windows kļūdas kods, ko atšifrē net helpmsg <kods>.
-
Lietotnes avārija
Get-WinEvent -FilterHashtable @{LogName='Application'; Id=1000,1026} -MaxEvents 10 | Format-List TimeCreated, MessageKo darīt: 1000 nosauc avarējušo moduli (DLL), 1026 - .NET izņēmumu. Tas norāda, vai vaina ir lietotnē vai kopīgā bibliotēkā.
Disks un failu sistēma
-
Vai disks nav pilns
Get-Volume | Select-Object DriveLetter, FileSystemLabel, SizeRemaining, SizeKo darīt: Mazāk par 10% brīvas vietas sistēmas diskā palēnina atjauninājumus un var tos apturēt.
-
Kas aizņem vietu
Get-ChildItem C:\ -Directory -Force -ErrorAction SilentlyContinue | ForEach-Object { [pscustomobject]@{Folder=$_.FullName; GB=[math]::Round((Get-ChildItem $_.FullName -Recurse -File -Force -ErrorAction SilentlyContinue | Measure-Object Length -Sum).Sum/1GB,1)} } | Sort-Object GB -Descending | Select-Object -First 10Ko darīt: Bieži vainīgie: WinSxS, lejupielādes, pagaidu faili. Tīri ar Diska tīrīšanu vai Storage Sense, ne dzēšot sistēmas mapes.
-
Vai disks ir vesels
Get-PhysicalDisk | Select-Object FriendlyName, MediaType, HealthStatus, OperationalStatusGet-WinEvent -FilterHashtable @{LogName='System'; ProviderName='disk'; Id=7,51,153} -MaxEvents 20 | Format-List TimeCreated, Id, Messagechkdsk C: /scanKo darīt: HealthStatus, kas nav Healthy, un notikumi 7 (bojāts bloks), 51 vai 153 (atkārtotas I/O operācijas) ir bojājuma pazīme - vispirms rezerves kopija. chkdsk /scan tikai pārbauda un sistēmu neaptur.
Veiktspēja
-
Kas noslogo procesoru
Get-Process | Sort-Object CPU -Descending | Select-Object -First 10 Name, Id, CPUKo darīt: CPU kolonna ir kopējais procesora laiks kopš starta, ne pašreizējā slodze - salīdzini divus mērījumus vai skaties Get-Counter.
-
Kas aizņem atmiņu
Get-Process | Sort-Object WorkingSet64 -Descending | Select-Object -First 10 Name, Id, @{n='MB'; e={[math]::Round($_.WorkingSet64/1MB)}}Ko darīt: Process, kura atmiņa aug stundām, var būt noplūde. Pārstartē to un vēro, vai tas atkārtojas.
-
Pašreizējā slodze
Get-Counter '\Processor(_Total)\% Processor Time', '\Memory\Available MBytes', '\PhysicalDisk(_Total)\Avg. Disk sec/Transfer' -SampleInterval 2 -MaxSamples 3Ko darīt: Diska vidējais atbildes laiks ilgstoši virs 0,02 s (20 ms) ar zemu CPU nozīmē, ka sistēma gaida disku. Lokalizētā Windows skaitītāju nosaukumi ir tulkoti - ja komanda tos neatrod, nosaukumus parāda Get-Counter -ListSet *.
Startēšana un atjauninājumi
-
Negaidīta izslēgšanās
Get-WinEvent -FilterHashtable @{LogName='System'; Id=41,6008} -MaxEvents 10 | Format-List TimeCreated, Id, MessageKo darīt: 41 (Kernel-Power) nozīmē, ka sistēma izslēdzās nekorekti, bet cēloni pats nenosauc. Ja tā BugcheckCode ir 0, tā bija barošanas pazušana, pārkaršana vai pilnīga sasalšana, ja nav 0 - zilais ekrāns.
-
Zilais ekrāns (BSOD)
Get-WinEvent -FilterHashtable @{LogName='System'; Id=1001; ProviderName='Microsoft-Windows-WER-SystemErrorReporting'} -MaxEvents 5 | Format-List TimeCreated, MessageGet-ChildItem C:\Windows\Minidump -ErrorAction SilentlyContinueKo darīt: Ziņojumā ir BugCheck kods. Atkārtots kods pēc draivera atjauninājuma norāda uz šo draiveri.
-
Kas palēnina startēšanu
Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-Diagnostics-Performance/Operational'; Id=100} -MaxEvents 5 | Format-List TimeCreated, MessageGet-CimInstance Win32_StartupCommand | Select-Object Name, Command, LocationKo darīt: Notikums 100 parāda startēšanas ilgumu, 101 un tālākie nosauc lietotnes, draiverus un servisus, kas to palēnināja. Automātiski startējošās programmas atslēdz Uzdevumu pārvaldniekā (Startup apps).
-
Kas instalēts pēdējā laikā
Get-HotFix | Sort-Object InstalledOn -Descending | Select-Object -First 10Get-WinEvent -FilterHashtable @{LogName='System'; ProviderName='Microsoft-Windows-WindowsUpdateClient'} -MaxEvents 10 | Format-List TimeCreated, MessageTest-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired'Ko darīt: Ja problēma sākās pēc atjauninājuma, šis saraksts nosauc kandidātu. True pēdējā komandā nozīmē, ka atjauninājums gaida pārstartēšanu. Atinstalē caur Iestatījumi - Windows Update - Atjauninājumu vēsture.
-
Vai sistēmas faili nav bojāti
sfc /verifyonlyDISM /Online /Cleanup-Image /ScanHealthKo darīt: Bojāti sistēmas faili pēc neizdevuša atjauninājuma rada dīvainas kļūdas. Ja pārbaude tos atrod, vispirms DISM /RestoreHealth, tad sfc /scannow (abiem vajag administratora tiesības).
Piekļuve un laiks
-
Kāpēc Access denied
Get-Acl <ceļš> | Format-List Owner, AccessToStringwhoami /groupsKo darīt: Liegums (Deny) pārspēj atļauju. Ja grupa pievienota nesen, lietotājam jāpiesakās no jauna, lai tā stātos spēkā.
-
Konts bloķēts vai parole beigusies
net user <lietotājs> /domainGet-WinEvent -FilterHashtable @{LogName='Security'; Id=4740} -MaxEvents 10 | Format-List TimeCreated, MessageKo darīt: net user /domain parāda, vai konts ir aktīvs un kad beidzas parole (vietējam kontam bez /domain). Notikums 4740 tiek ierakstīts domēna kontrolierī, ne lietotāja datorā, un nosauc datoru, no kura konts bloķēts - bieži tā ir veca parole kartētā diskā, ieplānotā uzdevumā vai telefonā.
-
Uzticēšanās attiecības ar domēnu
nltest /sc_query:<domēns>nltest /dsgetdc:<domēns>Ko darīt: Ziņojums The trust relationship between this workstation and the primary domain failed nozīmē, ka datora konta parole domēnā vairs nesakrīt. nltest parāda, vai drošais kanāls strādā un kuru domēna kontrolieri dators atrod. Labo ar Test-ComputerSecureChannel -Repair vai atkārtotu pievienošanu domēnam.
-
Vai laiks ir pareizs
w32tm /query /statusw32tm /query /sourceKo darīt: Laika nobīde virs 5 minūtēm lauž Kerberos pieteikšanos domēnā un TLS. Avotam domēnā jābūt domēna kontrolierim.
Ielaušanās tests
Ielaušanās tests pārbauda aizsardzību no uzbrucēja skatpunkta. Sadaļa seko posmiem: izlūkošana, tīmekļa virsma, TLS, paroles un pieejamības noturība. Katram ierakstam blakus ir aizsardzība - ielaušanās tests ir vērtīgs tikai tad, ja atradumi tiek novērsti. Rīki parasti nāk no testētāja mašīnas (bieži Kali Linux), tāpēc tie ir vieni abām sistēmām.
Uzbrukuma virsmu un tās samazināšanu skaidro uzbrukuma virsmas ceļvedis.
Šī sadaļa ir izglītojošiem nolūkiem. Lieto šīs metodes TIKAI pret sistēmām, kas tev pieder vai ko tev ir rakstiska atļauja testēt. Neatļauta skenēšana un testēšana ir sodāma (Krimināllikums 241.-243. pants). Mērķa vietā <mērķis> ieraksti savu testa sistēmu.
Izlūkošana un portu skenēšana
-
Hostu un atvērto portu atklāšana
nmap -sn 10.0.0.0/24nmap -sV -p- <mērķis>Aizsardzība: Katrs atvērts ports ir ieejas punkts. Aizver neizmantotos servisus, piesaisti pārvaldību un datubāzes 127.0.0.1 adresei un liec internetam pieejamos aiz ugunsmūra. Tas pats skatpunkts ir sistēmas audita tīkla sadaļā.
-
Pakalpojumu un versiju noteikšana
nmap -sV --script=banner <mērķis>whatweb <url>Aizsardzība: Versija pasaka uzbrucējam, kuru publisko ievainojamību meklēt. Noņem versiju atklājošās galvenes (Server, X-Powered-By) un turi servisus atjauninātus.
-
DNS un zonu pārsūtīšana
dig AXFR @<ns> <domēns>dnsrecon -d <domēns>Aizsardzība: Atvērta zonu pārsūtīšana atdod visu iekšējo vārdu sarakstu. Liedz AXFR nepilnvarotiem un nerādi iekšējos hostus publiskajā DNS.
Tīmekļa lietotnes
-
Zināmo ievainojamību skenēšana
nuclei -u <url>nikto -h <url>Aizsardzība: Skeneri meklē publiski zināmas ievainojamības un nepareizu konfigurāciju. Aizsardzība: tīmekļa lietotņu ugunsmūris (WAF) priekšā, ievades validācija serverī un regulāri ielāpi.
-
Slēpto failu un ceļu pārbaude
ffuf -w <wordlist> -u <url>/FUZZgobuster dir -u <url> -w <wordlist>Aizsardzība: Uzbrucējs mēģina atrast .env, .git un dublējumus. Nekad neliec noslēpumus zem webroot un noraidi šos ceļus jau tīmekļa servera malā, pirms tie sasniedz lietotni.
-
Starpnieka pārbaude (Burp, ZAP)
# Burp Suite / OWASP ZAP - manuāla pieprasījumu pārtveršanazap-baseline.py -t <url>Aizsardzība: Pārtverošs starpnieks rāda, ka klienta puses pārbaudes var apiet. Katru vārteju izpildi SERVERĪ, ne tikai pārlūkā, un lieto CSRF žetonus un piederības pārbaudes.
TLS un šifrēšana
-
TLS konfigurācijas pārbaude
testssl.sh <host>:443sslscan <host>Aizsardzība: Izslēdz protokolus zem TLS 1.2 un vājos šifrus, ieslēdz HSTS. Novecojis protokols ir lēns, bet drošs ceļš uz starpnieka uzbrukumu.
-
Sertifikāta pārbaude
openssl s_client -connect <host>:443 -servername <host>Aizsardzība: Pārbaudi, vai sertifikāts ir derīgs, neizbeidzies un atbilst domēnam. Automatizē atjaunošanu, lai termiņš klusi nebeidzas.
Paroļu un hašu audits
-
Hašu stipruma audits (uz saviem hašiem)
hashcat -m <režīms> hashes.txt <wordlist>john --wordlist=<wordlist> hashes.txtAizsardzība: Palaid pret SAVIEM izvilktajiem hašiem, lai redzētu, cik ātri vājas paroles krīt. Aizsardzība: stiprs, lēns jaucējalgoritms, pietiekami garas paroles un konta bloķēšana pēc neveiksmīgiem mēģinājumiem.
-
Pieteikšanās noturība pret minēšanu
# autorizēts tests pret SAVU pieteikšanās galapunktunmap -p 80,443 --script http-brute <mērķis>Aizsardzība: Ātruma ierobežošana un konta bloķēšana padara tiešu minēšanu nerentablu. Pret sadalītu minēšanu no daudzām adresēm vajag reputācijas slāni, kas bloķē adreses pēc to uzvedības citur.
Pieejamības noturība (DoS)
-
Lēnā HTTP noturība (Slowloris klase)
slowhttptest -c 500 -H -u <url>Aizsardzība: Slowloris tur savienojumus atvērtus ar lēni sūtītām galvenēm. Aizsardzība: pieprasījuma taimauti un vienlaicīgo savienojumu ierobežojums uz IP. Testē TIKAI savu testa vidi.
-
Slodzes noturība
ab -n 10000 -c 100 <url># vai slodzes ģenerators (wrk, Locust) - TIKAI pret savu vidiAizsardzība: Izmēri, cik pieprasījumu sekundē sistēma iztur. Aizsardzība: anonīmo lapu kešs un ātruma ierobežojumi; saglabā izmērīto bāzlīniju un salīdzini pēc katras izmaiņas.