Skip to content

Instantly share code, notes, and snippets.

@adrianlzt
Created April 22, 2021 17:18
Show Gist options
  • Select an option

  • Save adrianlzt/559635c2bd1877734501f90218645425 to your computer and use it in GitHub Desktop.

Select an option

Save adrianlzt/559635c2bd1877734501f90218645425 to your computer and use it in GitHub Desktop.
golang: execute command under different network namespace
/*
* 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))
}
@adrianlzt

Copy link
Copy Markdown
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment