# -*- coding: gb2312 -*-
'''
Created on 2012-8-9
python Version is 2.4
@author: TyBo
'''
import string, telnetlib,time
def telnetcmd(host,myuid,mypwd,command_prompt,mycommand,**kw):
mycmdtimeout=kw.get('timeout', 600)
mytelnet=telnetlib.Telnet()
mytelnet.open(host, 23)
try:
try:
mytelnet.write("\n")
login_prompt="login:"
response=mytelnet.read_until(login_prompt, 5)
if string.count(response,login_prompt):
print "【Waiting Login Success: 】\n"# , response
else:
print "【Waiting Login Error: 】\n"# , response
return 0
time.sleep(5) #需设置适当延时,否则报错
mytelnet.write("%s\n" % myuid)
password_prompt="Password:"
response=mytelnet.read_until(password_prompt,10)
if string.count(response,password_prompt):
print "【Waiting PassWord Success: 】\n"# , response
else:
print "【Waiting Password Error: 】\n"# , response
return 0
time.sleep(5) #需设置适当延时,否则报错
mytelnet.write("%s\n" % mypwd)
response=mytelnet.read_until(command_prompt,5)
if string.count(response,"tset: unknown terminal type"):#需要输入终端的类型,可登陆LINUX后使用tset? 了解
mytelnet.write("vt100\n")
response=mytelnet.read_until(command_prompt,5)
elif not string.count(response,command_prompt):
print "【Password Validate Error: 】\n"# , response
return 0
print "【Password Input Success: 】\n"# , response
mytelnet.write("%s\n" % mycommand)
response=mytelnet.read_until(command_prompt,mycmdtimeout)
if not string.count(response,command_prompt):
print "【Command Execute Error: 】\n"# , response
return 0
print "【Command Execute Success: 】\n"# , response
return 1
except:
print "【Error occured!】"
finally:
mytelnet.close()
uid="user"
pwd="pwd"
command_prompt="shellprompt"
command="echo 'this is a python telnet test' > py.test"
host="ipadress"
telnetcmd(host,uid,pwd,command_prompt,command,timeout=10)
本文详细解析了使用Python进行Telnet命令执行及登录的过程,包括身份验证、命令提示符等待以及命令执行的步骤。通过实例展示了如何利用Telnet连接远程主机并执行特定命令。
685

被折叠的 条评论
为什么被折叠?



