在做后台的自动化测试中,我们可能会遇到一些中断服务器网络的情况,来测试程序在这种网络异常情况下的可靠性和健壮性。那之前采用的简单易用的方法是到机房去,将对应服务器的网线直接拔掉,这种效率低的方法无法满足自动化测试的需求。
我们借助python telnetlib库提供的方法,可以有效的解决这个问题。
- import time
- import telnetlib
- class OperateSw:
- def swLogin(swip):
- try:
- handler = telnetlib.Telnet(swip)
- except Exception:
- return {'rc':-1}
- handler.read_until("Password: ")
- handler.write("******\n")
- handler.write("enable\n")
- handler.read_until("Password: ")
- handler.write("******\n")
- return {'rc':0,'result':handler}
- swLogin = staticmethod(swLogin)
- def swShutPort(handler,port):
- if OperateSw.swPortIsUp(handler,port):
- handler.write("conf terminal\n")
- handler.write("int %s\n" % port)
- handler.write("shutdown\n")
- handler.write("end\n")
- handler.write("write\n")
- else:
- return True
- i = 0
- while OperateSw.swPortIsUp(handler,port):
- time.sleep(1)
- i += 1
- if i > 30:
- return False
- return True
- swShutPort = staticmethod(swShutPort)
- def swNoShutPort(handler,port):
- if not OperateSw.swPortIsUp(handler,port):
- handler.write("conf terminal\n")
- handler.write("int %s\n" % port)
- handler.write("no shutdown\n")
- handler.write("end\n")
- handler.write("write\n")
- else:
- return True
- i = 1
- while OperateSw.swPortIsUp(handler,port) == False:
- time.sleep(1)
- i += 1
- if i > 30:
- return False
- return True
- swNoShutPort = staticmethod(swNoShutPort)
-
- def swPortIsUp(handler,port):
- handler.write("show int %s\n" % port)
- handler.write(" ")
- time.sleep(1)
- string = handler.read_very_eager()
- if string.find("connected") != -1:
- return True
- elif string.find("down") != -1:
- return False
- swPortIsUp = staticmethod(swPortIsUp)
-
- class NetActions:
- def noShutSwPort(swip,swport):
- __login = OperateSw.swLogin(swip)
- if __login['rc'] == -1:
- return {'rc':-1,'result':"Can't login switch %s"%swip}
- if OperateSw.swNoShutPort(__login['result'], swport):
- return {'rc':0}
- else:
- return {'rc':-1,'result':"Execute Switch configuration command failed"}
- noShutSwPort = staticmethod(noShutSwPort)
-
- def shutSwPort(swip,swport):
- __login = OperateSw.swLogin(swip)
- if __login['rc'] == -1:
- return {'rc':-1,'result':"Can't login switch %s"%swip}
- if OperateSw.swShutPort(__login['result'], swport):
- return {'rc':0}
- else:
- return {'rc':-1,'result':"Execute Switch configuration command failed"}
- shutSwPort = staticmethod(shutSwPort)
-
- if __name__=="__main__":
- MyAction = NetActions()
- #MyAction.noShutSwPort("10.224.29.147","f0/6")
- MyAction.shutSwPort("10.224.29.147","f0/6")
阅读(1883) | 评论(0) | 转发(0) |