实用运维脚本

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/u014589856/article/details/96438081

近期要做一些集群的维护工作,打算开发一些实用的脚本协助集群的管理:

1、实现多机操控和文件复制

实现基于sshpass模块的远程操作和批量复制,依赖前体要通过离线或者在线的方式在运行脚本的机器上安装sshpass命令(Python2和使用到的模块好像已经默认集成到centos系统中);还有集群所有节点的密码要统一,如果不统一可以稍作修改指定不同的用户账户和密码实现统一控制。

sshUtil.py的内容如下:

#! /usr/bin/python
# -*- coding:UTF-8 -*-
import os
import sys
import commands
import datetime
import re
import argparse
class Run(object):
        def __init__(self,user,host,password):
                self.__host=host
                self.__password=password
                self.__user=user
        def sshdo(self, cmd):
                cmd = "sshpass -p'%s' ssh -o 'StrictHostKeyChecking=no' %s@%s '%s'" %(self.__password,self.__user,self.__host, cmd)
                if os.system(cmd)!=0:
                        print("[err]: "+cmd)
        def sshcopy(self, srcfile, destfile):
                cmd = "sshpass -p'%s' scp -r %s %s@%s:%s" % (self.__password, srcfile, self.__user, self.__host, destfile)
                (status, output) = commands.getstatusoutput(cmd)
                print("[status]"+str(status))
                return status
def runHosts(args):
        showArgs(args)
        user = "root"
        password = "root"
        for line in open(args.f):
                line=line.replace("\n", "").replace("\r", "").strip()
                if not line.startswith("192"):
                        continue
                host = re.split(" |\t",line)[-1]
                print("-----["+host+"]------")
                run = Run(user,host,password)
                if args.cmd=="run":
                        run.sshdo(args.c)
                elif args.cmd=="cp":
                        run.sshcopy(args.s, args.d)
                elif args.cmd=="chage_passwd_time":
                        #通过修改密码过期时间,做到密码防止过期(用于不能修改密码过期策略的集群)
                        run.sshdo("chage -d %s %s" %(datetime.datetime.today().strftime('%Y-%m-%d'),user))
                        run.sshdo("chage -l  %s| head -n 1" %(user))
                else:
                        print("error cmd!!!!!")
def showArgs(args):
        if args.cmd=="run":
                print("[cmd]run:"+args.c)
        elif args.cmd=="cp":
                print("[cmd]cp:"+args.s +" to "+args.d)
        elif args.cmd=="chage_passwd_time":
                print("[cmd]chage_passwd_time")
        else:
                print("error cmd!!!!!")
if __name__ == "__main__" :
        parser = argparse.ArgumentParser(description='run or cp for each node.')
        parser.add_argument('cmd',type=str,help='run cmd[run/cp/chage_passwd_time]')
        parser.add_argument('-s',type=str,help='srcFile [cp]')
        parser.add_argument('-d',type=str,help='destPath [cp]')
        parser.add_argument('-c',type=str,help='cmd  [run]')
        parser.add_argument('-f',type=str,help='hosts file',default='/etc/hosts')
        args = parser.parse_args()
        print("[begin]...............")
        runHosts(args)
        print("[finish]!!!!!!!!!!!!!!")

用法演示如下,其中还可以通过 -f指定要使用的配置文件路径

[root@n101 python]# python sshUtil.py --help
usage: sshUtil.py [-h] [-s S] [-d D] [-c C] [-f F] cmd

run or cp for each node.

positional arguments:
  cmd         run cmd[run/cp/chage_passwd_time]

optional arguments:
  -h, --help  show this help message and exit
  -s S        srcFile [cp]
  -d D        destPath [cp]
  -c C        cmd [run]
  -f F        hosts file
[root@n101 python]# python sshUtil.py cp -s /root/shell/python/test -d /root
[begin]...............
[cmd]cp:/root/shell/python/test to /root
-----[n101]------
[status]0
-----[n102]------
[status]0
-----[n103]------
[status]0
[finish]!!!!!!!!!!!!!!
[root@n101 python]# python sshUtil.py run -c "ls -l /root"
[begin]...............
[cmd]run:ls -l /root
-----[n101]------
总用量 171364
-rw-------.  1 root root      1231 6月  16 09:43 anaconda-ks.cfg
drwxr-xr-x.  3 root root       134 7月   9 23:09 shell
drwxr-xr-x.  2 root root        15 7月  18 17:07 test
-----[n102]------
总用量 4
-rw-------. 1 root root 1231 6月  16 09:43 anaconda-ks.cfg
drwxr-xr-x. 2 root root   15 7月  18 17:07 test
-----[n103]------
总用量 4
-rw-------. 1 root root 1231 6月  16 09:43 anaconda-ks.cfg
drwxr-xr-x. 2 root root   15 7月  18 17:07 test
[finish]!!!!!!!!!!!!!!
[root@n101 python]# python sshUtil.py chage_passwd_time
[begin]...............
[cmd]chage_passwd_time
-----[n101]------
最近一次密码修改时间                                    :7月 18, 2019
-----[n102]------
最近一次密码修改时间                                    :7月 18, 2019
-----[n103]------
最近一次密码修改时间                                    :7月 18, 2019
[finish]!!!!!!!!!!!!!!

猜你喜欢

转载自blog.csdn.net/u014589856/article/details/96438081