Skip to content

Commit 273c5c7

Browse files
committed
Escapeshellcmd
1 parent 8a4ccf3 commit 273c5c7

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

exec.go

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,17 @@ import (
55
"log"
66
"os"
77
"os/exec"
8+
"regexp"
9+
"strings"
810
)
911

12+
var rPatt *regexp.Regexp
13+
14+
15+
func init() {
16+
rPatt = regexp.MustCompile(`[^\w@%+=:,./-]`)
17+
}
18+
1019
// Exec - Start a command on system
1120
//
1221
// Original : https://www.php.net/manual/tr/function.exec.php
@@ -56,3 +65,33 @@ func Exit(of int) {
5665
func Die(of int) {
5766
os.Exit(of)
5867
}
68+
69+
// Escapeshellarg - Escape a string to be used as a shell argument
70+
//
71+
// Original: https://www.php.net/manual/en/function.escapeshellarg.php
72+
//
73+
func Escapeshellarg(s string) string {
74+
if len(s) == 0 {return "''"}
75+
76+
if rPatt.MatchString(s) {
77+
return "'" + strings.ReplaceAll(s, "'", "'\"'\"'") + "'"
78+
}
79+
80+
return s
81+
}
82+
83+
// Escapeshellcmd - Escape shell metacharacters
84+
//
85+
// Original: https://www.php.net/manual/en/function.escapeshellcmd.php
86+
//
87+
func Escapeshellcmd(s string) string {
88+
cmds := Explode(s, " ") // I know thats maybe not proper way...
89+
90+
z := make([]string, len(cmds))
91+
92+
for i ,s := range cmds {
93+
z[i] = Escapeshellarg(s)
94+
}
95+
96+
return Join(" ",z)
97+
}

0 commit comments

Comments
 (0)