我正在尝试从我的容器中运行一些 kubectl 命令。package mainimport ( "fmt" "os/exec") op, err := GetPods("test-containers", "qa") if err != nil { fmt.Printf("\nError: %v", err) } fmt.Printf(op)func GetPods(name, namespace string) (podName string, err error) { fmt.Println("Get pod names ....") cmd := "kubectl get pods -n " + namespace + " -o wide | grep " + name + " | awk '{print $1}' " cmnd, err := exec.Command("sh", "-c", cmd).Output() if err != nil { fmt.Println("Failed to find pod name." + string(cmnd)) } podName = string(cmnd) return}我的多级 Dockerfile 基于 Alpine3.6 并安装了 kubectl 二进制文件。FROM alpine:3.6RUN apk add --update curl wget ca-certificates unzip python py-pip openssl bash && \ apk --update add openssh-client && \ apk --update add --virtual build-dependencies python-dev libffi-dev openssl-dev build-base && \ apk add --no-cache --upgrade bash && \ pip install --upgrade pip cffi && \ pip install awscli && \ wget https://storage.googleapis.com/kubernetes-release/release/v1.15.1/bin/linux/amd64/kubectl && \ chmod u+x kubectl && mv kubectl /bin/kubectl && \ apk del build-dependencies && \ rm -rf /var/cache/apk/*ENV HOME=/go/app/WORKDIR /go/appCOPY --from=go-container-build /go/app/ .ENTRYPOINT ["bash"]当我将容器作为 pod 运行并尝试执行命令时;我总是遇到以下错误:cmd: kubectl -n qa get pods -o wide | grep test-containers | awk '{print $1}'Failed to find pod name.exit status 2/bin/sh: illegal option -我也尝试过使用 os.exec.Command() exec.Command("/bin/sh", "-c", cmd),exec.Command("/bin/bash", "-c", cmd)但我遇到了类似的错误。Failed to find pod name.exit status 2/bin/sh: illegal option -我也直接试过cmnd := exec.Command(cmd);但我得到了错误:Failed to find pod name.fork/exec kubectl -n qa get pods -o wide | grep test-containers | awk '{print $1}':executable file not found in $PATH我已经在容器中安装了 bash,当我直接在容器 shell 上运行命令时,我总是得到输出。
1 回答
偶然的你
TA贡献1841条经验 获得超3个赞
/bin/sh: 非法选项 -
是因为-carg 解析器将其解释为/bin/sh "- "- 具有讽刺意味的是(?)您的golang代码段是正确的,但是您粘贴的代码部分和问题的症结显示了错误的语法
无需涉及busybox或其他任何东西,就可以轻松地重现这一点
package main
import (
"fmt"
"os/exec"
)
func main() {
// c, err := exec.Command("/bin/sh", "-c", "echo -n hello | grep lo").Output()
c, err := exec.Command("/bin/sh", "-c ", "echo -n hello | grep lo").Output()
if err != nil {
ee := err.(*exec.ExitError)
panic(fmt.Errorf("c is %q and err is %q and stderr is %q", string(c), err, string(ee.Stderr)))
}
fmt.Println("OK")
}
结果,panic: c is "" and err is "exit status 2" and stderr is "/bin/sh: - : invalid option\n如果交换注释行,它会打印OK
- 1 回答
- 0 关注
- 187 浏览
添加回答
举报
0/150
提交
取消