Skip to content

Instantly share code, notes, and snippets.

@mwindower
Last active November 24, 2020 11:33
Show Gist options
  • Save mwindower/c0d28eda63f4a2310696680d98855fe0 to your computer and use it in GitHub Desktop.
Save mwindower/c0d28eda63f4a2310696680d98855fe0 to your computer and use it in GitHub Desktop.
Self replace binary in Golang
package main
import (
"io"
"io/ioutil"
"os"
)
const (
binaryToReplace = "./main"
newBinary = "/home/.../bin/test"
)
func main() {
newBin, err := os.Open(newBinary)
if err != nil {
panic(err)
}
err = replaceBinary(newBin)
if err != nil {
panic(err)
}
}
func replaceBinary(binaryReader io.ReadCloser) error {
filename, err := copyToTempFile(binaryReader)
if err != nil {
return err
}
if err = os.Rename(filename, binaryToReplace); err != nil {
return err
}
return nil
}
func copyToTempFile(binaryReader io.ReadCloser) (string, error) {
file, err := ioutil.TempFile("/var/tmp", "")
if err != nil {
return "", err
}
_, err = io.Copy(file, binaryReader)
if err != nil {
return "", err
}
defer binaryReader.Close()
err = os.Chmod(file.Name(), 0744)
if err != nil {
return "", err
}
return file.Name(), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment