About "sudo go run main.go"

huangapple go评论129阅读模式
英文:

About "sudo go run main.go"

问题

我在我的Ubuntu 16.04上使用Go语言,并设置了GOPATHGOROOT,并成功运行了简单的代码。

现在我想使用"gopacket"来捕获网络数据包,但它需要sudo/root权限。我执行了命令:sudo go run main.go,但是它报错:

"exec: go: 在$PATH中找不到可执行文件"

我在Google上搜索了一下,并编辑了文件/etc/sudoers,将行"Defaults env_reset"改为"Defaults !env_reset",但是没有起作用...

你能帮助我吗?

英文:

I use Go in my Ubuntu 16.04, and I set GOPATH, GOROOT and run simple code successfully.

Now I want to capture network packet by "gopacket", but it needs sudo /root permission. I excute command: sudo go run main.go, it echo error:

> "exec: go: excutable file not found in $PATH"

I googled it and I edit file /etc/sudoders and change line "Defaults env_reset" to "Defaults !env_reset", but it not work...

Can you help me?

答案1

得分: 12

您的根用户的环境变量未设置。请不要尝试运行sudo go run ...,而是在没有sudo的情况下构建二进制文件,例如go buildgo install,然后使用sudo执行二进制文件。

假设您在main.go所在的文件夹中,假设它被称为mycapt

go build
sudo ./mycapt

或者:

go install
sudo $GOPATH/bin/mycapt
英文:

Your environment variables are not set for your root user. Don't try to run sudo go run ..., instead build the binary without sudo, e.g. go build or go install, and then execute the binary with sudo.

Let's say you're in the folder of main.go, assumed it's called mycapt:

go build
sudo ./mycapt

Or:

go install
sudo $GOPATH/bin/mycapt

答案2

得分: 8

sudo -E go run main.go 可能适用于你。

以下是关于 -E 选项的说明,来自 man sudo

  • -E, --preserve-env
    表示用户希望保留其现有的环境变量。如果用户没有权限保留环境,则安全策略可能会返回错误。
英文:

sudo -E go run main.go may work for you.

Here is what you can get about -E option from man sudo

-E, --preserve-env
   Indicates to the security policy that the user wishes to preserve
   their existing environment variables. The security policy may return
   an error if the user does not have permission to preserve the environment.

huangapple
  • 本文由 发表于 2016年11月2日 15:24:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/40374434.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定