运维小脚本

记录一些python脚本。

1、启动java应用服务:

#!/usr/bin/env python
# coding: utf-8
import os
import time
import socket
import subprocess


class JavaServer:
    def __init__(self, command, port):
        self.command = command
        self.port = port
        self.server_start_all()

    def server_start_all(self):
        fnull = open(os.devnull, 'w')
        result = subprocess.call(self.command, shell=True, stdout=fnull, stderr=fnull)
        current_time = time.strftime('%Y%m%d-%H%M%S', time.localtime())
        time.sleep(1)  # 延迟1秒
        if result:
            print('时间:{}---执行命令:{} 失败'.format(current_time, self.command))
            return False
        else:
            print('时间:{}---执行命令:{} 成功'.format(current_time, self.command))
            self.check_aliveness()
        fnull.close()

    def check_aliveness(self):
        hostname = socket.gethostname()  # 获取主机名
        ip = socket.gethostbyname(hostname)  # 获取主机ip地址
        sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sk.settimeout(1)
        try:
            sk.connect((ip, self.port))
            print('server:{} 端口:{} is OK '.format(ip, self.port))
            self.server_port = 'ok'
        except Exception:
            print('sever:{} 端口:{} is NOT OK '.format(ip, self.port))
            return False
        finally:
            sk.close()


if __name__ == '__main__':
    command_list = [['/usr/local/zookeeper-3.4.6/bin/zkServer.sh start', 3888],
                    ['sh /usr/java/account/bin/startup.sh &', 20678],
                    ['sh /usr/java/order/bin/startup.sh &', 20999],
                    ['sh /usr/java/user/bin/startup.sh &', 20001],
                    ['sh /usr/java/system/bin/startup.sh &', 20888]
                    ]

    while True:
        for i in command_list:
            st = JavaServer(i[0], i[1])
            print(st.__dict__)
            if st.__dict__['server_port'] == 'ok':
                pass
            else:
                print('服务:{}开启失败'.format(i[0]))
                break
        break

。。。。  

猜你喜欢

转载自www.cnblogs.com/Black-rainbow/p/9180945.html