Golang : Force your program to run with root permissions
Problem:
Because of security requirements, you need to create programs that can only be executed with the proper root
permissions. For example, if a non-root user tries to execute the executable, instead of running as usual......the program will not prompt for the root password and will also display a warning message that it is only meant for those with root
privilege before exiting.
How do to that?
Solution:
On Mac/Unix/Linux operating systems, there is a program call id
that is used to return the user identity. For example, if you have the root
privilege, executing the command sudo id -u
will return 0 instead of 501
$id -u
501
$sudo id -u
0
We will incorporate this id -u
command into our simple Golang program to check for the root
privilege. Try executing the following program with and without sudo
to see the differences.
Here you go!
package main
import (
"log"
"os/exec"
"strconv"
)
func main() {
cmd := exec.Command("id", "-u")
output, err := cmd.Output()
if err != nil {
log.Fatal(err)
}
// output has trailing \n
// need to remove the \n
// otherwise it will cause error for strconv.Atoi
// log.Println(output[:len(output)-1])
// 0 = root, 501 = non-root user
i, err := strconv.Atoi(string(output[:len(output)-1]))
if err != nil {
log.Fatal(err)
}
if i == 0 {
log.Println("Awesome! You are now running this program with root permissions!")
} else {
log.Fatal("This program must be run as root! (sudo)")
}
}
Output:
$ ./checksudo
2017/04/22 16:23:10 This program must be run as root! (sudo)
$ sudo ./checksudo
Password:
2017/04/22 16:23:16 Awesome! You are now running this program with root permissions!
References:
https://www.socketloop.com/tutorials/execute-shell-command-golang
https://adamscheller.com/systems-administration/check-if-bash-script-is-run-with-root-permissions/
See also : Golang : Remove characters from string example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+5.6k CodeIgniter/PHP : Remove empty lines above RSS or ATOM xml tag
+19.9k Golang : How to get struct tag and use field name to retrieve data?
+6.6k Golang : Muxing with Martini example
+12.4k Golang : Remove or trim extra comma from CSV
+6.3k Golang : Totalize or add-up an array or slice example
+19.1k Golang : Fix cannot download, $GOPATH not set error
+12.9k Golang : Handle or parse date string with Z suffix(RFC3339) example
+15.9k Golang : Loop each day of the current month example
+6.5k Golang : Join lines with certain suffix symbol example
+13k CodeIgniter : "Fatal error: Cannot use object of type stdClass as array" message
+7.3k Gogland : Single File versus Go Application Run Configurations
+20.9k Golang : Create and resolve(read) symbolic links