First, I already googled but only found examples where a compressed file (say a .tar.gz) is embedded into a shell script.
Basically if I have a C program (hello.c) that prints a string, say Hello World!.
I compile it to get an executable binary
gcc hello.c -o hello
Now I have a shell script testEmbed.sh
What I am asking is if it is possible to embed the binary (hello) inside the shell script so that when I run
./testEmbed.sh
it executes the binary to print Hello World!.
Clarification:
One alternative is that I compress the executable into an archive and then extract it when the script runs. What I am asking is if it is possible to run the program without that.
Up until now, I was trying the method here. But it does not work for me. I guess the author was using some other distribution on another architecture. So, basically this did not work for me. 😛
Also, if the workflow for a C program differs from a Java jar, I would like to know that too!
Yes, this can be done. It’s actually quite similar in concept to your linked article. The trick is to use
uuencodeto encode the binary into text format then tack it on to the end of your script.Your script is then written in such a way that it runs
uudecodeon itself to create a binary file, change the permissions then execute it.uuencodeanduudecodewere originally created for shifting binary content around on the precursor to the internet, which didn’t handles binary information that well. The conversion into text means that it can be shipped as a shell script as well. If, for some reason your distribution complains when you try to runuuencode, it probably means you have to install it. For example, on Debian Squeeze:will get the relevant executables for you. Here’s the process I went through. First create and compile your C program
hello.c:Then create a shell script
testEmbed.sh, which will decode itself:The first
rmstatement demonstrates that thehelloexecutable is being created anew by this script, not left hanging around from your compilation. Since you need the payload in the file as well, attach the encoded executable to the end of it:Afterwards, when you execute the script
testEmbed.sh, it extracts the executable and runs it.The reason this works is because
uudecodelooks for certain marker lines in its input (beginandend) which are put there byuuencode, so it only tries to decode the encoded program, not the entire script:There are other things you should probably worry about, such as the possibility that your program may require shared libraries that don’t exist on the target system, but the process above is basically what you need.
The process for a JAR file is very similar, except that the way you run it is different. It’s still a single file but you need to replace the line:
with something capable of running JAR files, such as: