通过另一个用户下的os / exec运行外部命令 [英] Running external commands through os/exec under another user

查看:443
本文介绍了通过另一个用户下的os / exec运行外部命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 os / exec 包,我想代表另一个用户在* nix OS上运行一个外部命令(当然,在root用户下运行进程具有su权限的另一个用户)

Using the os/exec package, I want to run an external command on a *nix OS, on behalf of another user (of course go process run under root user of another user with su privileges)

我想避免使用su或bash命令并纯粹使用go。

I want avoid "su" or "bash" commands and make it purely with go.

我使用 syscall.Setuid 做了一个方法,但这会将用户更改为主项目,我只需要将用户更改为外部子进程:

I made an approach using syscall.Setuid but this will change the user to the main project, I just need change the user to the external child process:

func (self *Command) LoseTo(username string) {
   u, err := user.Lookup(username)
   if err != nil {
      fmt.Printf("%v", err)
   }

   uid, err := strconv.Atoi(u.Uid)
   if err := syscall.Setuid(uid); err != nil {
      fmt.Printf("%v", err)
   }
}


推荐答案

您可以将一个syscall.Credential结构添加到Cmd.SysProcAttr中

You can add a syscall.Credential struct to Cmd.SysProcAttr

cmd := exec.Command(command, args...)
cmd.SysProcAttr = &syscall.SysProcAttr{}
cmd.SysProcAttr.Credential = &syscall.Credential{Uid: uid, Gid: gid}

这篇关于通过另一个用户下的os / exec运行外部命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆