I was facing a similar situation as I was trying to brute force a canary in a ctf pwn challenge. Your code exploit looks good buts it is missing a few things. You should make the process connection,p, also global. Don't forget to close the processes before the next iterations so that you don't get an OSError number 24.