secureCRT自动登录脚本(python)

由于每次登录都要输入用户名和密码,还有个别设备不能用SSH2,而我又不记得是哪几台??!!

写个脚本,做个按钮,在Button Bar,New Button,在Action -> Function选Run Script,在Run Script选好脚本路径,自己命名个Label。

 

给2个版本的示例代码,都是可以直接运行的,一个简单点,但扩展性不好;一个复杂点,但具有很强的扩展性。

 

版本1:

单个文件,用户名和密码保存在全局变量中。

# $language = "python"
# $interface = "1.0"

#--------------------------------------------------------------------------------------
import os
#--------------------------------------------------------------------------------------

szSSH2UserName = '"asdaf adsf"'
szSSH2Passwd = "adsfqweradsf"
szTelnetUserName = "asdaf adsf"
szTelnetPasswd = szSSH2Passwd

def connectFun():
    szHost = crt.Dialog.Prompt("Enter host IP address : ", "Host IP", "", False)
    ssh2cmd = "/SSH2 /L %s /PASSWORD %s %s" % (szSSH2UserName, szSSH2Passwd, szHost)
    telnetcmd = "/Telnet %s" % (szHost)
    oTab = 0

    crt.Screen.Synchronous = True
    try:
        crt.Session.ConnectInTab(ssh2cmd)
        oTab = crt.GetActiveTab()
    except:
        try:
            crt.Session.ConnectInTab(telnetcmd)
            oTab = crt.GetActiveTab()
            oTab.Screen.WaitForString("name")
            oTab.Screen.Send(szTelnetUserName + "\r")
            oTab.Screen.WaitForString("assword")
            oTab.Screen.Send(szTelnetPasswd + "\r")
        except:
            crt.Dialog.MessageBox(szHost + " Login Failed!","Failed")
    return oTab
    
connectFun()

 

版本2:

分三个文件,分别是autoConnect.py、connectEnv.py和UserNameAndPassword.txt。(放在同一目录下,且只要在crt中运行autoConnect.py就行了)

  1. autoConnect.py登录逻辑代码,包括用户名和密码读取。
  2. connectEnv.py打包了crt所有的API。可参考我重新打包的crt环境类
  3. UserNameAndPassword.txt保存用户名和密码,第一行是用户名,第二行是密码。

 

autoConnect.py

# $language = "python"
# $interface = "1.0"

#--------------------------------------------------------------------------------------
import os
import sys

def getScriptPath():
    return os.path.split(os.path.realpath(__file__))[0]

sys.path.append(getScriptPath())
import connectEnv
connectEnv.init(crt)
#--------------------------------------------------------------------------------------

class Device():
    def __init__(self):
        self.szDeviceIP = ''
        self.szUserName = ''
        self.szPasswd = ''
        self.env = connectEnv.CrtEnv()

    def initInformation(self):
        self.szDeviceIP = self.env.inputBox("Enter host IP address : ", "Auto login")
        self.__readUsernameAndPassword()

    def login(self):
        isLogin = self.env.login(self.getIP(), self.getUserName(), self.getPasswd())
        if not isLogin:
            self.env.messageBox(self.getIP() + " Login Failed!", "Failed")
        return isLogin

    def getIP(self):
        return self.szDeviceIP

    def getUserName(self):
        return self.szUserName

    def getPasswd(self):
        return self.szPasswd

    def __readUsernameAndPassword(self):
        with open(getScriptPath() + "\\" + "UserNameAndPassword.txt", "r") as f:
            self.szUserName = f.readline().strip('\n')
            self.szPasswd = f.readline().strip('\n')


def main():
    device = Device()
    device.initInformation()
    device.login()

main()

 

connectEnv.py


global crt

def init(crtAPI):
    global crt
    crt = crtAPI

class CrtEnv():
    @staticmethod
    def promptBox(szMessage, szTitle):
        return crt.Dialog.Prompt(szMessage, szTitle, "", True)
 
    @staticmethod
    def inputBox(szMessage, szTitle):
        return crt.Dialog.Prompt(szMessage, szTitle, "", False)
 
    @staticmethod
    def messageBox(szMessage, szTitle):
        crt.Dialog.MessageBox(szMessage, szTitle)
 
    def __init__(self):
        self.__oTab = None
        self.__szPrompt = ""
        self.__szInitPrompt = "#"
        self.__szHostname = ""
 
    def login(self, szHostname, szUsername, szPassword):
        self.__szHostname = szHostname
		
        if self.__ssh(szUsername,szPassword):
            return True
        if self.__telnet(szUsername,szPassword):
            return True
 
        return False
 
    def logout(self):
        self.__oTab.Session.Disconnect()
 
    def send(self, szCMD):
        self.__checkEnv()
        self.__send(szCMD)
        self.__oTab.Screen.WaitForString(szCMD)
        return self.__getResult().encode('utf-8')
 
    def changePrompt(self, szCMD):
        self.__send(szCMD)
        self.__oTab.Screen.WaitForString(szCMD, 1)
        self.__oTab.Screen.WaitForString("Some String will not echo.", 1)
        self.__updatePrompt()
 
    def getTabName(self):
        if self.__isTabEmpty():
            self.__getCurrentTab()
        return self.__oTab.Caption.encode('utf-8')
    
    def getTab(self):
        if self.__isTabEmpty():
            self.__getCurrentTab()
        return self.__oTab

    def getPrompt(self):
        return self.__szPrompt

    def setPrompt(self, szPrompt):
        self.__szPrompt = szPrompt

    def setLog(self, szFileName):
        self.__oTab.Session.LogFileName = szFileName

    def log(self, isLog, isAppend = False):
        self.__oTab.Session.Log(isLog, isAppend)

    def getInitPrompt(self):
        return self.__szInitPrompt
    
    def setInitPrompt(self, szInitPrompt):
        self.__szInitPrompt = szInitPrompt

    def __ssh(self, szUsername, szPassword):
        szConnectString = "/SSH2 /L \"%s\" /PASSWORD \"%s\" %s" % \
            (szUsername, szPassword, self.__szHostname)
        if self.__connect(szConnectString) == False:
            return False
        self.__oTab.Screen.Synchronous = True
        self.__waitDeviceTabInit()
        return True
    
    def __telnet(self, szUsername, szPassword):
        szConnectString = "/Telnet %s" % (self.__szHostname)
        if self.__connect(szConnectString) == False:
            return False
        self.__oTab.Screen.Synchronous = True
        self.__oTab.Screen.WaitForString("ame")
        crt.Sleep(200)
        self.__send(szUsername)
        self.__oTab.Screen.WaitForString("assword")
        crt.Sleep(200)
        self.__send(szPassword)
        self.__waitDeviceTabInit()
        return True
 
    def __connect(self, szConnectString):
        try:
            self.__oTab = crt.Session.ConnectInTab(szConnectString)
            return True
        except:
            return False

    def __waitDeviceTabInit(self):
        crt.Sleep(300)
        self.__oTab.Screen.WaitForString(self.getInitPrompt())
 
    def __send(self, szCMD):
        szCMD = szCMD + '\r'
        self.__oTab.Screen.Send(szCMD)

    def __checkEnv(self):
        if self.__isTabEmpty():
            self.__getCurrentTab()
            self.__oTab.Screen.Synchronous = True
        if self.__isPromptEmpty():
            self.__updatePrompt()
 
    def __isPromptEmpty(self):
        if self.__szPrompt == "":
            return True
        return False
 
    def __isTabEmpty(self):
        if self.__oTab == None:
            return True
        return False
    
    def __getCurrentTab(self):
        self.__oTab = crt.GetActiveTab()
 
    def __getResult(self):
        return self.__oTab.Screen.ReadString(self.__szPrompt)
 
    def __updatePrompt(self):
        crt.Sleep(300)
        rowIndex = self.__oTab.Screen.CurrentRow
        colIndex = self.__oTab.Screen.CurrentColumn - 1
        self.__szPrompt = self.__oTab.Screen.Get(rowIndex, 0, rowIndex, colIndex)
        self.__szPrompt = self.__szPrompt.strip().encode('utf-8')

 

UserNameAndPassword.txt

asdaf adsf
adsfqweradsf

 

你可能感兴趣的:(secureCRT自动登录脚本(python))