Dontrustme recently wrote a tutorial on infecting PE files. Works great, but there's a small problem - the main program doesn't start until the payload finishes. This is significant if your payload is, for example, a shell. The program will most likely never start!
The solution is to start your shellcode in a new thread. This way, the payload and the executable will run concurrently.
Here's a link to dtm's program rewritten in python with threading added. Do note however, that this sometimes fails and the infected program crashes upon starting. Stick to infecting small programs.
Here we have a code cave in putty.exe:
Let's infect it:
Our shellcode is inside the cave:
infected_putty.exe starts up fine:
Let's telnet to port 8888...
Love and waffles,