search
HomeBackend DevelopmentGolangReverse function or library of os.Getenv()

os.Getenv() 的反向函数或库

php小编苹果今天要为大家介绍的是os.Getenv() 的反向函数或库。在开发中,我们常常需要获取环境变量的值,而os.Getenv() 是一个常用的函数。但是有时候,我们需要根据某个值来获取对应的环境变量名称,这时候就需要一个反向的函数或库来实现了。下面我们将为大家介绍一些常用的方法来实现这个功能。

问题内容

我有一个 reg_expand_sz 类型的十六进制字符串列表。 样本: reg,[hkey_local_machine\softwar\wow6432node], "pathethic"=hex(2):43,00,3a,00,5c,00,57,00,49,00,4e,00,44,00,4f,00 ,57,00,53,00,\00,00 //忽略解析和格式化部分。

我需要将其转换为原始字符串。

预期输出: %systemroot%

实际输出: c:\windows

问题是,当用户最初运行命令终端时,它会展开: reg add hkey_local_machine\softwar\wow6432node /v pathetic /t reg_expand_sz /d "%systemroot%"。稍后使用实际扩展的字符串。例如:初始 %systemroot% = 实际 c:\windows。当我将十六进制字符串转换为常规字符串时,我得到 c:\windows。

这就是为什么我想知道是否有任何库或工具可以通过提供值来获取密钥,即反向。 c:\window :=os.getenv(???).

package main

import (
    "encoding/hex"
    "fmt"
    "log"
    "os"
)

func ctogostring(b []byte) string {
    var buf []byte
    for _, c := range b {
        if c != 0 {
            buf = append(buf, c)
        }
    }
    return string(buf)
}

func main() {

    str := "43003a005c00570049004e0044004f00570053000000" //%systemroot%
    bs, err := hex.decodestring(str)
    if err != nil {
        panic(err)
    }
    //s := ctogostring(bs)
    result := ctogostring(bs)
    fmt.println(result)

    f, err := os.openfile("rollback.bat", os.o_rdwr|os.o_create|os.o_trunc, 0755)
    if err != nil {
        log.fatal(err)
    }

    f.writestring(result + "\n")

}

我尝试过手动执行此操作,但扩展的字符串比我预期的要多。因此,我的程序是有限的。请告知此问题的任何解决方案。 `

func reverseEnvVar(value string) string {
    // Use os.ExpandEnv() to expand environment variables in the input string
    expanded := os.ExpandEnv(value)

    // Check if the expanded string matches a known environment variable value
    switch expanded {
    case os.Getenv("SystemRoot"):
        return "%systemroot%"
    case os.Getenv("ProgramFiles"):
        return "%programfiles%"
    case os.Getenv("ProgramFiles(x86)"):
        return "%programfiles(x86)%"
    case os.Getenv("AppData"):
        return "%appdata%"
    case os.Getenv("LocalAppData"):
        return "%localappdata%"
    case os.Getenv("UserProfile"):
        return "%userprofile%"
    case os.Getenv("TEMP"):
        return "%temp%"
    case os.Getenv("TMP"):
        return "%tmp%"
    default:
        // If the expanded string doesn't match a known environment variable value,
        // return the original input value
        return value
    }
}

解决方法

我没有找到一个接受 c:\windows 并提供 %systemroot% 的库,但它可以使用 os.environ() 轻松实现。

进口:

import (
    "errors"
    "fmt"
    "os"
    "strings"
)

值 -> 键数组的哈希映射:

func createenvhashmap() map[string][]string {
    envmap := make(map[string][]string)

    for _, env := range os.environ() {
        pair := strings.splitn(env, "=", 2)
        if len(pair) == 2 {
            key := fmt.sprintf("%%%s%%", strings.tolower(pair[0]))
            value := pair[1]
            envmap[value] = append(envmap[value], key)
        }
    }

    return envmap
}

返回给定列表的函数:

func getenvkeysbyvalue(envmap map[string][]string, value string) ([]string, error) {
    keys, found := envmap[value]
    if !found {
        return nil, errors.new("no environment variable keys found for the value")
    }
    return keys, nil
}

现在您可以在主函数中使用 getenvkeysbyvalue() 函数:

func main() {

    // create a map of environment variables and their keys
    envmap := createenvhashmap()

    // this value can be replaced with the result variable in your main() function
    value := "c:\\windows"

    // get environment variable keys by value
    keys, err := getenvkeysbyvalue(envmap, value)
    if err != nil {
        fmt.println("error:", err)
        return
    }

    fmt.println("environment variable keys:")
    for _, key := range keys {
        fmt.println(key)
    }
}

输出:

Environment variable keys:
%systemroot%
%windir%

这样就不需要手动编写 switch case 语句了。 确保仅调用 createenvhashmap() 一次,然后多次调用 getenvkeysbyvalue(envmap, value) 以在 o(1) 时间内获取键列表。

The above is the detailed content of Reverse function or library of os.Getenv(). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:stackoverflow. If there is any infringement, please contact admin@php.cn delete
Golang vs. Python: The Pros and ConsGolang vs. Python: The Pros and ConsApr 21, 2025 am 12:17 AM

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Golang and C  : Concurrency vs. Raw SpeedGolang and C : Concurrency vs. Raw SpeedApr 21, 2025 am 12:16 AM

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Why Use Golang? Benefits and Advantages ExplainedWhy Use Golang? Benefits and Advantages ExplainedApr 21, 2025 am 12:15 AM

Reasons for choosing Golang include: 1) high concurrency performance, 2) static type system, 3) garbage collection mechanism, 4) rich standard libraries and ecosystems, which make it an ideal choice for developing efficient and reliable software.

Golang vs. C  : Performance and Speed ComparisonGolang vs. C : Performance and Speed ComparisonApr 21, 2025 am 12:13 AM

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

Is Golang Faster Than C  ? Exploring the LimitsIs Golang Faster Than C ? Exploring the LimitsApr 20, 2025 am 12:19 AM

Golang performs better in compilation time and concurrent processing, while C has more advantages in running speed and memory management. 1.Golang has fast compilation speed and is suitable for rapid development. 2.C runs fast and is suitable for performance-critical applications. 3. Golang is simple and efficient in concurrent processing, suitable for concurrent programming. 4.C Manual memory management provides higher performance, but increases development complexity.

Golang: From Web Services to System ProgrammingGolang: From Web Services to System ProgrammingApr 20, 2025 am 12:18 AM

Golang's application in web services and system programming is mainly reflected in its simplicity, efficiency and concurrency. 1) In web services, Golang supports the creation of high-performance web applications and APIs through powerful HTTP libraries and concurrent processing capabilities. 2) In system programming, Golang uses features close to hardware and compatibility with C language to be suitable for operating system development and embedded systems.

Golang vs. C  : Benchmarks and Real-World PerformanceGolang vs. C : Benchmarks and Real-World PerformanceApr 20, 2025 am 12:18 AM

Golang and C have their own advantages and disadvantages in performance comparison: 1. Golang is suitable for high concurrency and rapid development, but garbage collection may affect performance; 2.C provides higher performance and hardware control, but has high development complexity. When making a choice, you need to consider project requirements and team skills in a comprehensive way.

Golang vs. Python: A Comparative AnalysisGolang vs. Python: A Comparative AnalysisApr 20, 2025 am 12:17 AM

Golang is suitable for high-performance and concurrent programming scenarios, while Python is suitable for rapid development and data processing. 1.Golang emphasizes simplicity and efficiency, and is suitable for back-end services and microservices. 2. Python is known for its concise syntax and rich libraries, suitable for data science and machine learning.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor