使用Golang与Sudosh

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

Using Sudosh with Golang

问题

我的程序的目的是执行一些任务,然后在最后以一个用户的身份进行 sudosh。

然而,当我用 Go 运行时,我得到了 sudosh: couldn't get your controlling terminal 的错误。

这是因为 sudosh 正在寻找一个控制终端,但找不到吗?在 Go 中是否可以实现这个功能?我正在将一个 Python 脚本转换为这个 Go 程序,在 Python 中它可以正常工作。

import (
    "github.com/codeskyblue/go-sh"
    "fmt"
    "os"
)
c, _ := sh.Command("sudo", "sudosh", "bob").Output()
fmt.Println(c)
os.Exit(0)

修复方法

import "os/exec"

func sudosh(name string) {
    c := exec.Command("/bin/sh", "-c", "sudo /path/to/sudosh " + name)
    c.Stdin = os.Stdin
    c.Stderr = os.Stderr
    c.Stdout = os.Stdout
    o := c.Run()
    o=o
}
英文:

my programs purpose is to do some tasks and then sudosh as a user all the way at the end.

However when running this with Go I get the sudosh: couldn't get your controlling terminal.

Is this because sudosh is looking for a controlling terminal and can't find it? Is this possible to do with Go? I am converting a Python script over to this Go program and it worked fine in Python.

import (
    "github.com/codeskyblue/go-sh"
    "fmt"
    "os"
)
c, _ := sh.Command("sudo", "sudosh", "bob").Output()
fmt.Println(c)
os.Exit(0)

> sudosh: couldn't get your controlling terminal.

The Fix

import "os/exec"

func sudosh(name string) {
    c := exec.Command("/bin/sh", "-c", "sudo /path/to/sudosh " + name)
    c.Stdin = os.Stdin
    c.Stderr = os.Stderr
    c.Stdout = os.Stdout
    o := c.Run()
    o=o
}

答案1

得分: 1

sudo2sh source显示它正在尝试调用ttyname,在go-sh.Command调用exec.Command(cmd, args...)的上下文中可能无法工作。

您可以通过直接调用ttyname进行测试,或者尝试实现一个TTYname()函数,就像这个线程中所示。
您还可以检查go-termutilisatty函数来调试此问题(如此答案中所示)。

底线是:如果在exec.Command会话中ttyname失败,sudosh将始终返回该错误消息。

英文:

sudo2sh source shows that it is trying to call ttyname, which might not work in the context of a go-sh.Command calling exec.Command(cmd, args...).

You can test by calling ttyname directly, or by trying and implement a TTYname() function as in this thread.
You can also check the isatty function of go-termutil to debug the issue (as in this answer).

The bottom line is: if ttyname fails in a exec.Command session, sudosh will always return that error message.

huangapple
  • 本文由 发表于 2014年9月9日 00:51:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/25729235.html
匿名

发表评论

匿名网友

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

确定