Python的Telnet登陆

# -*- 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)


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值