dongpo0409 2019-03-18 13:50
浏览 31
已采纳

如何执行命令行

I am trying to execute two commands:

  • sudo ip link set can0 type can bitrate 500000
  • sudo ip link set can type can restart-ms 1000

here is my code:

package main

import (
    "log"
    "os"
    "os/exec"
)

func main(/*in string*/)/*(out bool)*/ {

        in :="setup"

    switch in {

    case "setup":
        bringUp()
        setRestart()
        log.Println("can0 is brought up")
        //return true

    case "restart":
        setRestart()
        log.Println("can0 is restarted")
        //return true

    default:
        log.Println("System cannot be brought up, contact administrator")
        //return false
    }
}


func bringUp (){
    cmd := exec.Command("sh", "-c", "sudo ip link set can0 type can bitrate 500000")

    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr

    err := cmd.Run()

    if err != nil {
        log.Fatal(err)
    }
}

func setRestart(){
    cmd:= exec.Command("sh", "-c", "sudo ip link set can type can restart-ms 10000")

    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr

    err := cmd.Run()

    if err != nil{
        log.Fatal(err)
    }
}

Whenever I execute it goes in to "setup" case and starts executing the bringUp function but it can never finish executing and I can't understand why. I am working on a raspberry pi.

  • 写回答

1条回答 默认 最新

  • dqd22496 2019-03-18 14:20
    关注

    Your go code looks correct. The problem lies with sudo, I believe. I replaced your commands with benign commands like sudo touch /tmp/bringUp-executed etc. The code did prompted for my sudo password - but once inputed - completed without issue.

    Are you running your go-executable in a headless fashion? And thus has no access to the console for password input? I would suggest creating wrapper scripts for your any root-level tasks and give them password-less sudoer privileges as outlined here.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)