Start the exe executable file compiled by the golang project to obtain windows administrator permissions (UAC)

background:

After the go code is started, it involves operations such as modifying the IP address, which requires administrator rights. Double-clicking the packaged exe file to execute it does not have administrator rights by default. If you modify the IP, you will be prompted to require administrator rights.

Solution 1: Right-click to run the exe file with administrator rights.
Solution 2: When compiling the exe, a pop-up prompt will automatically execute to obtain administrator rights.

Let’s talk directly about solution 2

Note: The prerequisite go environment is already ok

1. Create a new nac.manifest file in the project root directory with the following content:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
        <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
            <security>
                <requestedPrivileges>
                    <requestedExecutionLevel level="requireAdministrator"/>
                </requestedPrivileges>
            </security>
    </trustInfo>
</assembly>

2. Install the rsrc tool go get github.com/akavel/rsrc

3. To make rsrc effective, it needs to be compiled under windows. Find github.com/akavel/rsrc on your computer (for example, search the location directly through Evenything), open it with Terminal, enter go build, press Enter to run, rsrc.exe will be generated

4. Copy rsrc.exe to the /bin/ directory of the go installation directory, such as C:\go\bin

5. For the case where the ico icon is not required and only administrator rights are required: rsrc -manifest nac.manifest -o nac.syso
For the case where the ico icon is required (prepare the icon icon.ico and place it in the project root directory):rsrc -manifest nac.manifest -o nac.syso -ico icon.ico

6. Execute the following command in the project root directory to compile the go project into exe:

Example:

go build -o <此处自定义可执行文件名称>.exe

:: Interfaceless compilation: go build -ldflags="-w -s -H windowsgui" -o MVPTool.exe
:: Conventional compilation (-ldflags="-w -s" is used to remove debugging information)go build -ldflags="-w -s" -o MVPTool.exe

Insert image description here
Double-click to run and you will automatically be prompted to obtain administrator rights.
Insert image description here

Guess you like

Origin blog.csdn.net/qq_38923792/article/details/129419131