[Python - Design Mode] - (1): small chestnut factory mode, telnet and ssh

Recent going to start to write python practical aspects of small, small example, focused on the record some easy to write python code is easy to maintain way.

Usually work when the main contact is embedded c, not very exposed to python, but the work place occasionally encounter with the python. Some python code sometimes just moving bricks, and did not think to go back and easy maintenance, and what is more than in moving bricks, but lifting a brick on their own feet, with the stuffing, the code behind the colleagues of course, even do not want to maintain.

So when is a record if it was a share of it - and, of course because of the limited level of bad places please criticism

Assume such a scenario, you need to maintain a number of different devices, you need to write a tool to manage them, port access different devices is not the same, such a device requires a telnet, b devices require ssh, and in addition to other logic is the same, so in order to facilitate better not move the upper logic, but the telnet and ssh fit together, the factory is a convenient mode of this scenario design patterns apply.

Factory pattern belongs as needed to generate a different pattern classes, say I need to telnet and ssh connect with a common method, you only need to use the factory class to generate two types can contain connect method.

Given the code:

# -*- coding: UTF-8 -*-
# import pyModule
import sys
import os
import time
import xlrd

import telnetlib
import paramiko

# import usrModule
# sys.path.append('blablabla/')
# import blablabla
sys.path.append('basic/')
# global var
global g_var
# var init
g_var = 0

from pyf_Basic import pyfBasic

class pyfComF(pyfBasic):
    def __init__(self, host     =None,    port   =None,
                       usrname  =None,    passwd =None,
                       whichCom ='telnet'):
        pyfBasic.__init__(self)
        self.className = 'pyfComF'
        self.host      = host
        self.port      = port
        self.usrname   = usrname
        self.passwd    = passwd
        self.whichCom  = whichCom
        self.comObj    = None
        self.buff      = ''

    def constructObj(self):
        if ( self.whichCom == 'telnet' ):
            return pyfComF_telnet(self.host, self.port, self.usrname, self.passwd, self.whichCom)
        if ( self.whichCom == 'ssh' ):
            return pyfComF_ssh(self.host, self.port, self.usrname, self.passwd, self.whichCom)
        pass

    def connect(self):
        pass

    def disconnect(self):
        pass

    def write(self, cmd='\r\n'):
        if(cmd == '\r\n'):
            self.cmd = cmd
        else:
            self.cmd = cmd + '\r\n'
        pass

    def getReply(self, wait=['finished', 'ksh'], timeoutGet=180):
        pass

class pyfComF_telnet(pyfComF):
    def connect(self):
        self.className = 'pyfComF_telnet'
        self.comObj    = telnetlib.Telnet(self.host, self.port)
        self.write(self.usrname)
        time.sleep(0,3)
        self.write(self.passwd)
        time.sleep(0.3)
        pass

    def disconnect(self):
        self.comObj.close()

    def write(self, cmd='\r\n'):
        super(pyfComF_telnet, self).write(cmd=cmd)
        self.comObj.write( cmd )

    def getReply(self, wait=['finished','ksh'], timeoutGet=180):
        self.comObj.read_lazy()
        i,m,reply = self.comObj.expect(wait, timeoutGet)
        return i,m,reply
        

class pyfComF_ssh(pyfComF):
    def connect(self):
        # ssh的connect
        self.className = 'pyfComF_ssh'
        self.comObj    = paramiko.SSHClient()
        self.comObj.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.comObj.connect( self.host, self.port, self.usrname, self.passwd )
        self.bak       = self.comObj
        self.comObj    = self.comObj.invoke_shell()

    def disconnect(self):
        # 封装一层disconnect
        self.comObj.close()
        self.bak.close()

    def write(self, cmd='\r\n'):
        # 可以公用一部分父类的write,方便
        super(pyfComF_ssh, self).write(cmd=cmd)
        self.comObj.send(self.cmd)

    def getReply(self, wait=['finished', 'ksh'], timeoutGet=180):
        time.sleep(0.1)
        foundFlag = -1
        counter   = 0
        counter2  = 0
        choice    = len(wait)
        self.buff = ''
        while(True):
            # 乱写的超时控制
            counter += 1
            time.sleep(0.1)
            if counter > (timeoutGet*10) :
                return foundFlag, wait[foundFlag], self.buff
            # 每次加写到buff,直到满足条件返回
            self.buff += str( self.comObj.recv(10024).decode("utf-8") )
            # 匹配寻找条件
            for indexC in range(choice):
                if wait[indexC] in self.buff:
                    foundFlag = indexC
                    counter2 += 1
                    if (counter2 <= 1):
                        self.write()
                        break
                    return foundFlag, wait[foundFlag], self.buff
# -*- coding: UTF-8 -*-
import sys
# include usrPath
sys.path.append('comF/')

# import pyf_UsrMethod
from pyf_comf import pyfComF

if __name__ == "__main__":
    test  = pyfComF( '192.168.1.102', 22, 'xxx', 'xxx', 'ssh' )
    test1 = test.constructObj()
    test1.connect()
    test1.write('df -h')
    i,m,reply = test1.getReply(wait=['#','$'], timeoutGet=10)
    print(reply)
    test1.write('who')
    i,m,reply = test1.getReply(wait=['#','$'], timeoutGet=10)
    print(reply)
    test1.write('uptime')
    i,m,reply = test1.getReply(wait=['#','$'], timeoutGet=10)
    print(reply)
    test1.disconnect()
    pass

 If you want to change telnet can be seen, then only need to change it to a top parameter method, it is convenient for maintenance, the logic is relatively clear. Will need a separate interface, it can be completed.

Guess you like

Origin www.cnblogs.com/nullspace/p/12046798.html