我如何在python中的telnet会话上发送超过2个参数?

时间:2016-12-13 11:17:58

标签: python networking telnet

我有两个包含用户名和密码的列表。我想通过迭代两个压缩列表来检查哪一个是正确的,但它不起作用。 以下是追溯

Traceback (most recent call last):
File "C:\Users\mohamed\Downloads\second_PassWD_Test.py", line 27, in <module>
mme=tn.write(j,i)
TypeError: write() takes exactly 2 arguments (3 given)

以下是抛出异常的代码。

import telnetlib
import re
HOST = "192.168.1.1"
USER =  ["admin\n","admin\n","admin"]
PASS = ["cpe#","1234"," "]

try:
  tn = telnetlib.Telnet(HOST)
except:
print "Oops! there is a connection error"
frist_log = tn.read_until(":")
 if "log" in frist_log:
while 1:
    for i,j in zip(USER,PASS):
         tn.write(j,i)
    break

1 个答案:

答案 0 :(得分:0)

Telnet.write(buffer)首先只接受两个参数是telnet对象,另一个是发送到会话的缓冲区,因此您的解决方案将抛出异常。解决问题的一种方法是使用expect api的except脚本,并使用预期输出列表,如下面的示例所示

USER =  ["admin\n","admin\n","admin"]
PASS = ["cpe#","1234"," "]
prompt = "#"    ## or your system prompt 
tn = telnetlib.Telnet(HOST)
first_log = tn.read_until(":")
for user,password in zip(USER,PASS):
    try:
        tn.write(user)
        tn.expect([":"],timeout = 3) # 3 second timeout for password prompt
        tn.write(password+"\n")
        index,obj,string = tn.expect([":",prompt],timeout = 3)
        found = string.find(prompt)
        if found >= 0:
            break # found the username password match break 
        ###else continue for next user/password match    
    except:
        print "exception",sys.exc_info()[0]