自动化测试脚本A版

#! /usr/bin/python3.8

#测试电源,配合网口检查,bypass功能测试

from telnetlib import Telnet

import csv

import logging

import telnetlib

import time

import os

IP_SERVER = "192.168.0.111"

#LOCAL = "192.168.0.200"

base_path = '/home/spec/FW_PY/'

config_file = base_path+'config.csv'

count_file = base_path+'log/counter.csv'

failcount_file = base_path+'log/failcount.csv'

failure_file = base_path+'log/failure.csv'

class main:

    def __init__(self):

        #self.success=open('/home/spec/FW_PY/log/success.csv','a',encoding='utf-8',newline='')

        self.failure=open(failure_file,'a',encoding='utf-8',newline='')

        #self.success_writer=csv.writer(self.success)

        self.failure_writer=csv.writer(self.failure)

    #打开config文件获取参数

    def getconfig(self, arg, file):

        try:

            #root下使用

            workbook = open(file,'r', encoding='utf-8', newline='')

            rows= csv.reader(workbook)

            for row in rows:

                #print(row)

                if row[0] == "USER" and arg == "USER":

                    user =  row[1]

                    return user

                if row[0] == "Passwd"and arg == "Passwd":

                    psw = row[1]

                    return psw

                if row[0] == "networks"and arg == "networks":

                    networks_tmp = row[1:]

                    networks = [str(num) for num in networks_tmp]

                    return networks

                if row[0] == "source_ip"and arg == "source_ip":

                    ips_tmp = row[1:]

                    ips = [str(num) for num in ips_tmp]

                    return ips

                if row[0] == "destnation_ip"and arg == "destnation_ip":

                    ips_tmp = row[1:]

                    ips_des = [str(num) for num in ips_tmp]

                    return ips_des

                if row[0] == "count" and arg == "count":

                    count =  int(row[1])

                    return count

                if row[0] == "eth_check" and arg == "eth_check":

                    eth_check_tmp = row[1:]

                    eth_check = [str(num) for num in eth_check_tmp]

                    return eth_check

        except Exception as e:

            print(f"失败: {e}")

            return False

    #打开文档增加统计次数

    #适用于硬断电需要用文件统计循环次数的场景

    def openfile(self, file):

        try:

            #file = os.path.abspath('counter.csv')

            #csvfile = open(file,'r', encoding='utf-8', newline='')

            #root下使用

            csvfile = open(file,'r', encoding='utf-8', newline='')

            counte1 = csv.reader(csvfile)

            for row in counte1:

                print(row)

                row1 = int(row[0])+1

                print(row1)

            csvfile1 = open(file,'w', encoding='utf-8', newline='')

            csv.DictWriter(csvfile1, fieldnames= [row1]).writeheader()

            csvfile.close()

            return row1

        except Exception as e:

            print(f"失败: {e}")

            return False

       

       

    #打开文档增加失败次数

    def failcount(self, file):

        try:

            csvfile = open(file, 'r', encoding='utf-8', newline='')

            counte1 = csv.reader(csvfile)

            for row in counte1:

                row1 = int(row[0])+1

            csvfile1 = open(file,'w', encoding='utf-8', newline='')

            csv.DictWriter(csvfile1, fieldnames= [row1]).writeheader()

            csvfile.close()

            return row1

        except Exception as e:

            print(f"失败: {e}")

            return False


 

    def telnet(self,ip,port,username,password):

        try:

            self.session=Telnet(host=ip, port=port)

            #print( f"####{ip} {23} 连接成功")

            self.session.read_until(b'login:', timeout=2)

            self.session.write(username.encode('utf-8') + b'\n')

            self.session.read_until(b'Password:', timeout=2)

            self.session.write(password.encode('utf-8') + b'\n')

            self.session.read_until(b'Welcome', timeout=2)

            command_result = self.session.read_very_eager().decode('utf-8')

            #print(command_result)

            #切换到root用户下

            self.session.write(b'\n'+"sudo -s".encode('utf-8') + b'\n')

            self.session.read_until(b'Password:', timeout=2)

            self.session.write(password.encode('utf-8') + b'\n')

            self.session.read_until(b'root@spec', timeout=2)

            #command_result = self.session.read_very_eager().decode('utf-8')

            #print(command_result)

            row=[ip,23,'login success']

            #self.success_writer.writerow(row)

            print(f"####{ip} {23}  telnet登录成功")

            return self

        except Exception as e:

            row=[ip,23,'!!!!telnet登录失败']

            self.failure_writer.writerow(row)

            print(f"{ip} {23}  telnet登录失败: {e}")

            return False

       

    #关闭telnet连接

    def logout_host(self):

        self.session.close()

    #执行命令不需要回显

    def execute_some_command(self, command, time_wait):

        try:

        # 执行命令

            self.session.write(command.encode('ascii')+b'\n')

            time.sleep(time_wait)

            # 获取命令结果

            command_result = self.session.read_very_eager().decode()

            # logging.warning(command + '执行结果:\n%s' % command_result)

            return command_result

        except Exception as e:

            row = ['execute_command false:', command]

            self.failure_writer.writerow(row)

            print(f"执行命令失败: {command}, 错误信息: {e}")

            return None

    #执行命令并判断回显是否符合预期

    def execute_some_command_add_check(self, command, result_char, time_wait):

       try:

            # 执行命令

            self.session.write(command.encode('ascii')+b'\n')

            time.sleep(time_wait)

            # 获取命令结果

            command_result = self.session.read_very_eager().decode()

            # logging.warning(command + '执行结果:\n%s' % command_result)

            if result_char in command_result:

                print('execute_command success:' , command)

                return True

            else:

                print('execute_command false:' , command)

                row=['execute_command false:', command]

                self.failure_writer.writerow(row)

                self.failure_writer.writerow([command_result])

                print(command_result)

                return False

       except Exception as e:

            row = ['execute_command false:', command]

            self.failure_writer.writerow(row)

            print(f"执行命令失败: {command}, 错误信息: {e}")

            return False

    #执行命令并判断回显是否符合预期

    def execute_some_command_add_check_fail(self, command, result_char, time_wait):

       try:

            # 执行命令

            self.session.write(command.encode('ascii')+b'\n')

            time.sleep(time_wait)

            # 获取命令结果

            command_result = self.session.read_very_eager().decode()

            # logging.warning(command + '执行结果:\n%s' % command_result)

            if result_char in command_result:

                print('except success,  execute_command false:' , command)

                row=['except success,  execute_command false:', command]

                self.failure_writer.writerow(row)

                self.failure_writer.writerow([command_result])

                print(command_result)

                return False

            else:

                print('expect fail,  execute_command success:' , command)

                return True

       except Exception as e:

            row = ['except success,  execute_command false:', command]

            self.failure_writer.writerow(row)

            print(f"执行命令失败: {command}, 错误信息: {e}")

            return False

       

    def execute_some_command_os(self, command):

        try:

        # 执行命令

            command_result = os.popen(command).read()

            #time.sleep(time_wait)

            # 获取命令结果

            return command_result

        except Exception as e:

            row = ['execute_command false:', command]

            self.failure_writer.writerow(row)

            print(f"执行命令失败: {command}, 错误信息: {e}")

            return None

    #执行命令并判断回显是否符合预期

    def execute_some_command_add_check_os(self, command, result_char):

       try:

            # 执行命令

            command_result = os.popen(command).read()

            # 获取命令结果

            if result_char in command_result:

                print('execute_command success:' , command)

                return True

            else:

                print('execute_command false:' , command)

                row=['execute_command false:', command]

                self.failure_writer.writerow(row)

                self.failure_writer.writerow([command_result])

                print(command_result)

                return False

       except Exception as e:

            row = ['execute_command false:', command]

            self.failure_writer.writerow(row)

            print(f"执行命令失败: {command}, 错误信息: {e}")

            return False

           

    #执行命令并判断回显是否符合预期

    def execute_some_command_add_check_os_nolog(self, command, result_char):

       try:

            # 执行命令

            command_result = os.popen(command).read()

            # 获取命令结果

            if result_char in command_result:

                print('execute_command success:' , command)

                return True

            else:

                print('execute_command false:' , command)

                #row=['execute_command false:', command]

                #self.failure_writer.writerow(row)

                #self.failure_writer.writerow([command_result])

                #print(command_result)

                return False

       except Exception as e:

            row = ['execute_command false:', command]

            self.failure_writer.writerow(row)

            print(f"执行命令失败: {command}, 错误信息: {e}")

            return False

    #执行命令并判断回显是否符合预期

    def execute_some_command_add_check_fail_os(self, command, result_char):

       try:

            # 执行命令

            command_result = os.popen(command).read()

            # 获取命令结果

            # logging.warning(command + '执行结果:\n%s' % command_result)

            if result_char in command_result:

                print('except success,  execute_command false:' , command)

                row=['except success,  execute_command false:', command]

                self.failure_writer.writerow(row)

                self.failure_writer.writerow([command_result])

                print(command_result)

                return False

            else:

                print('expect fail,  execute_command success:' , command)

                return True

       except Exception as e:

            row = ['except success,  execute_command false:', command]

            self.failure_writer.writerow(row)

            print(f"执行命令失败: {command}, 错误信息: {e}")

            return False

if __name__ == '__main__':

    print("程序开始执行")

    main=main()

    #ips=main.GetIp()

    fail_num = 0

    retry_num = 0

    fail1 = 0

    USER = main.getconfig('USER',config_file)

    PSW_1 = main.getconfig('Passwd',config_file)

    eth = main.getconfig('networks',config_file)

    source_ip = main.getconfig('source_ip',config_file)

    destnation_ip = main.getconfig('destnation_ip',config_file)

    count = main.getconfig('count',config_file)

    eth_check = main.getconfig('eth_check',config_file)

    #测试重启以后网卡是否恢复正确

    check_eth = int(input("是否需要校验网卡信息,需要输入 1 ,不需要输入 0,默认为0 :") or "0")

    #是否需要测试板载bypass

    if_onboard = int(input("是否需要测试板载bypass,需要请输入 1 ,不需要输入 0,默认为0 :") or "0")

    #是否需要测试扩展卡bypass

    if_slot = int(input("是否需要测试扩展卡slot1的bypass,需要请输入 1 ,不需要输入 0,默认为0 :") or "0")

    #测试模式

    test_mode = int(input("测试模式选择,shutdown需要请输入 1 ,startup需要输入 2,否则为reboot模式,默认为0:") or "0")

    #num = main.openfile()

    #client =main.ssh_login(LOCAL,USER,PSW_1)

    #main.failure_writer.writerow(['count: %d' %num])

    #配置IP地址

    #pc.execute_some_command('ip addr del 11.1.1.1/24 dev enp101s0', 1)

    #pc.execute_some_command('ip addr add 11.1.1.1/24 dev enp101s0', 1)

    #

    for j in range(0, count):

        print('测试第 ',j+1,' 轮')

        pc=main.telnet(IP_SERVER,23,USER,PSW_1)

        pc.failure_writer.writerow(['count: %d' %(j+1)])

        pc.execute_some_command('cd /root/FW_PY', 1)

        pc.execute_some_command('pwd', 1)

        pc.execute_some_command('chmod 777 bypass_tool', 1)

        #网卡检查

        if (check_eth == 1):

            for eth in eth_check:

                cmd_eth = 'ip addr show dev ' + eth

                a13=pc.execute_some_command_add_check_fail(cmd_eth, 'does not exist',1)

                if (a13==False):

                    fail_num = fail_num +1

        #板载bypass测试

        if (if_onboard == 1):

            if j == 0:

                a1=pc.execute_some_command_add_check('./bypass_tool 1 0 0 1', 'change bypass_stat is success', 5)

                a2=pc.execute_some_command_add_check('./bypass_tool 1 0 1 1', 'change bypass_stat is success', 5)

            #time.sleep(3)

            cmd3 = 'ping  ' + destnation_ip[0] + '  -c   2'

            a3=main.execute_some_command_add_check_os(cmd3, 'ttl=128 time=')

            #增加重试是为了增加脚本可靠性

            if a3 == False:

                print('开启旁路功能未能通, 预期能通, 做一次retry')

                time.sleep(5)

                retry_num = retry_num+1

                cmd1 = 'ifconfig  ' + eth[0]+ ' down'

                cmd2 = 'ifconfig  ' + eth[0]+ ' up'

                main.execute_some_command_os(cmd1)

                main.execute_some_command_os(cmd2)

                a3=main.execute_some_command_add_check_os(cmd3, 'ttl=128 time=')

                #if a3 == False:

                    #input("按下任意键继续执行")

            time.sleep(5)

            a4=pc.execute_some_command_add_check('./bypass_tool 1 0 0 0', 'change bypass_stat is success', 5)

            a5=pc.execute_some_command_add_check('./bypass_tool 1 0 1 0', 'change bypass_stat is success', 5)

            time.sleep(5)

            a6=main.execute_some_command_add_check_fail_os(cmd3, 'ttl=')

            #if (a1==False or a2==False or a3==False or a4==False or a5==False or a6==False):

            if (a3==False or a6==False):

                fail_num = fail_num +1

            time.sleep(20)

        #板载bypass测试

        ##########另一组bypass##########

        #slot1的bypass测试

        if (if_slot == 1):

            if j == 0:

                a1=pc.execute_some_command_add_check('./bypass_tool 1 1 0 1', 'change bypass_stat is success', 5)

                a2=pc.execute_some_command_add_check('./bypass_tool 1 1 1 1', 'change bypass_stat is success', 5)

            time.sleep(3)

            cmd3 = 'ping  ' + destnation_ip[1] + '  -c   2'

            a3=main.execute_some_command_add_check_os(cmd3, 'ttl=128 time=')

            #增加重试是为了增加脚本可靠性

            if a3 == False:

                print('开启旁路功能未能通, 预期能通, 做一次retry')

                time.sleep(5)

                retry_num = retry_num+1

                cmd1 = 'ifconfig  ' + eth[1]+ ' down'

                cmd2 = 'ifconfig  ' + eth[1]+ ' up'

                main.execute_some_command_os(cmd1)

                main.execute_some_command_os(cmd2)

                a3=main.execute_some_command_add_check_os(cmd3, 'ttl=')

            time.sleep(5)

            a4=pc.execute_some_command_add_check('./bypass_tool 1 1 0 0', 'change bypass_stat is success', 5)

            a5=pc.execute_some_command_add_check('./bypass_tool 1 1 1 0', 'change bypass_stat is success', 5)

            time.sleep(5)

            a6=main.execute_some_command_add_check_fail_os(cmd3, 'ttl=128 time=')

            if (a3==False or a6==False):

                fail_num = fail_num +1

        #第二组结束

        print('本轮失败次数:', fail_num, '重试次数', retry_num)

        fail1 = fail1 + fail_num

        fail_num = 0        

        print('失败次数:', fail1, '轮次', j+1,'总次数', count)

            #print(fail_num)

        if j+1 == count:

            break

        #测试模式

        if (test_mode == 1):

            pc.execute_some_command('shutdown now', 1)

            print('待测设备shutdown')

        if (test_mode == 2):

            print('等待断电')

            for k in range(0, 100):

                cmd4 = 'ping  ' + IP_SERVER + '  -c   2'

                a7 = main.execute_some_command_add_check_os_nolog(cmd4, 'ttl=64 time=')

                print('待测设备是否可连通',a7)

                if a7 == False:

                    break

                time.sleep(20)

            print('硬断电开始')

        else:

            pc.execute_some_command('reboot', 1)

            print('待测设备reboot')

        time.sleep(20)

        for k in range(0, 100):

            cmd4 = 'ping  ' + IP_SERVER + '  -c   2'

            a7 = main.execute_some_command_add_check_os_nolog(cmd4, 'ttl=64 time=')

            print(a7)

            if a7 == True:

                break

            #测试板载

            if (if_onboard == 1):

                cmd5 = 'ping  ' + destnation_ip[0] + '  -c   2'

                a3 = main.execute_some_command_add_check_os(cmd5, 'ttl=128 time=')

                time.sleep(30)

                #增加重试是为了增加脚本可靠性

                if a3 == False:

                    print('开启旁路功能未能通, 预期能通, 做一次retry')

                    time.sleep(5)

                    retry_num = retry_num+1

                    cmd1 = 'ifconfig  ' + eth[0]+ ' down'

                    cmd2 = 'ifconfig  ' + eth[0]+ ' up'

                    main.execute_some_command_os(cmd1)

                    main.execute_some_command_os(cmd2)

                    a3=main.execute_some_command_add_check_os(cmd5, 'ttl=128 time=')

                    #time.sleep(30)

                if (a3==False):

                    fail_num = fail_num +1

            #测试slot1

            if (if_slot == 1):

                cmd6 = 'ping  ' + destnation_ip[1] + '  -c   2'

                a3 = main.execute_some_command_add_check_os(cmd6, 'ttl=128 time=')

                time.sleep(30)

                #增加重试是为了增加脚本可靠性

                if a3 == False:

                    print('开启旁路功能未能通, 预期能通, 做一次retry')

                    time.sleep(5)

                    retry_num = retry_num+1

                    cmd1 = 'ifconfig  ' + eth[1]+ ' down'

                    cmd2 = 'ifconfig  ' + eth[1]+ ' up'

                    main.execute_some_command_os(cmd1)

                    main.execute_some_command_os(cmd2)

                    a3=main.execute_some_command_add_check_os(cmd6, 'ttl=128 time=')

                    #time.sleep(30)

                if (a3==False):

                    fail_num = fail_num +1

            #测试slot1

           

    print('####备注\n####失败次数:一次循环任意一个步骤失败则统计为失败。\n####重试次数: 开启旁路功能如果失败,会重试一次')

    print('失败次数:', fail1, '总次数', count)

    pc.failure_writer.writerow(['失败次数:', fail1, '总次数', count])

    time.sleep(20)

    main.failure.close()

    pc.logout_host()

    print('####关闭连接!')

    print('执行完毕!')

    #time.sleep(16000)


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值