Created
June 23, 2022 10:11
-
-
Save fengyfei/b6a6fa85825ef5af38a3889bb7570a53 to your computer and use it in GitHub Desktop.
[Go] Sudo execution
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"io" | |
"log" | |
"os/exec" | |
"strings" | |
"sync" | |
"time" | |
) | |
func main() { | |
output := bytes.Buffer{} | |
stderr := bytes.Buffer{} | |
process := exec.Command("sudo", "-S", "ls", "-la") | |
process.Stdout = &output | |
process.Stderr = &stderr | |
// process.Stdin = strings.NewReader("YOUR PASSWORD HERE") | |
stdin, err := process.StdinPipe() | |
if err != nil { | |
log.Fatal(err) | |
} | |
var wg sync.WaitGroup | |
done := make(chan struct{}, 1) | |
wg.Add(1) | |
go func() { | |
timer := time.NewTicker(time.Second) | |
for { | |
select { | |
case <-done: | |
log.Print("Finished:", output.String()) | |
wg.Done() | |
return | |
case <-timer.C: | |
log.Print("[Stderr]:", stderr.String(), "\n") | |
if strings.Contains(stderr.String(), "Password") { | |
io.WriteString(stdin, "YOUR PASSWORD HERE\n") | |
} | |
} | |
} | |
}() | |
if err := process.Start(); err != nil { | |
log.Fatal(err) | |
} | |
if err := process.Wait(); err != nil { | |
log.Print("Error:", err) | |
} | |
done <- struct{}{} | |
log.Print("Waiting for goroutine finish\n") | |
wg.Wait() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment