从伪终端获取环境变量
我有一个程序,使用 https://github.com/creack/pty 创建伪终端。给定一个命令,它会创建一个文件对象,您可以在其中读取和写入,并将其用作标准输入和标准输出。
我使用 WebSocket 来读取和将命令写入程序。我已将其配置为根据我的选择从 root 用户以及当前用户的主目录运行。
初始化
cmd := exec.Command("/bin/sh", "env")
设置命令执行路径
cmd.Dir = "/var/root" // for system user
// (or)
cmd.Dir = "/Users/user_name" // for current user
使用 pty 启动命令。
ptmx, err := pty.Start(cmd) // ptmx is of type *os.File
这工作正常,但是当我尝试打印环境变量时,它不会显示该特定用户或根用户的所有相应环境变量。
有没有办法从 root 用户/当前用户的伪终端获取环境变量?
I have a program that uses https://github.com/creack/pty to create pseudo terminals. Given a command, it creates a file object where you can read and write and it will work as stdin and stdout.
I use a WebSocket to read & write commands to the program. I have configured it to run from the home directory of root user as well as current user based on my selection.
Initialise
cmd := exec.Command("/bin/sh", "env")
Set Command Execution path
cmd.Dir = "/var/root" // for system user
// (or)
cmd.Dir = "/Users/user_name" // for current user
Start the command with a pty.
ptmx, err := pty.Start(cmd) // ptmx is of type *os.File
This works fine but when I try to print environment variables, it will not show all respective environment variables for that particular user or root user.
Is there any way to get environment variables from pseudo-terminal for root user/current user?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您没有获得预期输出的原因是
env
不是 shell 脚本。在交互式提示符处尝试运行 Go 程序正在运行的命令。这是我看到的:尝试运行
/bin/sh -c env
。但是,由于您的命令不包含任何 shell 语法,并且除了执行env
二进制文件之外什么也不做,因此您根本不需要/bin/sh
。只需执行env
即可。另外,你似乎有一些误解。不存在“用户环境变量”这样的东西。同样,pty 没有环境变量。环境变量是每个进程私有的(pty 不是进程)。
确实,交互式 shell 可以通过在显示第一个提示之前自动读取各种 shell 配置文件(例如
~/.bashrc
)来设置环境变量,但我不认为这就是您所指的,因为您/bin/sh -c env
不会启动交互式 shell;即使它的 stdin 和 stdout 附加到 pty。The reason you're not getting the expected output is because
env
is not a shell script. At an interactive prompt try running the command your Go program is running. Here is what I see:Try running
/bin/sh -c env
instead. However, since your command does not contain any shell syntax and does nothing more than execute theenv
binary you don't need/bin/sh
at all. Just execenv
.Also, you seem to be under some misconceptions. There is no such thing as "user environment variables". Similarly, a pty does not have env vars. Environment variables are private to each process (and a pty is not a process).
It is true that interactive shells may set env vars by automatically reading various shell config files such as
~/.bashrc
before showing the first prompt but I don't think that's what you're referring to since your/bin/sh -c env
won't start an interactive shell; even though its stdin and stdout are attached to a pty.