Skip to content

one-api/winutil

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

2 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Platform Windows MIT License Support LTS

winutil πŸš€

One repo for Windows utils in Go, all you need.

  • Pure, production-ready Go-style APIs β€” Zero CGO, no os/exec command-line wrappers, no syscall.
  • One-line superpowers β€” like RunAsAdmin(), RunTask(), and EmptyRecycleBin().
  • Complete control β€” Master Services, File Systems, Network states, and more.

⚑ Actively developed. Contributions, feature requests, and PRs are more than welcome!


πŸ“¦ Feature Index

Module Feature Description Status
πŸ–₯️ System & Hardware Accurate OS Version Bypass compatibility shims to get true Windows version and build. 🟒 Stable
Active Sessions List logged-on users and retrieve the active console/desktop session user. 🟒 Stable
USB Device Monitoring Background message-only window listener for USB device plug/unplug. 🟒 Stable
Last Shutdown Reason Query Event Log for last shutdown/reboot/BSOD event parameters. 🟒 Stable
Display & Monitor Metrics Query multi-monitor geometry, bounds, and DPI scaling factors. 🟒 Stable
System Uptime Retrieve elapsed duration since the Windows system was booted. 🟒 Stable
Workstation Control Instantly lock the current Windows desktop session. 🟒 Stable
Recycle Bin Control Programmatically empty the Recycle Bin on all drives silently. 🟒 Stable
Memory Metrics Query current physical and virtual memory utilization bytes. 🟒 Stable
Workstation Lock State Detect if the workstation session is currently locked. 🟑 Roadmap
CPU Metrics Query average or core-level active CPU utilization percentage. 🟑 Roadmap
GPU Info & Diagnostics Detect active graphics card models, driver versions, and dedicated VRAM capacity. 🟑 Roadmap
Battery & Power Status Query real-time power source (AC/DC) and precise remaining battery percentage. 🟑 Roadmap
BIOS & Motherboard Info Retrieve physical motherboard serial number, manufacturer, and BIOS date/version. 🟑 Roadmap
πŸ“‚ Files & Shell Shortcuts (.lnk) Create (.lnk via COM) and parse (.lnk via custom binary parser) shortcuts natively. 🟒 Stable
Known Folders Retrieve true paths to Desktop, AppData, LocalAppData, etc. 🟒 Stable
File Lock Hunter Identify which processes (PIDs) currently lock a specific file. 🟒 Stable
Disk & Partitions Retrieve disk SN (hardware), partition GUID, and filesystem format (NTFS, etc). 🟒 Stable
Drive Type Query Retrieve drive storage type (e.g., Fixed, CD-ROM, Removable, Network). 🟒 Stable
Disk Free Space Query total, free, and caller-available bytes on any path/volume. 🟒 Stable
File Attributes Programmatically check or toggle the "Hidden" file attribute. 🟒 Stable
File Owner Query Retrieve security owner (Domain\User) details for any file/folder. 🟑 Roadmap
Recycle Bin Space Programmatically query aggregate file count and total size in the Recycle Bin. 🟑 Roadmap
NTFS Alternate Streams List, create, read, and delete hidden Alternate Data Streams (ADS) natively. 🟑 Roadmap
USN Journal Change Monitor Real-time change tracking of volume/directory file modifications and write events. 🟑 Roadmap
🌐 Network & Firewall Advanced Networking Retrieve adapter physical MAC addresses and Native Wi-Fi SSID/signal. 🟒 Stable
Firewall Rules Programmatically add, update, or delete Windows Firewall rules. 🟒 Stable
Port-to-PID Tracking Find which local process (PID) owns a specific TCP/UDP port. 🟒 Stable
Internet Connectivity Instant NLA-based network connectivity status check. 🟒 Stable
DNS Client Cache Programmatically flush the system DNS client resolver cache. 🟒 Stable
Native Ping Calculate latency via ICMP echo packets without spawning ping.exe. 🟑 Roadmap
Active TCP/UDP Table Enumerate all live network connections, local/remote endpoints, and states. 🟑 Roadmap
System Proxy Settings Query, toggle, or update system-wide dynamic Internet Explorer proxy endpoints. 🟑 Roadmap
Network Routing Table Retrieve and parse current static and dynamic routing configurations. 🟑 Roadmap
πŸš€ Process & Control Process Parameters Query any process's command line, working directory, and parent PID. 🟒 Stable
Single Instance Lock Global Mutex lock to ensure a single instance of an application runs. 🟒 Stable
Environment Sync Modify system environment variables and broadcast to the OS instantly. 🟒 Stable
Job Objects Bind child processes to a Job Object to ensure auto-kill on parent crash. 🟒 Stable
Process Running Check Case-insensitive check of process activity by executable name. 🟒 Stable
Process Memory Metrics Retrieve private working set, virtual size, and page fault counts for any PID. 🟑 Roadmap
CPU Affinity Mask Query or set processor core affinity masks to restrict process execution. 🟑 Roadmap
Token Impersonation Duplicate and impersonate high-privilege tokens to execute code as another user. 🟑 Roadmap
πŸ›‘οΈ Security & Credentials Digital Signature Verification Validate executable/DLL signatures, extract leaf certs and details. 🟒 Stable
UAC & Privilege Checks Check if running as Admin (elevated token). 🟒 Stable
Privilege Elevation & Drop Launch processes as Administrator or downgrade to standard user sessions. 🟒 Stable
Credential Manager Read, write, and delete Windows Credential Manager generic credentials. 🟒 Stable
Access Control (ACL) Modify DACL/ACE permissions on files/folders without boilerplate. 🟒 Stable
User SID Retrieve the Security Identifier (SID) string of the current user. 🟒 Stable
Token Elevation Type Retrieve token elevation context ("Default", "Full", "Limited"). 🟒 Stable
UAC Status Query registry policy to check if User Account Control is enabled. 🟒 Stable
Adjust Privileges Dynamically enable or disable specific LUID process privileges. 🟑 Roadmap
Run as SYSTEM Spawn a child process with local NT AUTHORITY\SYSTEM credentials. 🟑 Roadmap
βš™οΈ Automation & Admin Task Scheduler Manage Windows Scheduled Tasks (Create, Read, Update, Delete, Run, Stop). 🟒 Stable
Windows Services Install, uninstall, start, stop, restart, and query Windows services. 🟒 Stable
Simplified Registry API High-level API for registry key and value CRUD operations. 🟒 Stable
Event Log Management Write to and query translated, formatted Windows Event Logs (via PowerShell/Evt). 🟒 Stable
Installed Applications Scan Registry Uninstall nodes to list all installed software. 🟒 Stable
Active Window Tracking Listen to active foreground window transitions and extract their titles natively. 🟑 Roadmap
BitLocker Volume Status Query encryption percentage, encryption status, and protection level of volumes. 🟑 Roadmap

πŸ› οΈ Architecture & Package Layout

The library is logically split into four domain packages:

winutil/
β”œβ”€β”€ executable/     # Security, Credentials, Privileges, UAC, DACL/ACL
β”œβ”€β”€ file/           # Cryptography, Compression, Shortcuts, Known Folders, Disk Info, File Locks
β”œβ”€β”€ system/         # Task Scheduler, Services, Registry, Event Log, Processes, Monitor Metrics, USB, OS Info
└── network/        # Physical MAC, Native Wi-Fi, COM Firewall Rule Management, Port Tracking

πŸ›οΈ Native Go Integrity & Equivalent CLI Mappings

winutil is strictly committed to 100% pure native Win32/COM execution. It contains zero process spawns, zero command-line shell assemblies (e.g., os/exec to cmd or powershell), and zero CGO dependencies. Instead of wrapping command-line tools, winutil communicates directly with Windows Kernel, Security, and Desktop APIs.

Below is a complete quick-reference mapping of each Go function inside winutil to its equivalent standard Windows CLI command, alongside a list of powerful Native-Only Capabilities that have no standard command-line equivalents.

πŸ›‘οΈ Security & Credentials (executable)

Go Function Equivalent Windows CLI / PowerShell Command
VerifySignature signtool verify /pa <filePath> or Get-AuthenticodeSignature
GetLeafCertificate PowerShell (Get-AuthenticodeSignature <filePath>).SignerCertificate
IsAdmin whoami /groups or checking net session
RunAsAdmin powershell Start-Process <cmdPath> -Verb RunAs or runas
RunAsUser None (Native-Only Explorer Token Duplication)
WriteCredential cmdkey /generic:<target> /user:<user> /pass:<pass>
ReadCredential cmdkey /list:<target> (cmdkey won't show passwords for safety)
DeleteCredential cmdkey /delete:<target>
GrantFileAccess icacls <filePath> /grant <identity>:(permission)
RevokeFileAccess icacls <filePath> /remove <identity>
GetCurrentUserSID whoami /user or (Get-WmiObject Win32_UserAccount -Filter "Name='$env:username'").SID
GetTokenElevationType None (Native-Only TokenElevationType structure query)
IsUACEnabled reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA
EnablePrivilege None (Native-Only AdjustTokenPrivileges API) [Roadmap]
RunAsSystem None (Native-Only Service Token Duplication) [Roadmap]
ImpersonateToken None (Native-Only ImpersonateLoggedOnUser API) [Roadmap]

πŸ“‚ Files, Shell & Cryptography (file)

Go Function Equivalent Windows CLI / PowerShell Command
CalculateMD5 certutil -hashfile <filePath> MD5
EncryptAES / DecryptAES None (No native CMD handles raw AES-CFB encryption)
GetDiskSerialNumber wmic diskdrive get serialnumber or Get-PhysicalDisk
GetPartitionGUID mountvol or diskpart
GetFileSystemFormat fsutil fsinfo volumeinfo <drive>
GetKnownFolderPath PowerShell [Environment]::GetFolderPath(...)
GetFileLocks Sysinternals handle.exe -p <pid> <filePath> or openfiles
CreateShortcut PowerShell (New-Object -COM WScript.Shell).CreateShortcut(...)
ResolveShortcut PowerShell (New-Object -COM WScript.Shell).CreateShortcut(...).TargetPath
ParseLnkFile None (Native-Only High-speed pure Go binary .lnk parser)
Zip PowerShell Compress-Archive -Path <src> -DestinationPath <dest>
Unzip PowerShell Expand-Archive -Path <src> -DestinationPath <dest>
GetDriveType wmic diskdrive get mediatype or PowerShell Get-Volume
GetDiskFreeSpace fsutil volume diskfree <path> or PowerShell Get-Volume
IsFileHidden attrib <path> (checking for 'H' attribute)
SetFileHidden attrib +h <path> or attrib -h <path>
GetFileOwner PowerShell (Get-Acl <path>).Owner [Roadmap]
GetRecycleBinSize PowerShell (Get-ChildItem -Path C:\$Recycle.Bin -Recurse -Force).Length` [Roadmap]
GetNTFSAlternateStreams dir /r or PowerShell Get-Item -AlternateStream * [Roadmap]
MonitorUSNJournal fsutil usn readjournal [Roadmap]

🌐 Networking & Firewall (network)

Go Function Equivalent Windows CLI / PowerShell Command
AddFirewallRule netsh advfirewall firewall add rule ... or New-NetFirewallRule
DeleteFirewallRule netsh advfirewall firewall delete rule ... or Remove-NetFirewallRule
GetPortOwner netstat -ano | findstr <port>
GetMACAddress getmac /fo list or ipconfig /all or Get-NetAdapter
GetWiFiInfo netsh wlan show interfaces
IsInternetAvailable None (Native-Only high-speed NLA state check)
FlushDNS ipconfig /flushdns or PowerShell Clear-DnsClientCache
Ping ping or PowerShell Test-Connection [Roadmap]
GetActiveTCPTable netstat -an [Roadmap]
GetSystemProxy netsh winhttp show proxy [Roadmap]
GetRoutingTable route print [Roadmap]

πŸ–₯️ System & Automation (system)

Go Function Equivalent Windows CLI / PowerShell Command
GetDisplayInfo PowerShell Get-CimInstance Win32_VideoController
WriteEventLog eventcreate /ID <eventID> /L APPLICATION /SO <sourceName> ...
ReadEventLog wevtutil qe <logName> ... or PowerShell Get-WinEvent
getLogicalDrives fsutil fsinfo drives or PowerShell Get-PSDrive
ExpandEnv echo %variable% or cmd.exe /c "echo ..."
GetExecutablePathByPID wmic process where processid=<pid> get executablepath
GetProcessCommandLine wmic process where processid=<pid> get commandline
GetProcessWorkingDirectory None (Querying PEB CurrentDirectory of another process)
GetProcessParentPID wmic process where processid=<pid> get parentprocessid
SingleInstanceLock None (Native-Only Kernel Mutex Synchronization)
SyncEnvironment PowerShell [Environment]::SetEnvironmentVariable(...)
AssignProcessToJobObject None (Native-Only OS Job Object Sandboxing)
SetRegistryString reg add "<key>" /v "<name>" /t REG_SZ /d "<val>" /f
GetRegistryString reg query "<key>" /v "<name>"
DeleteRegistryValue reg delete "<key>" /v "<name>" /f
DeleteRegistryKey reg delete "<key>" /f
GetTasks schtasks /query /fo list or PowerShell Get-ScheduledTask
CreateTask schtasks /create /tn "<task>" /tr "<exe>" ...
DeleteTask schtasks /delete /tn "<task>" /f
RunTask schtasks /run /tn "<task>"
StopTask schtasks /end /tn "<task>"
InstallService sc.exe create <name> binPath= "<exePath>"
RemoveService sc.exe delete <name>
StartService sc.exe start <name> or net start <name>
StopService sc.exe stop <name> or net stop <name>
QueryService sc.exe query <name>
GetActiveUser query user or qwinsta
GetLoggedOnUsers qwinsta or query session
GetLastShutdownReason wevtutil qe System /q:"*[System[(EventID=1074 or ...)]]" ...
GetInstalledSoftware wmic product get name or querying Uninstall Registry paths
GetStartupItemsFromRegKeys PowerShell query of Run keys
GetBootItemsFromFolder dir "%USERPROFILE%\AppData\Roaming\...\Programs\Startup"
ListenUSBDeviceEvents None (Native-Only dynamic Window message loop listening)
GetAccurateOSVersion systeminfo | findstr /B /C:"OS Version"
GetSystemUptime systeminfo (uptime field) or PowerShell LastBootUpTime
LockWorkstation rundll32.exe user32.dll,LockWorkStation
EmptyRecycleBin PowerShell Clear-RecycleBin -Force
IsProcessRunning tasklist /fi "imagename eq <name>" or PowerShell Get-Process
GetMemoryStatus systeminfo or PowerShell Get-CimInstance Win32_OperatingSystem
GetCPUUsage wmic cpu get loadpercentage [Roadmap]
IsWorkstationLocked None (Native-Only lock check API) [Roadmap]
GetGPUInfo wmic path win32_VideoController get name [Roadmap]
GetBatteryStatus powercfg /batteryreport or PowerShell Get-CimInstance Win32_Battery [Roadmap]
GetBIOSInfo wmic bios get serialnumber or PowerShell Get-CimInstance Win32_Bios [Roadmap]
GetProcessMemoryMetrics tasklist or PowerShell (Get-Process -Id <pid>).WorkingSet [Roadmap]
SetProcessAffinity PowerShell (Get-Process -Id <pid>).ProcessorAffinity = <mask_value> [Roadmap]
TrackActiveWindow None (Native-Only Event Hooks: SetWinEventHook) [Roadmap]
GetBitLockerStatus manage-bde -status or PowerShell Get-BitLockerVolume [Roadmap]

πŸ”‘ Exclusive Native-Only Capabilities

These features are implemented directly via low-level kernel abstractions or dynamic OS synchronization primitives, and cannot be directly mapped or simulated via standard single-line CLI commands:

  1. ListenUSBDeviceEvents: Sets up a specialized message-only background window via RegisterClassExW and CreateWindowExW to capture WM_DEVICECHANGE and DBT_DEVICEARRIVAL Windows messages dynamically in real-time. No standard CLI can do asynchronous Windows message loop subscription.
  2. SingleInstanceLock: Leverages the Windows Kernel Mutex synchronization object via windows.CreateMutex. It guarantees single-process orchestration across separate Windows sessions natively in memory.
  3. AssignProcessToJobObject: Leverages Windows Job Objects (CreateJobObjectW, AssignProcessToJobObject) to sandbox child processes and guarantee their immediate, clean termination when the parent process exits or crashes.
  4. RunAsUser: Re-duplicates the Shell (explorer.exe) token via OpenProcessToken and DuplicateTokenEx to downgrade privilege from Administrator down to a standard active session user.

πŸš€ Installation & Setup

Ensure you have Go installed (version 1.22 or later).

git clone https://github.com/your-username/winutil.git
cd winutil
go mod tidy

πŸ’» Code Examples

πŸ›‘οΈ 1. Privilege Elevation & Administrator Check (Most Popular)

Below is the standard, production-ready pattern for checking whether the current process has administrator permissions and, if not, requesting dynamic self-elevation.

package main

import (
	"fmt"
	"os"

	"github.com/one-api/winutil/executable"
)

func main() {
	// Check if running with elevated administrator privileges
	if !executable.IsAdmin() {
		fmt.Println("⚠️ Current process is NOT running as Administrator.")
		fmt.Println("Attempting self-elevation...")

		// Get the current executable path to re-launch as administrator
		exePath, err := os.Executable()
		if err != nil {
			fmt.Printf("Failed to locate current executable: %v\n", err)
			return
		}

		// Relaunch the executable as administrator, passing the original arguments
		// The final parameter 'true' will show the newly spawned elevated console window
		err = executable.RunAsAdmin(exePath, os.Args[1:], true)
		if err != nil {
			fmt.Printf("❌ Failed to elevate privileges: %v\n", err)
			return
		}

		fmt.Println("Elevation request sent! Exiting current standard instance.")
		os.Exit(0)
	}

	fmt.Println("πŸ›‘οΈ Success: Running with full elevated Administrator privileges!")
}

πŸ–₯️ 2. System Diagnostics, Internet Status & Storage Telemetry

This unified example retrieves the system's runtime uptime, total/free physical memory, current security identifier ( SID), and active network NLA internet status.

package main

import (
	"fmt"

	"github.com/one-api/winutil/executable"
	"github.com/one-api/winutil/file"
	"github.com/one-api/winutil/network"
	"github.com/one-api/winutil/system"
)

func main() {
	fmt.Println("=== WINDOWS SYSTEM TELEMETRY ===")

	// 1. Check Internet Connectivity (NLA check: no slow socket ping required)
	if network.IsInternetAvailable() {
		fmt.Println("🌐 Network: Internet is connected and active.")
	} else {
		fmt.Println("🌐 Network: No internet connection detected.")
	}

	// 2. Query System Uptime
	uptime, err := system.GetSystemUptime()
	if err == nil {
		fmt.Printf("πŸ•’ System Uptime: %v\n", uptime)
	}

	// 3. Query Memory Status
	totalPhys, availPhys, _, _, err := system.GetMemoryStatus()
	if err == nil {
		fmt.Printf("🧠 Physical Memory: %d GB Total / %d GB Available\n",
			totalPhys/(1024*1024*1024), availPhys/(1024*1024*1024))
	}

	// 4. Query Current User SID
	sid, err := executable.GetCurrentUserSID()
	if err == nil {
		fmt.Printf("πŸ‘€ User Security SID: %s\n", sid)
	}

	// 5. Query Storage Capacity on Disk C:
	totalSpace, freeSpace, availableSpace, err := file.GetDiskFreeSpace("C:\\")
	if err == nil {
		fmt.Printf("πŸ’Ύ Disk C: Total: %d GB | Free: %d GB | Available: %d GB\n",
			totalSpace/(1024*1024*1024), freeSpace/(1024*1024*1024), availableSpace/(1024*1024*1024))
	}
}

πŸ“‚ 3. Managing Native Windows Shortcuts (.lnk)

Create shortcuts via standard shell COM bindings and inspect or parse target metadata binaries utilizing our lightweight, custom, high-speed LNK parser.

package main

import (
	"fmt"

	"github.com/one-api/winutil/file"
)

func main() {
	shortcutPath := `C:\Users\Public\Desktop\MyShortcut.lnk`
	targetPath := `C:\Windows\System32\cmd.exe`

	// 1. Create a native Windows shortcut (.lnk file)
	err := file.CreateShortcut(shortcutPath, targetPath, "", "", 0)
	if err != nil {
		fmt.Printf("Failed to create shortcut: %v\n", err)
		return
	}
	fmt.Printf("βœ… Shortcut created successfully at: %s\n", shortcutPath)

	// 2. Parse and resolve shortcut target path using our pure Go parser
	lnk, err := file.ParseLnkFile(shortcutPath)
	if err != nil {
		fmt.Printf("Failed to parse shortcut: %v\n", err)
		return
	}

	fmt.Printf("πŸ” Parsed Shortcut target: %s\n", lnk.TargetPath)
	if lnk.Description != "" {
		fmt.Printf("πŸ“ Description: %s\n", lnk.Description)
	}
}

βš™οΈ 4. Workstation Security & Silence Empty Recycle Bin

Interact directly with the Windows Shell interface to silently clear cached items, followed by a local kernel call to lock the screen.

package main

import (
	"fmt"

	"github.com/one-api/winutil/system"
)

func main() {
	// 1. Programmatically empty Recycle Bin silently (No sound, progress UI, or confirmations)
	fmt.Println("Cleaning up files...")
	err := system.EmptyRecycleBin()
	if err != nil {
		fmt.Printf("Failed to empty recycle bin: %v\n", err)
	} else {
		fmt.Println("πŸ—‘οΈ Recycle Bin emptied successfully!")
	}

	// 2. Lock Workstation instantly (equivalent to Win + L)
	fmt.Println("Locking screen for security...")
	err = system.LockWorkstation()
	if err != nil {
		fmt.Printf("Failed to lock desktop session: %v\n", err)
		return
	}
	fmt.Println("πŸ”’ Desktop locked successfully.")
}

πŸ§ͺ Running Tests

The library is equipped with robust unit tests across all packages. You can run all test suites instantly without compiling CGO:

go test -v ./...

πŸ“Š Diagnostics Console Dashboard

To run the built-in diagnostic dashboard demonstrating real-time outputs of the entire library, execute:

go run main.go

License & Contact

  • License: This project is licensed under the MIT License. Copyright (c) 2026 github.com/one-api.
  • Contact: hello@one-api.net or file a GitHub Issue.

About

One repo for Windows utils in Go, all you need. 100% native Win32/COM execution for services, tasks, UAC elevation, files, networks and more.

Resources

License

Stars

1 star

Watchers

1 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages