本文整理汇总了Golang中os.Getgroups函数的典型用法代码示例。如果您正苦于以下问题:Golang Getgroups函数的具体用法?Golang Getgroups怎么用?Golang Getgroups使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Getgroups函数的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: CurrentProcessInfo
func CurrentProcessInfo() *ProcessInfo {
var hasTty bool
cwd, _ := os.Getwd()
grp, _ := os.Getgroups()
// no syscall.Getsid() wrapper on Linux?
sid, _, _ := syscall.RawSyscall(syscall.SYS_GETSID, 0, 0, 0)
if fh, err := os.Open("/dev/tty"); err == nil {
hasTty = true
fh.Close()
}
return &ProcessInfo{
Ppid: os.Getppid(),
Pid: os.Getpid(),
Uid: os.Getuid(),
Euid: os.Geteuid(),
Gid: os.Getgid(),
Egid: os.Getegid(),
Pgrp: syscall.Getpgrp(),
Sid: int(sid),
Dir: cwd,
Groups: grp,
Args: os.Args,
Env: os.Environ(),
HasTty: hasTty,
}
}
示例2: testFileChown
func testFileChown(t *testing.T, s *Client, path string) {
uid, oldGID, err := stat(path)
if err != nil {
t.Errorf("stat(%q) = _, %v want nil", path, err)
return
}
groups, err := os.Getgroups()
if err != nil {
t.Errorf("os.GetGroups() = _, %v, want nil", err)
return
}
var newGID int
if groups[0] != int(oldGID) {
newGID = groups[0]
} else {
newGID = groups[1]
}
f, err := s.Open(path)
if err != nil {
t.Errorf("Open(%q) = %v, want nil", path, err)
}
f.Chown(int(uid), newGID)
_, gid, err := stat(path)
if err != nil {
t.Errorf("stat(%q) = _, %v want nil", path, err)
}
if gid != uint32(newGID) {
t.Errorf("gid = %d, want %d", gid, newGID)
}
}
示例3: main
func main() {
// 获取系统名字
fmt.Println(os.Hostname())
// 获取系统内存
fmt.Println(os.Getpagesize())
// 获取系统环境变量
for index, env := range os.Environ() {
fmt.Println(index, " : ", env)
}
// 获取指定key的环境变量,环境变量不区分大小写
fmt.Println("当前系统目录为:", os.Getenv("windir"))
// 设置环境变量
fmt.Println("cody的环境变量为:", os.Getenv("cody"))
os.Setenv("Cody", "guo")
fmt.Println("cody的环境变量为:", os.Getenv("cody"))
// 删除所有环境变量
os.Clearenv()
fmt.Println(os.Environ())
// 如果存在os.Exit()就不会执行defer
// defer fmt.Println("我在退出吗?")
// os.Exit(0)
fmt.Println("程序已退出,不打印了...")
fmt.Println(os.Getuid(), os.Getgid())
fmt.Println(os.Getgroups())
fmt.Println(os.Getpid(), os.Getppid())
fmt.Println(os.TempDir())
}
示例4: main
func main() {
ids, err := os.Getgroups()
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("%v\n", ids)
}
示例5: validateLinuxProcess
func validateLinuxProcess(spec *rspec.Spec) error {
logrus.Debugf("validating container process")
validateGeneralProcess(spec)
uid := os.Getuid()
if uint32(uid) != spec.Process.User.UID {
return fmt.Errorf("UID expected: %v, actual: %v", spec.Process.User.UID, uid)
}
gid := os.Getgid()
if uint32(gid) != spec.Process.User.GID {
return fmt.Errorf("GID expected: %v, actual: %v", spec.Process.User.GID, gid)
}
groups, err := os.Getgroups()
if err != nil {
return err
}
groupsMap := make(map[int]bool)
for _, g := range groups {
groupsMap[g] = true
}
for _, g := range spec.Process.User.AdditionalGids {
if !groupsMap[int(g)] {
return fmt.Errorf("Groups expected: %v, actual (should be superset): %v", spec.Process.User.AdditionalGids, groups)
}
}
cmdlineBytes, err := ioutil.ReadFile("/proc/1/cmdline")
if err != nil {
return err
}
args := bytes.Split(bytes.Trim(cmdlineBytes, "\x00"), []byte("\x00"))
if len(args) != len(spec.Process.Args) {
return fmt.Errorf("Process arguments expected: %v, actual: %v", len(spec.Process.Args), len(args))
}
for i, a := range args {
if string(a) != spec.Process.Args[i] {
return fmt.Errorf("Process arguments expected: %v, actual: %v", string(a), spec.Process.Args[i])
}
}
ret, _, errno := syscall.Syscall6(syscall.SYS_PRCTL, PR_GET_NO_NEW_PRIVS, 0, 0, 0, 0, 0)
if errno != 0 {
return errno
}
if spec.Process.NoNewPrivileges && ret != 1 {
return fmt.Errorf("NoNewPrivileges expected: true, actual: false")
}
if !spec.Process.NoNewPrivileges && ret != 0 {
return fmt.Errorf("NoNewPrivileges expected: false, actual: true")
}
return nil
}
示例6: checkGroup
func checkGroup() {
groups, _ := os.Getgroups()
var fuseGroup bool
fuseGroup = false
for i := 0; i < len(groups); i++ {
if groups[i] == 104 {
fuseGroup = true
}
}
if fuseGroup == false {
log.Printf("Add yourself to the fuse usergroup by:\n useradd -G fuse [username]")
}
}
示例7: RESTGetRuntimeArgs
func RESTGetRuntimeArgs(w http.ResponseWriter, r *http.Request) {
flags := map[string]interface{}{}
flag.VisitAll(func(f *flag.Flag) {
flags[f.Name] = f.Value
})
env := []string(nil)
for _, e := range os.Environ() {
if !strings.Contains(e, "PASSWORD") &&
!strings.Contains(e, "PSWD") &&
!strings.Contains(e, "AUTH") {
env = append(env, e)
}
}
groups, groupsErr := os.Getgroups()
hostname, hostnameErr := os.Hostname()
user, userErr := user.Current()
wd, wdErr := os.Getwd()
MustEncode(w, map[string]interface{}{
"args": os.Args,
"env": env,
"flags": flags,
"process": map[string]interface{}{
"euid": os.Geteuid(),
"gid": os.Getgid(),
"groups": groups,
"groupsErr": cbgt.ErrorToString(groupsErr),
"hostname": hostname,
"hostnameErr": cbgt.ErrorToString(hostnameErr),
"pageSize": os.Getpagesize(),
"pid": os.Getpid(),
"ppid": os.Getppid(),
"user": user,
"userErr": cbgt.ErrorToString(userErr),
"wd": wd,
"wdErr": cbgt.ErrorToString(wdErr),
},
})
}
示例8: Launch
func Launch(arg, cpath string, args []string, noexec bool) error {
idx, name, err := parseProfileArg(arg)
if err != nil {
return err
}
pwd, _ := os.Getwd()
groups, _ := os.Getgroups()
gg := []uint32{}
if len(groups) > 0 {
gg = make([]uint32, len(groups))
for i, v := range groups {
gg[i] = uint32(v)
}
}
resp, err := clientSend(&LaunchMsg{
Index: idx,
Name: name,
Path: cpath,
Pwd: pwd,
Gids: gg,
Args: args,
Env: os.Environ(),
Noexec: noexec,
})
if err != nil {
return err
}
switch body := resp.Body.(type) {
case *ErrorMsg:
fmt.Printf("error was %s\n", body.Msg)
case *OkMsg:
fmt.Println("ok received")
default:
fmt.Printf("Unexpected message received %+v", body)
}
return nil
}
示例9: validateProcess
func validateProcess(spec *specs.LinuxSpec, rspec *specs.LinuxRuntimeSpec) error {
fmt.Println("validating container process")
uid := os.Getuid()
if uint32(uid) != spec.Process.User.UID {
return fmt.Errorf("UID expected: %v, actual: %v", spec.Process.User.UID, uid)
}
gid := os.Getgid()
if uint32(gid) != spec.Process.User.GID {
return fmt.Errorf("GID expected: %v, actual: %v", spec.Process.User.GID, gid)
}
groups, err := os.Getgroups()
if err != nil {
return err
}
groupsMap := make(map[int]bool)
for _, g := range groups {
groupsMap[g] = true
}
for _, g := range spec.Process.User.AdditionalGids {
if !groupsMap[int(g)] {
return fmt.Errorf("Groups expected: %v, actual (should be superset): %v", spec.Process.User.AdditionalGids, groups)
}
}
if spec.Process.Cwd != "" {
cwd, err := os.Getwd()
if err != nil {
return err
}
if cwd != spec.Process.Cwd {
return fmt.Errorf("Cwd expected: %v, actual: %v", spec.Process.Cwd, cwd)
}
}
cmdlineBytes, err := ioutil.ReadFile("/proc/1/cmdline")
if err != nil {
return err
}
args := strings.Split(string(bytes.Trim(cmdlineBytes, "\x00")), " ")
if len(args) != len(spec.Process.Args) {
return fmt.Errorf("Process arguments expected: %v, actual: %v")
}
for i, a := range args {
if a != spec.Process.Args[i] {
return fmt.Errorf("Process arguments expected: %v, actual: %v", a, spec.Process.Args[i])
}
}
for _, env := range spec.Process.Env {
parts := strings.Split(env, "=")
key := parts[0]
expectedValue := parts[1]
actualValue := os.Getenv(key)
if actualValue != expectedValue {
return fmt.Errorf("Env %v expected: %v, actual: %v", expectedValue, actualValue)
}
}
return nil
}
示例10: main
func main() {
globalFlagset.Parse(os.Args[1:])
args := globalFlagset.Args()
if len(args) > 0 {
fmt.Fprintln(os.Stderr, "Wrong parameters")
os.Exit(1)
}
if globalFlags.PreSleep >= 0 {
time.Sleep(time.Duration(globalFlags.PreSleep) * time.Second)
}
if globalFlags.ReadStdin {
reader := bufio.NewReader(os.Stdin)
fmt.Printf("Enter text:\n")
text, _ := reader.ReadString('\n')
fmt.Printf("Received text: %s\n", text)
}
if globalFlags.CheckTty {
fd := int(os.Stdin.Fd())
var termios syscall.Termios
_, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), syscall.TCGETS, uintptr(unsafe.Pointer(&termios)), 0, 0, 0)
if err == 0 {
fmt.Printf("stdin is a terminal\n")
} else {
fmt.Printf("stdin is not a terminal\n")
}
}
if globalFlags.PrintExec {
fmt.Fprintf(os.Stdout, "inspect execed as: %s\n", os.Args[0])
}
if globalFlags.PrintMsg != "" {
fmt.Fprintf(os.Stdout, "%s\n", globalFlags.PrintMsg)
messageLoopStr := os.Getenv("MESSAGE_LOOP")
messageLoop, err := strconv.Atoi(messageLoopStr)
if err == nil {
for i := 0; i < messageLoop; i++ {
time.Sleep(time.Second)
fmt.Fprintf(os.Stdout, "%s\n", globalFlags.PrintMsg)
}
}
}
if globalFlags.PrintEnv != "" {
fmt.Fprintf(os.Stdout, "%s=%s\n", globalFlags.PrintEnv, os.Getenv(globalFlags.PrintEnv))
}
if globalFlags.PrintCapsPid >= 0 {
caps, err := capability.NewPid(globalFlags.PrintCapsPid)
if err != nil {
fmt.Fprintf(os.Stderr, "Cannot get caps: %v\n", err)
os.Exit(1)
}
fmt.Printf("Capability set: effective: %s\n", caps.StringCap(capability.EFFECTIVE))
fmt.Printf("Capability set: permitted: %s\n", caps.StringCap(capability.PERMITTED))
fmt.Printf("Capability set: inheritable: %s\n", caps.StringCap(capability.INHERITABLE))
fmt.Printf("Capability set: bounding: %s\n", caps.StringCap(capability.BOUNDING))
if capStr := os.Getenv("CAPABILITY"); capStr != "" {
capInt, err := strconv.Atoi(capStr)
if err != nil {
fmt.Fprintf(os.Stderr, "Environment variable $CAPABILITY is not a valid capability number: %v\n", err)
os.Exit(1)
}
c := capability.Cap(capInt)
if caps.Get(capability.BOUNDING, c) {
fmt.Printf("%v=enabled\n", c.String())
} else {
fmt.Printf("%v=disabled\n", c.String())
}
}
}
if globalFlags.PrintUser {
fmt.Printf("User: uid=%d euid=%d gid=%d egid=%d\n", os.Getuid(), os.Geteuid(), os.Getgid(), os.Getegid())
}
if globalFlags.PrintGroups {
gids, err := os.Getgroups()
if err != nil {
fmt.Fprintf(os.Stderr, "Error getting groups: %v\n", err)
os.Exit(1)
}
// getgroups(2): It is unspecified whether the effective group ID of
// the calling process is included in the returned list. (Thus, an
// application should also call getegid(2) and add or remove the
// resulting value.)
egid := os.Getegid()
if !in(gids, egid) {
gids = append(gids, egid)
sort.Ints(gids)
}
var b bytes.Buffer
for _, gid := range gids {
b.WriteString(fmt.Sprintf("%d ", gid))
}
fmt.Printf("Groups: %s\n", b.String())
//.........这里部分代码省略.........
示例11: main
//.........这里部分代码省略.........
}
if globalFlags.PrintCapsPid >= 0 {
caps, err := capability.NewPid(globalFlags.PrintCapsPid)
if err != nil {
fmt.Fprintf(os.Stderr, "Cannot get caps: %v\n", err)
os.Exit(1)
}
fmt.Printf("Capability set: effective: %s (%s)\n", caps.StringCap(capability.EFFECTIVE), globalFlags.SuffixMsg)
fmt.Printf("Capability set: permitted: %s (%s)\n", caps.StringCap(capability.PERMITTED), globalFlags.SuffixMsg)
fmt.Printf("Capability set: inheritable: %s (%s)\n", caps.StringCap(capability.INHERITABLE), globalFlags.SuffixMsg)
fmt.Printf("Capability set: bounding: %s (%s)\n", caps.StringCap(capability.BOUNDING), globalFlags.SuffixMsg)
if capStr := os.Getenv("CAPABILITY"); capStr != "" {
capInt, err := strconv.Atoi(capStr)
if err != nil {
fmt.Fprintf(os.Stderr, "Environment variable $CAPABILITY is not a valid capability number: %v\n", err)
os.Exit(1)
}
c := capability.Cap(capInt)
if caps.Get(capability.BOUNDING, c) {
fmt.Printf("%v=enabled (%s)\n", c.String(), globalFlags.SuffixMsg)
} else {
fmt.Printf("%v=disabled (%s)\n", c.String(), globalFlags.SuffixMsg)
}
}
}
if globalFlags.PrintUser {
fmt.Printf("User: uid=%d euid=%d gid=%d egid=%d\n", os.Getuid(), os.Geteuid(), os.Getgid(), os.Getegid())
}
if globalFlags.PrintGroups {
gids, err := os.Getgroups()
if err != nil {
fmt.Fprintf(os.Stderr, "Error getting groups: %v\n", err)
os.Exit(1)
}
// getgroups(2): It is unspecified whether the effective group ID of
// the calling process is included in the returned list. (Thus, an
// application should also call getegid(2) and add or remove the
// resulting value.)
egid := os.Getegid()
if !in(gids, egid) {
gids = append(gids, egid)
sort.Ints(gids)
}
var b bytes.Buffer
for _, gid := range gids {
b.WriteString(fmt.Sprintf("%d ", gid))
}
fmt.Printf("Groups: %s\n", b.String())
}
if globalFlags.WriteFile {
fileName := os.Getenv("FILE")
if globalFlags.FileName != "" {
fileName = globalFlags.FileName
}
content := os.Getenv("CONTENT")
if globalFlags.Content != "" {
content = globalFlags.Content
}
err := ioutil.WriteFile(fileName, []byte(content), 0600)
if err != nil {
示例12:
dstPath := path.Join(longPath, filepath.Base(dstFile.Name()))
defer os.Remove(dstPath)
dstFile.Close()
fileInfo, err := osFs.Stat(dstPath)
Expect(fileInfo).ToNot(BeNil())
Expect(os.IsNotExist(err)).To(BeFalse())
err = osFs.RemoveAll(dstPath)
Expect(err).ToNot(HaveOccurred())
_, err = osFs.Stat(dstPath)
Expect(os.IsNotExist(err)).To(BeTrue())
})
// Alert future developers that a previously unimplemented
// function in the os package is now implemented on Windows.
It("fails if os features are implemented in Windows", func() {
Expect(os.Chown("", 0, 0)).To(Equal(&os.PathError{"chown", "", syscall.EWINDOWS}), "os.Chown")
Expect(os.Lchown("", 0, 0)).To(Equal(&os.PathError{"lchown", "", syscall.EWINDOWS}), "os.Lchown")
Expect(os.Getuid()).To(Equal(-1), "os.Getuid")
Expect(os.Geteuid()).To(Equal(-1), "os.Geteuid")
Expect(os.Getgid()).To(Equal(-1), "os.Getgid")
Expect(os.Getegid()).To(Equal(-1), "os.Getegid")
_, err := os.Getgroups()
Expect(err).To(Equal(os.NewSyscallError("getgroups", syscall.EWINDOWS)))
})
})
示例13: NewSymlinkManager
func NewSymlinkManager(a WebotsArchive) (*SymlinkWebotsManager, error) {
var err error
res := &SymlinkWebotsManager{
archive: a,
}
res.basepath, res.workpath, res.installpath, err = symlinkManagerPath()
if err != nil {
return nil, err
}
res.templates, err = NewHasHTemplateManager(path.Join(res.workpath, "templates"))
if err != nil {
return nil, err
}
res.usedpath = path.Join(res.workpath, "used")
res.lock, err = lockfile.New(path.Join(res.workpath, "global.lock"))
if err != nil {
return nil, err
}
err = res.listInstalled()
if err != nil {
return nil, err
}
err = res.listUsed()
if err != nil {
return nil, err
}
//checks that we have the right gid
res.gid, err = getGid("webots-manager")
if err != nil {
return nil, err
}
found := false
userGroups, err := os.Getgroups()
if err != nil {
return nil, err
}
for _, g := range userGroups {
if g == res.gid {
found = true
break
}
}
if found == false {
return nil, fmt.Errorf("Current use is not in 'webots-manager' group")
}
webotsHome := os.Getenv("WEBOTS_HOME")
if len(webotsHome) == 0 {
fmt.Printf("WEBOTS_HOME is not set, please consider exporting WEBOTS_HOME=%s", res.installpath)
} else if webotsHome != res.installpath {
return nil, fmt.Errorf("Invalid WEBOTS_HOME=%s, please use WEBOTS_HOME=%s", webotsHome, res.installpath)
}
return res, nil
}