go - golang linux在exec的帮助下添加用户
问题描述
我想使用 golang exec 功能将用户添加到我的服务器,但它不起作用我尝试了多种方法,但找不到有效的解决方案。是不是因为这个?“$(openssl passwd -1 测试)”
这是我的代码
cmd := exec.Command("sudo", "useradd -p", "$(openssl passwd -1 Test)", "Test1234")
b, err := cmd.CombinedOutput()
if err != nil {
fmt.Println(err)
}
fmt.Printf("%s\n", b)
解决方案
exec.Command
直接运行可执行文件。每个字符串都是一个文字参数。在您的示例中,sudo
是程序,您useradd -p
作为第一个参数传递,然后$(openssl passwd -1 Test)
作为第二个参数传递,依此类推。
useradd -p
是它自己的命令,并且不能作为单个字符串参数工作。
$(openssl passwd -1 Test)
是 bash(或其他 shell)特定的语法,在exec.Command
.
您实际上是在尝试运行三个可执行文件 - sudo
、useradd
和openssl
. 您可以在单独的exec.Command
调用中运行每个可执行文件,也可以直接运行 shell。
cmd := exec.Command("openssl", "passwd", "-1", "Test")
passwordBytes, err := cmd.CombinedOutput()
if err != nil {
panic(err)
}
// remove whitespace (possibly a trailing newline)
password := strings.TrimSpace(string(passwordBytes))
cmd = exec.Command("useradd", "-p", password, "Test1234")
b, err := cmd.CombinedOutput()
if err != nil {
fmt.Println(err)
}
fmt.Printf("%s\n", b)
(我建议不要sudo
直接在你的 go 代码中运行,因为你正在运行的程序应该直接管理权限。)
要直接运行 shell 以使用$(...)
子命令语法,请参阅https://stackoverflow.com/a/24095983/2178159。
推荐阅读
- tcp - 如何监控两个端点中间的简单双向 TCP 套接字流量(Telnet)?
- r - 通过 rmardown 中的循环创建代码片段
- javascript - 替换ul列表子元素
- ios - ExpoCLI-IOS 无法连接到服务器
- apache-calcite - Calcite SqlParser 在使用 MYSQL_5 一致性的 CREATE TABLE 语句中的“int(11)”数据类型规范上失败
- python - 如何在 python 中使用 time.nist.gov 获取东部标准时间
- haskell - 带数字的列表,其数字只有 2、4、6
- bash - 在bash中打印目录的文件名时出错
- node.js - 使用月光在数组中增加对象时遇到问题
- sql - 确定最接近另一个日期值的日期