dqy1265 2014-07-12 11:25
浏览 344
已采纳

使用Go使用参数运行sh / bash / python脚本

I've been stuck on this one a few days, I'm trying to run a bash script which runs off of the first argument (maybe I should give up all hope, haha)

Syntax for running the script can be assumed to be:

sudo bash script argument or since it has og+x it can be ran as just sudo script argument

In go I'm running it using the following:

package main

import (
    "os"
    "os/exec"
    "fmt"
)

func main() {
    c := exec.Command("/bin/bash", "script " + argument)
    if err := c.Run(); err != nil {
        fmt.Println("Error: ", err)
    }
    os.Exit(0)
}

I have had absolutely no luck, I've tried loads of other variations as well for this...

exec.Command("/bin/sh", "-c", "sudo script", argument)

exec.Command("/bin/sh", "-c", "sudo script " + argument) (my first try)

exec.Command("/bin/bash", "-c", "sudo script" + argument)

exec.Command("/bin/bash", "sudo script", argument)

exec.Command("/bin/bash sudo script" + argument)

Most of these I am met with '/bin/bash sudo ect' no such file or directory, or Error: exit status 1 I have even gone as far as to write a Python wrapper looking for an argument and executing the bash script with subprocess. To rule out the path to the script not being defined I have tried all of the above with a direct route to the script rather than script name.

For the sake of my remaining hair, what am I doing wrong here? How can I better diagnose this problem so that I can get more information rather than exit status 1?

  • 写回答

1条回答 默认 最新

  • duankan8739 2014-07-12 11:42
    关注

    You don't need to call bash/sh at all, simply pass each argument alone, also to get the error you have to capture the command's stderr, here's a working example:

    func main() {
        c := exec.Command("sudo", "ls", "/tmp")
        stderr := &bytes.Buffer{}
        stdout := &bytes.Buffer{}
        c.Stderr = stderr
        c.Stdout = stdout
        if err := c.Run(); err != nil {
            fmt.Println("Error: ", err, "|", stderr.String())
        } else {
            fmt.Println(stdout.String())
        }
        os.Exit(0)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 ubuntu系统下挂载磁盘上执行./提示权限不够
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型