当前位置: 首页>>代码示例>>Golang>>正文


Golang user.Lookup函数代码示例

本文整理汇总了Golang中os/user.Lookup函数的典型用法代码示例。如果您正苦于以下问题:Golang Lookup函数的具体用法?Golang Lookup怎么用?Golang Lookup使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Lookup函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: main

func main() {
	kingpin.Parse()

	u, err := user.Lookup(*cliChownUser)
	if err != nil {
		panic(err)
	}

	g, err := user.Lookup(*cliChownGroup)
	if err != nil {
		panic(err)
	}

	uid, err = strconv.Atoi(u.Uid)
	if err != nil {
		panic(err)
	}

	gid, err = strconv.Atoi(g.Gid)
	if err != nil {
		panic(err)
	}

	// Ensure all folders and files are currently set to the correct permissions.
	filepath.Walk(*cliDir, update)

	// Now we will wait for
	watch(*cliDir)
}
开发者ID:nickschuch,项目名称:permissions,代码行数:29,代码来源:main.go

示例2: fsPosixSetPerms

func fsPosixSetPerms(log *logging.Logger, element *common.JSONFile) common.JSONResult {
	var uid, gid int
	var result common.JSONResult

	uname, err := user.Lookup(element.User)
	if err != nil {
		uname, _ := user.Lookup("nobody")
		uid, _ = strconv.Atoi(uname.Uid)
		gid, _ = strconv.Atoi(uname.Gid)
	} else {
		uid, _ = strconv.Atoi(uname.Uid)
		gid, err = getGroupId(element.Group)
		if err != nil {
			gid, _ = getGroupId("nogroup")
		}
	}

	// TODO: fix possible error if element.Mode is empty
	if err := os.Chmod(element.Name, getPerms(element.Mode)); err != nil {
		log.Debug("Error:", err)
		result = common.JSONResult{Result: "ko", Message: err.Error()}
	} else {
		if err := os.Chown(element.Name, uid, gid); err != nil {
			log.Debug("Error:", err)
			result = common.JSONResult{Result: "ko", Message: err.Error()}
		} else {
			result = common.JSONResult{Result: "ok"}
		}
	}

	return result
}
开发者ID:mementobackup,项目名称:client,代码行数:32,代码来源:put.go

示例3: isDataboxUser

func isDataboxUser() bool {
	u, err := user.Lookup(pamUser)
	if err != nil {
		Fatal("Failed to obtain passwd entry for %q", pamUser)
	}
	return u.Gid == fmt.Sprint(databoxGid)
}
开发者ID:scraperwiki,项目名称:cobalt,代码行数:7,代码来源:main.go

示例4: TestClientChownReadonly

func TestClientChownReadonly(t *testing.T) {
	sftp, cmd := testClient(t, READONLY, NO_DELAY)
	defer cmd.Wait()
	defer sftp.Close()

	usr, err := user.Current()
	if err != nil {
		t.Fatal(err)
	}
	chownto, err := user.Lookup("daemon") // seems common-ish...
	if err != nil {
		t.Fatal(err)
	}

	if usr.Uid != "0" {
		t.Log("must be root to run chown tests")
		t.Skip()
	}
	toUid, err := strconv.Atoi(chownto.Uid)
	if err != nil {
		t.Fatal(err)
	}
	toGid, err := strconv.Atoi(chownto.Gid)
	if err != nil {
		t.Fatal(err)
	}

	f, err := ioutil.TempFile("", "sftptest")
	if err != nil {
		t.Fatal(err)
	}
	if err := sftp.Chown(f.Name(), toUid, toGid); err == nil {
		t.Fatal("expected error")
	}
}
开发者ID:kothar,项目名称:sftp,代码行数:35,代码来源:client_integration_test.go

示例5: TestSetUserConfig_Present

func (s *FileTestSuite) TestSetUserConfig_Present(c *C) {
	args := haiconf.CommandArgs{
		"Path":   "/foo.txt",
		"Ensure": haiconf.ENSURE_PRESENT,
		"Mode":   "0777",
		"Owner":  "nobody",
		"Group":  "nogroup",
		"Source": "/foo",
	}

	err := s.f.SetUserConfig(args)
	c.Assert(err, IsNil)

	u, err := user.Lookup("nobody")
	c.Assert(err, IsNil)

	g, err := hacks.LookupSystemGroup("nogroup")
	c.Assert(err, IsNil)

	c.Assert(s.f.Path, Equals, args["Path"])
	c.Assert(s.f.Mode, Equals, os.FileMode(0777))
	c.Assert(s.f.Owner, DeepEquals, u)
	c.Assert(s.f.Group, DeepEquals, g)
	c.Assert(s.f.Source, DeepEquals, args["Source"])
	c.Assert(s.f.Ensure, Equals, args["Ensure"])
}
开发者ID:jeromer,项目名称:haiconf,代码行数:26,代码来源:file_test.go

示例6: startAPIService

func startAPIService(t *testing.T, ctx *testutils.RktRunCtx) *gexpect.ExpectSubprocess {
	noUidGid := false
	gid, err := common.LookupGid(common.RktGroup)
	if err != nil {
		t.Logf("no %q group, will run api service with root, ONLY DO THIS FOR TESTING!", common.RktGroup)
		noUidGid = true
	} else {
		if err := ctx.SetupDataDir(); err != nil {
			t.Fatalf("failed to setup data directory: %v", err)
		}
	}

	u, err := user.Lookup("nobody")
	if err != nil {
		t.Logf(`no "nobody" user, will run api service with root, ONLY DO THIS FOR TESTING!`)
		noUidGid = true
	}
	uid, err := strconv.Atoi(u.Uid)
	if err != nil {
		t.Fatalf(`failed to parse "nobody" UID: %v`, err)
	}

	t.Logf("Running rkt api service")
	apisvcCmd := fmt.Sprintf("%s api-service", ctx.Cmd())

	if noUidGid {
		return startRktAndCheckOutput(t, apisvcCmd, "API service running")
	}
	return startRktAsUidGidAndCheckOutput(t, apisvcCmd, "API service running", false, uid, gid)
}
开发者ID:intelsdi-x,项目名称:rkt,代码行数:30,代码来源:rkt_api_service_test.go

示例7: TestSetUserConfig_Complete

func (s *DirectoryTestSuite) TestSetUserConfig_Complete(c *C) {
	args := haiconf.CommandArgs{
		"Path":    "/foo",
		"Ensure":  haiconf.ENSURE_PRESENT,
		"Recurse": true,
		"Mode":    "0777",
		"Owner":   "nobody",
		"Group":   "nogroup",
	}

	err := s.d.SetUserConfig(args)
	c.Assert(err, IsNil)

	u, err := user.Lookup("nobody")
	c.Assert(err, IsNil)

	g, err := hacks.LookupSystemGroup("nogroup")
	c.Assert(err, IsNil)

	c.Assert(s.d.Path, Equals, args["Path"])
	c.Assert(s.d.Mode, Equals, os.FileMode(0777))
	c.Assert(s.d.Owner, DeepEquals, u)
	c.Assert(s.d.Group, DeepEquals, g)
	c.Assert(s.d.Recurse, Equals, args["Recurse"])
	c.Assert(s.d.Ensure, Equals, args["Ensure"])
}
开发者ID:jeromer,项目名称:haiconf,代码行数:26,代码来源:directory_test.go

示例8: TestSuiteLinuxGidMappings

func TestSuiteLinuxGidMappings() string {
	addTestUser()
	linuxSpec.Spec.Process.Args = []string{"/bin/bash", "-c", "cat /proc/1/gid_map"}
	//get uid&gid of test account
	testuser, _ := user.Lookup("uidgidtest")
	testuidInt, _ := strconv.ParseInt(testuser.Uid, 10, 32)
	testgidInt, _ := strconv.ParseInt(testuser.Uid, 10, 32)
	//change owner of rootfs
	gopath := os.Getenv("GOPATH")
	if gopath == "" {
		log.Fatalf("utils.setBind error GOPATH == nil")
	}
	rootfspath := gopath + "/src/github.com/huawei-openlab/oct/tools/runtimeValidator/rootfs"
	utils.SetRight(rootfspath, int32(testuidInt), int32(testgidInt))
	var uid specs.IDMapping = specs.IDMapping{
		HostID:      int32(testuidInt),
		ContainerID: 0,
		Size:        10,
	}
	var gid specs.IDMapping = specs.IDMapping{
		HostID:      int32(testgidInt),
		ContainerID: 0,
		Size:        10,
	}
	failinfo := "mapping from Host GID to Container GID failed"
	linuxSpec = setIDmappings(uid, gid)
	result, err := testIDmappings(&linuxSpec, true, failinfo)
	var testResult manager.TestResult
	testResult.Set("TestSuiteLinuxGidMappings", gid, err, result)
	cleanTestUser()
	return testResult.Marshal()

}
开发者ID:WeiZhang555,项目名称:oct,代码行数:33,代码来源:test_linuxuidgidmappings.go

示例9: Execute

// Execute ChownJob.
func (job *ChownJob) Execute() {
	defer job.finalize()
	// -1 means not change.
	uid := -1
	gid := -1
	if job.owner != "" {
		newUser, err := user.Lookup(job.owner)
		if err != nil {
			job.setError(err)
			return
		}
		uid, _ = strconv.Atoi(newUser.Uid)
	}

	if job.group != "" {
		cGroupName := C.CString(job.group)
		defer C.free(unsafe.Pointer(cGroupName))
		group := C.getgrnam(cGroupName)
		if group == nil {
			job.setError(errors.New("no such a group"))
			return
		}
		gid = int(group.gr_gid)
	}

	job.setError(os.Chown(job.file.GetPath(), uid, gid))
}
开发者ID:linuxdeepin,项目名称:deepin-file-manager-backend,代码行数:28,代码来源:chown_job.go

示例10: ExpandHomedir

// Expand '~'-based homedif from the given path
func ExpandHomedir(s string) (string, error) {
	const (
		slash = string(os.PathSeparator)
		re1   = "~%s"            // regex: /~\//
		re2   = "~([\\w\\-]+)%s" // regex: /~([\w\-]+)\//
	)
	var (
		err error
		re  *regexp.Regexp
		u   *user.User
		rv  string
	)

	if strings.HasPrefix(s, fmt.Sprintf(re1, slash)) {
		u, _ = user.Current()
		rv = fmt.Sprintf("%s", u.HomeDir+s[1:])
		err = nil
	} else if re = regexp.MustCompile(fmt.Sprintf(re2, slash)); re.MatchString(s) {
		uname := re.FindStringSubmatch(s)[0]
		uname = uname[1 : len(uname)-1]
		if u, _ = user.Lookup(uname); u == nil {
			rv = s
			err = nil
		} else {
			rv = u.HomeDir + slash + strings.Join(strings.Split(s, slash)[1:], slash)
			err = nil
		}
	} else if err != nil {
		rv = s
	} else {
		rv = s
		err = nil
	}
	return rv, err
}
开发者ID:xenolog,项目名称:janus,代码行数:36,代码来源:config.go

示例11: userpath

// userpath takes a path and resolves a leading "~" pattern to
// the current or specified user's home directory. Note that the
// path will not be converted to an absolute path if there is no
// leading "~" pattern.
func userpath(path string) (string, error) {
	if len(path) > 0 && path[0] == '~' {
		slashindex := strings.IndexRune(path, filepath.Separator)
		var username string
		if slashindex == -1 {
			username = path[1:]
		} else {
			username = path[1:slashindex]
		}

		var u *user.User
		var err error
		if username == "" {
			u, err = user.Current()
		} else {
			u, err = user.Lookup(username)
		}
		if err != nil {
			return "", err
		}

		if slashindex == -1 {
			path = u.HomeDir
		} else {
			path = filepath.Join(u.HomeDir, path[slashindex+1:])
		}
	}
	return path, nil
}
开发者ID:payco,项目名称:llgo,代码行数:33,代码来源:paths.go

示例12: User

func (opt *UserOption) User() (userinfo *user.User, err error) {
	nvs := strings.TrimSpace(opt.Value)
	if nvs == "" {
		// special case: empty string is the current euid.
		return nil, EmptyUserSet
	}
	// attempt to map this as a number first, in case a numeric UID
	// was provided.
	_, err = strconv.Atoi(nvs)
	if err != nil {
		switch err.(type) {
		case *strconv.NumError:
			// not a number.  do a user table lookup.
			userinfo, err = user.Lookup(nvs)
			if err != nil {
				return nil, err
			}
			return userinfo, nil
		default:
			return nil, err
		}
	}
	userinfo, err = user.LookupId(nvs)
	return userinfo, err
}
开发者ID:kuroneko,项目名称:configureit,代码行数:25,代码来源:user.go

示例13: main

func main() {
	var (
		u        *user.User
		err      error
		username string
		program  string
		command  []string
	)
	if len(os.Args[1:]) < 2 {
		fmt.Fprintf(os.Stderr, "Usage: %s USERNAME COMMAND [args...]\n", os.Args[0])
		os.Exit(1)
	}
	username = os.Args[1]
	program = os.Args[2]
	command = append(command, os.Args[3:]...)
	if u, err = user.Lookup(username); err != nil {
		abort(err)
	}
	if program, err = exec.LookPath(program); err != nil {
		abort(err)
	}
	if err = setupEnv(u); err != nil {
		abort(err)
	}
	fmt.Println("Found binary at", program)
	fmt.Println("Args: ", command)
	if err = syscall.Exec(program, command, os.Environ()); err != nil {
		abort(err)
	}
}
开发者ID:iancmcc,项目名称:setuser,代码行数:30,代码来源:setuser.go

示例14: SetFileUser

func SetFileUser(filename, username string, run bool) (bool, error) {
	userData, err := user.Lookup(username)
	if err != nil {
		return false, err
	}
	uid, err := strconv.Atoi(userData.Uid)
	if err != nil {
		return false, err
	}
	var stat syscall.Stat_t
	err = syscall.Stat(filename, &stat)
	if err != nil {
		return false, err
	}
	if int(stat.Uid) == uid {
		return false, nil
	}
	if run {
		err = os.Chown(filename, uid, int(stat.Gid))
		if err != nil {
			return false, err
		}
	}
	return true, nil
}
开发者ID:RegalSkeppet,项目名称:prov,代码行数:25,代码来源:file.go

示例15: DropPrivileges

func DropPrivileges(username string) error {
	userInfo, err := user.Lookup(username)
	if err != nil {
		return err
	}

	uid, err := strconv.Atoi(userInfo.Uid)
	if err != nil {
		return err
	}

	gid, err := strconv.Atoi(userInfo.Gid)
	if err != nil {
		return err
	}

	// TODO: should set secondary groups too
	err = syscall.Setgroups([]int{gid})
	if err != nil {
		return err
	}

	err = syscall.Setgid(gid)
	if err != nil {
		return err
	}

	err = syscall.Setuid(uid)
	if err != nil {
		return err
	}

	return nil
}
开发者ID:MrSpock,项目名称:hooktftpd,代码行数:34,代码来源:drop_privileges.go


注:本文中的os/user.Lookup函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。