美文网首页
Go 调用交互式shell

Go 调用交互式shell

作者: ShootHzj | 来源:发表于2021-12-12 18:04 被阅读0次

    本文的代码已上传到github

    交互式shell常用在输入密码的场景,为了防止密码泄露在cmdline中被ps -ef读取

    举个🌰

    #!/bin/bash
    
    read -s -p "Enter Password: "  pwd
    echo -e "\nYour password is: " $pwd
    

    go调用交互式shell代码样例如下

    func TestCallInteractiveShell(t *testing.T) {
        dir, err := os.Getwd()
        if err != nil {
            panic(err)
        }
        cmd := exec.Command("/bin/bash", dir+"/interactive_shell.sh")
        var stdout, stderr bytes.Buffer
        cmd.Stdout = &stdout
        cmd.Stderr = &stderr
        buffer := bytes.Buffer{}
        buffer.Write([]byte("ZhangJian"))
        cmd.Stdin = &buffer
        err = cmd.Run()
        if err != nil {
            panic(err)
        }
        outStr, errStr := string(stdout.Bytes()), string(stderr.Bytes())
        fmt.Println("output is ", outStr)
        fmt.Println("err output is ", errStr)
        fmt.Println("Execute Over")
    }
    

    输出结果

    === RUN   TestCallInteractiveShell
    output is  Your password is:  ZhangJian
    
    err output is  
    Execute Over
    --- PASS: TestCallInteractiveShell (0.00s)
    PASS
    

    相关文章

      网友评论

          本文标题:Go 调用交互式shell

          本文链接:https://www.haomeiwen.com/subject/jqorfrtx.html