Golang exec.command

From UVOO Tech Wiki
Revision as of 04:43, 16 November 2020 by Busk (talk | contribs)
Jump to navigation Jump to search

package main

import (

   "fmt"
   "os/exec"
   "os"
   "strings"
   "runtime"
   "regexp"
   //match, _ := regexp.MatchString("p([a-z]+)ch", "peach")

)

func checkSubstrings(str string, subs ...string) (bool, int) {

matches := 0
isCompleteMatch := true

fmt.Printf("String: \"%s\", Substrings: %s\n", str, subs)

for _, sub := range subs {
    if strings.Contains(str, sub) {
        matches += 1
    } else {
        isCompleteMatch = false
    }
}

return isCompleteMatch, matches

}

func cmd_filter(name string, match_list []string){

   allow := false
   for k, v := range match_list {
       fmt.Println("At index", k, "value is", v)
       match, _ := regexp.MatchString(v, name)
       if match == true {
           allow = true
           break
       }
   } 
   if allow != true {
       fmt.Printf("E: Command %v is %v in shellcmd not allowed\n", name, allow)
       os.Exit(1)
   }

}

func shell_cmd(name string, args []string) {

   cmd := exec.Command(name, args...)
   out, err := cmd.Output()
   if err != nil {
       fmt.Println(err)
   }
   fmt.Printf(string(out))

}

func shellcmd() {

   system_os := runtime.GOOS
   if system_os == "linux" {
       name := os.Args[2]
       args := os.Args[3:]
       match_list := []string{"Get", "Fet"}
       cmd_filter(name, match_list)
       shell_cmd(name, args)
   }else if system_os == "windows" {
       if len(os.Args) < 3 {
           fmt.Printf("Usage: %v  \n", os.Args[0])
           fmt.Printf("Example: %v ls -lhat\n", os.Args[0])
           os.Exit(3)
       }
       var name string = "powershell.exe"
       match_list := []string{"Get", "Fet"}
       args := os.Args[2:]
       s := os.Args[2]
       fmt.Println(string(s))
       cmd_filter(s, match_list)
       shell_cmd(name, args)
   }else{
       fmt.Printf("OS %v not supported.\n", system_os)
   }

}

func main() {

   if len(os.Args) < 2 {
       fmt.Printf("Usage: %v \n", os.Args[0])
       fmt.Printf("Example: %v shellcmd ls -lhat\n", os.Args[0])
       os.Exit(3)
   }
   function := os.Args[1]
   if function == "shellcmd" {
       shellcmd()
   }else{
       fmt.Printf("E: Unsupported function %v\n", function)
   }

}