Home  >  Article  >  Backend Development  >  Reverse function or library of os.Getenv()

Reverse function or library of os.Getenv()

王林
王林forward
2024-02-15 15:45:08832browse

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.com. If there is any infringement, please contact admin@php.cn delete