本文整理汇总了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)
}
示例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
}
示例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)
}
示例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")
}
}
示例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"])
}
示例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)
}
示例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"])
}
示例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()
}
示例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))
}
示例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
}
示例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
}
示例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
}
示例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)
}
}
示例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
}
示例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
}