Last active
November 24, 2020 11:33
-
-
Save mwindower/c0d28eda63f4a2310696680d98855fe0 to your computer and use it in GitHub Desktop.
Self replace binary in Golang
This file contains 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 ( | |
"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