本文整理汇总了Golang中os.Getuid函数的典型用法代码示例。如果您正苦于以下问题:Golang Getuid函数的具体用法?Golang Getuid怎么用?Golang Getuid使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Getuid函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Attr
// Attr returns the attributes of a given node.
func (s *Node) Attr(ctx context.Context, a *fuse.Attr) error {
log.Debug("Node attr")
if s.cached == nil {
if err := s.loadData(); err != nil {
return fmt.Errorf("readonly: loadData() failed: %s", err)
}
}
switch s.cached.GetType() {
case ftpb.Data_Directory:
a.Mode = os.ModeDir | 0555
a.Uid = uint32(os.Getuid())
a.Gid = uint32(os.Getgid())
case ftpb.Data_File:
size := s.cached.GetFilesize()
a.Mode = 0444
a.Size = uint64(size)
a.Blocks = uint64(len(s.Nd.Links))
a.Uid = uint32(os.Getuid())
a.Gid = uint32(os.Getgid())
case ftpb.Data_Raw:
a.Mode = 0444
a.Size = uint64(len(s.cached.GetData()))
a.Blocks = uint64(len(s.Nd.Links))
a.Uid = uint32(os.Getuid())
a.Gid = uint32(os.Getgid())
case ftpb.Data_Symlink:
a.Mode = 0777 | os.ModeSymlink
a.Size = uint64(len(s.cached.GetData()))
a.Uid = uint32(os.Getuid())
a.Gid = uint32(os.Getgid())
default:
return fmt.Errorf("Invalid data type - %s", s.cached.GetType())
}
return nil
}
示例2: main
func main() {
flagUsername := flag.String("username", "nobody", "username for the unprivileged child")
isChild, r, w, _, err := privsep.MaybeBecomeChild()
if err != nil {
log.Fatalf("MaybeBecomeChild failed: %s", err)
}
who := "parent"
if isChild {
who = "child"
}
log.Printf("%s: pid=%d uid=%d euid=%d gid=%d egid=%d",
who, os.Getpid(), os.Getuid(), os.Geteuid(), os.Getgid(), os.Getegid())
if isChild {
child(r, w)
return
}
if os.Getuid() != 0 {
log.Print("Warning: this example only works when run as the root user")
}
_, r, w, err = privsep.CreateChild(*flagUsername, os.Args[0], nil, nil)
if err != nil {
log.Fatalf("CreateChild failed: %s", err)
}
parent(r, w)
}
示例3: TestSemStat
func TestSemStat(t *testing.T) {
semSetup(t)
defer semTeardown(t)
// EIDRM with a bad semset id
if _, err := (&SemaphoreSet{5, 2}).Stat(); err != syscall.EIDRM {
t.Error("semctl(IPC_STAT) on a made up semset id should fail")
}
info, err := ss.Stat()
if err != nil {
t.Fatal(err)
}
if info.Perms.OwnerUID != os.Getuid() {
t.Error("wrong owner uid", info.Perms.OwnerUID)
}
if info.Perms.CreatorUID != os.Getuid() {
t.Error("wrong creator uid", info.Perms.CreatorUID)
}
if info.Perms.Mode&0777 != 0600 {
t.Error("wrong mode", info.Perms.Mode)
}
if info.Count != 4 {
t.Error("wrong count", info.Count)
}
}
示例4: Auth
func (t *unixTransport) Auth() error {
cred := syscall.UnixCredentials(&syscall.Ucred{
Pid: int32(os.Getpid()),
Uid: uint32(os.Getuid()),
Gid: uint32(os.Getgid()),
})
_, _, err := t.WriteMsgUnix([]byte{0}, cred, nil)
if err != nil {
return err
}
if _, err := fmt.Fprintf(t, "AUTH EXTERNAL %x\r\n", fmt.Sprintf("%d", os.Getuid())); err != nil {
return err
}
var code, cookie string
if _, err := fmt.Fscanln(t, &code, &cookie); err != nil {
return err
}
fmt.Println(code, cookie)
if _, err := fmt.Fprintf(t, "BEGIN\r\n"); err != nil {
return err
}
return nil
}
示例5: TestLink
func TestLink(t *testing.T) {
ino := maggiefs.NewInode(0, maggiefs.FTYPE_REG, 0755, uint32(os.Getuid()), uint32(os.Getgid()))
id, err := testCluster.Names.AddInode(ino)
if err != nil {
panic(err)
}
ino.Inodeid = id
ino2 := maggiefs.NewInode(0, maggiefs.FTYPE_REG, 0755, uint32(os.Getuid()), uint32(os.Getgid()))
id, err = testCluster.Names.AddInode(ino)
if err != nil {
panic(err)
}
ino2.Inodeid = id
// test normal link
fmt.Println("linking")
err = testCluster.Names.Link(ino.Inodeid, ino2.Inodeid, "name", true)
if err != nil {
panic(err)
}
ino, err = testCluster.Names.GetInode(ino.Inodeid)
if err != nil {
panic(err)
}
if ino.Children["name"].Inodeid != ino2.Inodeid {
t.Fatalf("Didn't link properly!")
}
// test an unforced attempt to overwrite
// test overwriting forced
}
示例6: Test_l_File_Link2
// Test running 'ls -l' with a symlink 'b' pointing to a file 'a'
func Test_l_File_Link2(t *testing.T) {
setup_test_dir("l_File_Link2")
time_now := time.Now()
size := 13
path := "a"
_mkfile2(path, 0600, os.Getuid(), os.Getgid(), size, time_now)
_mklink(path, "b")
var output_buffer bytes.Buffer
args := []string{"-l", "--nocolor"}
ls_err := ls(&output_buffer, args, tw)
output := clean_output_buffer(output_buffer)
// remove the permissions string from each file listing
output_line_split := strings.Split(output, "\n")
output_noperms := ""
for _, l := range output_line_split {
output_line_split_noperms := strings.Split(l, " ")[1:]
output_line_noperms := strings.Join(output_line_split_noperms, " ")
if len(output_noperms) == 0 {
output_noperms = output_line_noperms
} else {
output_noperms = output_noperms + "\n" + output_line_noperms
}
}
var owner string
owner_lookup, err := user.LookupId(fmt.Sprintf("%d", os.Getuid()))
if err != nil {
owner = user_map[int(os.Getuid())]
} else {
owner = owner_lookup.Username
}
group := group_map[os.Getgid()]
expected := fmt.Sprintf(
"1 %s %s %d %s %02d %02d:%02d a\n1 %s %s 1 %s %02d %02d:%02d b -> %s",
owner,
group,
size,
time_now.Month().String()[0:3],
time_now.Day(),
time_now.Hour(),
time_now.Minute(),
owner,
group,
time_now.Month().String()[0:3],
time_now.Day(),
time_now.Hour(),
time_now.Minute(),
path)
check_output(t, output_noperms, expected)
check_error_nil(t, ls_err)
}
示例7: main
func main() {
flagUsername := flag.String("username", "nobody", "username for the unprivileged child")
isChild, _, _, files, err := privsep.MaybeBecomeChild()
if err != nil {
log.Fatalf("MaybeBecomeChild failed: %s", err)
}
who := "parent"
if isChild {
who = "child"
}
log.Printf("%s: pid=%d uid=%d euid=%d gid=%d egid=%d",
who, os.Getpid(), os.Getuid(), os.Geteuid(), os.Getgid(), os.Getegid())
if isChild {
if len(files) < 1 {
log.Fatalf("no extra files: %v", files)
}
l, err := net.FileListener(files[0])
if err != nil {
log.Fatalf("FileListener: %s", err)
}
child(l)
return
}
if os.Getuid() != 0 {
log.Print("Warning: this example only works when run as the root user")
}
addr := "localhost:1111"
laddr, err := net.ResolveTCPAddr("tcp", addr)
if err != nil {
log.Fatalf("resolve %s: %s", addr, err)
}
l, err := net.ListenTCP("tcp", laddr)
if err != nil {
log.Fatalf("listen %s: %s", laddr, err)
}
sock, err := l.File()
if err != nil {
log.Fatalf("fd: %s", err)
}
proc, _, _, err := privsep.CreateChild(*flagUsername, os.Args[0], nil, []*os.File{sock})
if err != nil {
log.Fatalf("CreateChild failed: %s", err)
}
sock.Close()
// tidy up so child doesn't run forever
defer proc.Kill()
parent(laddr)
}
示例8: TestCloneNEWUSERAndRemapNoRootSetgroupsEnableSetgroups
func TestCloneNEWUSERAndRemapNoRootSetgroupsEnableSetgroups(t *testing.T) {
if os.Getuid() == 0 {
t.Skip("skipping unprivileged user only test")
}
cmd := whoamiCmd(t, os.Getuid(), os.Getgid(), true)
err := cmd.Run()
if err == nil {
t.Skip("probably old kernel without security fix")
}
if !os.IsPermission(err) {
t.Fatalf("Unprivileged gid_map rewriting with GidMappingsEnableSetgroups must fail")
}
}
示例9: Test_LS_COLORS_orphan_link
// Test LS_COLORS with an orphan link
func Test_LS_COLORS_orphan_link(t *testing.T) {
setup_test_dir("LS_COLORS_orphan_link")
time_now := time.Now()
_mkfile2("a", 0600, os.Getuid(), os.Getgid(), 8, time_now)
_mklink("a", "b")
_rm("a")
os.Setenv("LS_COLORS", default_LS_COLORS)
var output_buffer bytes.Buffer
args := []string{"-l"}
ls_err := ls(&output_buffer, args, tw)
output := clean_output_buffer(output_buffer)
// remove the permissions string from the output
output_noperms := strings.Join(strings.Split(output, " ")[1:], " ")
var owner string
owner_lookup, err := user.LookupId(fmt.Sprintf("%d", os.Getuid()))
if err != nil {
owner = user_map[int(os.Getuid())]
} else {
owner = owner_lookup.Username
}
group := group_map[os.Getgid()]
// link info
link_info, err := os.Lstat("b")
if err != nil {
t.Fatalf("error checking the symlink")
}
expected := fmt.Sprintf("1 %s %s %d %s %02d %02d:%02d %sb%s -> %sa%s",
owner,
group,
link_info.Size(),
time_now.Month().String()[0:3],
time_now.Day(),
time_now.Hour(),
time_now.Minute(),
"\x1b[40;31;01m",
"\x1b[0m",
"\x1b[01;05;37;41m",
"\x1b[0m")
check_output(t, output_noperms, expected)
check_error_nil(t, ls_err)
}
示例10: 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())
}
示例11: TestRawConnUnicastSocketOptions
func TestRawConnUnicastSocketOptions(t *testing.T) {
switch runtime.GOOS {
case "plan9":
t.Skipf("not supported on %q", runtime.GOOS)
}
if os.Getuid() != 0 {
t.Skip("must be root")
}
ifi := loopbackInterface()
if ifi == nil {
t.Skipf("not available on %q", runtime.GOOS)
}
c, err := net.ListenPacket("ip4:icmp", "127.0.0.1")
if err != nil {
t.Fatalf("net.ListenPacket failed: %v", err)
}
defer c.Close()
r, err := ipv4.NewRawConn(c)
if err != nil {
t.Fatalf("ipv4.NewRawConn failed: %v", err)
}
testUnicastSocketOptions(t, r)
}
示例12: populateAttr
// populateAttr should only be called once n.ss is known to be set and
// non-nil
func (n *node) populateAttr() error {
ss := n.ss
n.attr.Mode = ss.FileMode()
if n.fs.IgnoreOwners {
n.attr.Uid = uint32(os.Getuid())
n.attr.Gid = uint32(os.Getgid())
executeBit := n.attr.Mode & 0100
n.attr.Mode = (n.attr.Mode ^ n.attr.Mode.Perm()) & 0400 & executeBit
} else {
n.attr.Uid = uint32(ss.MapUid())
n.attr.Gid = uint32(ss.MapGid())
}
// TODO: inode?
n.attr.Mtime = ss.ModTime()
switch ss.Type {
case "file":
n.attr.Size = ss.SumPartsSize()
n.attr.Blocks = 0 // TODO: set?
case "directory":
// Nothing special? Just prevent default case.
case "symlink":
// Nothing special? Just prevent default case.
default:
log.Printf("unknown attr ss.Type %q in populateAttr", ss.Type)
}
return nil
}
示例13: TestSetICMPFilter
func TestSetICMPFilter(t *testing.T) {
switch runtime.GOOS {
case "plan9", "windows":
t.Skipf("not supported on %q", runtime.GOOS)
}
if !supportsIPv6 {
t.Skip("ipv6 is not supported")
}
if os.Getuid() != 0 {
t.Skip("must be root")
}
c, err := net.ListenPacket("ip6:ipv6-icmp", "::1")
if err != nil {
t.Fatalf("net.ListenPacket failed: %v", err)
}
defer c.Close()
p := ipv6.NewPacketConn(c)
var f ipv6.ICMPFilter
f.SetAll(true)
f.Set(ipv6.ICMPTypeEchoRequest, false)
f.Set(ipv6.ICMPTypeEchoReply, false)
if err := p.SetICMPFilter(&f); err != nil {
t.Fatalf("ipv6.PacketConn.SetICMPFilter failed: %v", err)
}
kf, err := p.ICMPFilter()
if err != nil {
t.Fatalf("ipv6.PacketConn.ICMPFilter failed: %v", err)
}
if !reflect.DeepEqual(kf, &f) {
t.Fatalf("got unexpected filter %#v; expected %#v", kf, f)
}
}
示例14: TestMulticastListener
// TestMulticastListener tests both single and double listen to a test
// listener with same address family, same group address and same port.
func TestMulticastListener(t *testing.T) {
switch runtime.GOOS {
case "netbsd", "openbsd", "plan9", "windows":
t.Logf("skipping test on %q", runtime.GOOS)
return
case "linux":
if runtime.GOARCH == "arm" || runtime.GOARCH == "alpha" {
t.Logf("skipping test on %q/%q", runtime.GOOS, runtime.GOARCH)
return
}
}
for _, tt := range multicastListenerTests {
if tt.ipv6 && (!*testIPv6 || !supportsIPv6 || os.Getuid() != 0) {
continue
}
ifi, err := availMulticastInterface(t, tt.flags)
if err != nil {
continue
}
c1, err := ListenMulticastUDP(tt.net, ifi, tt.gaddr)
if err != nil {
t.Fatalf("First ListenMulticastUDP failed: %v", err)
}
checkMulticastListener(t, err, c1, tt.gaddr)
c2, err := ListenMulticastUDP(tt.net, ifi, tt.gaddr)
if err != nil {
t.Fatalf("Second ListenMulticastUDP failed: %v", err)
}
checkMulticastListener(t, err, c2, tt.gaddr)
c2.Close()
c1.Close()
}
}
示例15: initConnection
func (c *Conn) initConnection() error {
var err error
c.sysconn, err = dbus.SystemBusPrivate()
if err != nil {
return err
}
// Only use EXTERNAL method, and hardcode the uid (not username)
// to avoid a username lookup (which requires a dynamically linked
// libc)
methods := []dbus.Auth{dbus.AuthExternal(strconv.Itoa(os.Getuid()))}
err = c.sysconn.Auth(methods)
if err != nil {
c.sysconn.Close()
return err
}
err = c.sysconn.Hello()
if err != nil {
c.sysconn.Close()
return err
}
c.sysobj = c.sysconn.Object("org.freedesktop.systemd1", dbus.ObjectPath("/org/freedesktop/systemd1"))
// Setup the listeners on jobs so that we can get completions
c.sysconn.BusObject().Call("org.freedesktop.DBus.AddMatch", 0,
"type='signal', interface='org.freedesktop.systemd1.Manager', member='JobRemoved'")
c.initSubscription()
c.initDispatch()
return nil
}