Created
April 22, 2021 17:18
-
-
Save adrianlzt/559635c2bd1877734501f90218645425 to your computer and use it in GitHub Desktop.
golang: execute command under different network namespace
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
| /* | |
| * Execute a command under a different network namespace | |
| */ | |
| package main | |
| import ( | |
| "fmt" | |
| "io/ioutil" | |
| "log" | |
| "os/exec" | |
| "github.com/vishvananda/netns" | |
| ) | |
| func main() { | |
| pid := 1302916 | |
| ns, err := netns.GetFromPid(pid) | |
| if err != nil { | |
| log.Fatal(err) | |
| } | |
| err = netns.Setns(ns, netns.CLONE_NEWNET) | |
| if err != nil { | |
| log.Fatal(err) | |
| } | |
| cmd := exec.Command("ss", "-atn") | |
| stdout, err := cmd.StdoutPipe() | |
| if err != nil { | |
| log.Fatal(err) | |
| } | |
| if err := cmd.Start(); err != nil { | |
| log.Fatal(err) | |
| } | |
| out, err := ioutil.ReadAll(stdout) | |
| if err != nil { | |
| return | |
| } | |
| if err := cmd.Wait(); err != nil { | |
| log.Fatal(err) | |
| } | |
| fmt.Printf("%s", string(out)) | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm not sure if that will be possible. You can try using goroutines but I guess the change of NS apply to the whole process.