源码
package main
import (
"fmt"
"log"
"os/exec"
"strings"
)
func main() {
// 定义要使用sudo执行的命令
cmd := exec.Command("sudo", "-S", "apt-get", "update")
// 将密码作为命令的标准输入
cmd.Stdin = strings.NewReader("123\n")
// 捕获命令的输出
output, err := cmd.CombinedOutput()
if err != nil {
log.Fatalf("执行命令时出错: %s", err)
}
// 输出命令的输出
fmt.Printf("%s\n", output)
}
123
是密码
效果
liumou@liumou-PC:~/LinuxData/git/golang/demo$ go run demo.go
获取:1 http://packages.microsoft.com/repos/code stable InRelease [10.4 kB]
获取:3 http://packages.microsoft.com/repos/code stable/main amd64 Packages [123 kB]
获取:4 http://packages.microsoft.com/repos/code stable/main arm64 Packages [124 kB]
获取:5 http://packages.microsoft.com/repos/code stable/main armhf Packages [124 kB]
获取:6 https://community-packages.deepin.com/deepin apricot InRelease [13.6 kB]
命中:7 https://community-packages.deepin.com/driver driver InRelease
获取:2 https://home-store-img.uniontech.com/221209121854126/appstore deepin InRelease [6,128 B]
命中:8 https://community-packages.deepin.com/printer eagle InRelease
命中:9 https://pro-driver-packages.uniontech.com eagle InRelease
获取:10 https://dl.google.com/linux/chrome/deb stable InRelease [1,811 B]
获取:11 https://community-packages.deepin.com/deepin apricot/main i386 Packages [15.2 MB]
获取:12 https://home-store-img.uniontech.com/221209121854126/appstore deepin/appstore i386 Packages [633 kB]
获取:13 https://home-store-img.uniontech.com/221209121854126/appstore deepin/appstore amd64 Packages [5,395 kB]
获取:14 https://community-packages.deepin.com/deepin apricot/main amd64 Packages [15.4 MB]
获取:15 https://community-packages.deepin.com/deepin apricot/non-free amd64 Packages [225 kB]
获取:16 https://community-packages.deepin.com/deepin apricot/non-free i386 Packages [184 kB]
获取:17 https://dl.google.com/linux/chrome/deb stable/main amd64 Packages [1,093 B]
正在读取软件包列表...
liumou@liumou-PC:~/LinuxData/git/golang/demo$