登陆服务期执行命令并根据日志判断是否执行成功

项目中需要登录到远程服务器并手动执行任务,根据需求写的脚本,做个笔记。Python3.7环境下的

import paramiko
import configparser
import re
import os
import time
import datetime

config = configparser.ConfigParser()
config.read('conf.ini')

def main():
    print("输入命令: jobtype date -env 例如:   A 2018-09-08 -d\n"
          "1.jobtype:A,B\n"
          "2.date:日期格式yyyy-mm-dd 如:2018-08-04\n"
          "3.env:d(dev),t(test)\n\n")

    code_date = ['A','B','-d','-t']

    while True:
        job_code = input('请输入执行定时任务命令:')
        job_code = job_code.lower()
        job_codes = job_code.split()
        tmp = [val for val in job_codes if val in code_date]
        if len(tmp) != 2:
            print('任务类型或环境参数有误,请重新输入')
        else:
            # 定时任务类型
            if job_code.find('A') > -1:
                job_type = '执行A任务命令'
            elif job_code.find('B') > -1:
                job_type = '执行B任务命令'
            elif job_code.find('C') > -1:
                job_type = '执行C任务命令'


            # 执行环境
            if job_code.find('-d') > -1:
                env_code = 'dev'
            elif job_code.find('-t') > -1:
                env_code = 'test'

            # 获取日期
            date_string = re.findall(".* (.*) .*",job_code)
            job_date = "".join(date_string)

            # 获取环境配置
            ip = config.get(env_code,"ip")
            username = config.get(env_code,"username")
            password = config.get(env_code,"password")

            # 连接SSH
            try:
                ssh = paramiko.SSHClient()
                key = paramiko.AutoAddPolicy()
                ssh.set_missing_host_key_policy(key)
                ssh.connect(ip, 22, username, password ,timeout=5)

                # 获取当前时间
                # now_time=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

                # 执行Job命令
                job_command =job_type+job_date
                stdin, stdout, stderr = ssh.exec_command(job_command)
                print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + " 开始执行")
                ssh.close()
            except:
                print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + " 定时任务执行失败")

            #获取日志文件
            t = paramiko.Transport((ip, 22))
            t.connect(username=username, password=password)
            sftp = paramiko.SFTPClient.from_transport(t)
            try:
                result = 0
                for i in range(1, 20):
                    time.sleep(60)
                    sftp.get('os.getcwd()+'/\\console.log')
                    log_content = open('console.log', 'r', encoding='UTF-8')
                    log_string = log_content.read()
                    log_content.close()
                    if "任务开始时间" in log_string:
                        print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + " 执行中...")
                        if "执行完毕时间" in log_string:
                            time.sleep(5)
                            print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + " 执行完毕")
                            result = 1
                            break
                if result == 0:
                    print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + " 执行失败")
            except:
                print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + " 获取日志失败,可能未执行成功")

if __name__ == "__main__":
    main()

 

conf.ini文件如下:

[dev]
ip=192.168.51.1
username=xxx
password=xxxx

[test]
ip=192.168.49.8
username=yyy
password=yyyy

 

posted @ 2019-03-30 17:29  Dimdusk  阅读(379)  评论(0编辑  收藏  举报