批量管理python脚本

发布时间:2019-09-21 11:10:07编辑:auto阅读(1760)

    新出炉的脚本, 有错的地方还望指出,谢谢。

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    #
    #  Syscloud Operation platform.py

    #  Copyright 2013 allan <allan@ALLAN-PC>

    #  This program is free software; you can redistribute it and/or modify
    #  it under the terms of the GNU General Public License as published by
    #  the Free Software Foundation; either version 2 of the License, or
    #  (at your option) any later version.

    #  This program is distributed in the hope that it will be useful,
    #  but WITHOUT ANY WARRANTY; without even the implied warranty of
    #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    #  GNU General Public License for more details.

    #  You should have received a copy of the GNU General Public License
    #  along with this program; if not, write to the Free Software
    #  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
    #  MA 02110-1301, USA.

    #  QQ:286575330
    import paramiko
    import sys
    import Queue
    import threading
    import getopt
    class webmonitor:
        def __init__(self):
            try:
                self.pkey_file=‘这是密钥的路径’
                self.known_host = '/root/.ssh/known_hosts'
                self.key=paramiko.RSAKey.from_private_key_file(self.pkey_file, password=‘这里是密钥的密码’)
            except:
                print 'No such file or directory: \'/root/.ssh/jumper_rsa\''
        def help(self):
            return '''
                  -h,--help            帮助页面
                  -c,--command        执行的命令
                  -H,--host            主机IP
                  -f, --file        指定文件
                  -S, --SENDFILE    传输文件模式
                  -C, --COMMAND        执行命令模式
                  -L, --localpath    本地文件路径
                  -R, --removepath    远程服务器路径
          e.g.
              单台执行命令格式: -C -H “IP地址” -c “命令”
              批量执行命令格式: -C -f “IP地址文件” -c “命令”
              单台传送文件: -S -H “IP地址” -L "本地文件路径" -R “远程服务器文件路径”
              批量传送文件: -S -f "IP地址文件" -L “本地文件路径” -R “远程文件路径”
          '''
        def ssh(self,hostname,port,username, cmd):#ssh 远程执行命令
            ssh = paramiko.SSHClient()
            ssh.load_system_host_keys(self.known_host)
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh.connect(hostname, port, username, password='这是远程服务器密码', pkey=self.key, allow_agent=True, look_for_keys=True)
            stdin, stdout, stderr = ssh.exec_command(cmd)
            if stderr.read() != 0:
                print '%s%s\n[OK]%s\n' % (stderr.read(),stdout.read(),hostname)
                print '========================================================================='
            else:
                print "\033[1;31;40m[ERROR]%s\033[0m" % hostname
                print '========================================================================='
            ssh.close()
        def sftp(self, hostname, port,username,localpath, remotepath):#SFTP 传输文件
            ssh = paramiko.Transport((hostname,port))
            ssh.connect(username=username, pkey=self.key)
            sftp = paramiko.SFTPClient.from_transport(ssh)
            sftp.put(localpath,remotepath)
            sftp.close()
            ssh.close()
            print '========================================================================='
            print "OK %s" % hostname
            return 0
    def isset(v):#判断定义的是否为变量
        try:
            type (eval(v))
        except:
            return 0
        else:
            return 1
    if __name__ == '__main__':
        try:
            opts, args = getopt.getopt(sys.argv[1:], "L:R:CSH:c:f:h", ["localpath","remotepath","COMMAND","SENDFILE","host","command","file",'help'])
            if sys.argv[1] == "-S":
                for o, value in opts:
                    if o in ("-S","--SENDFILE"):
                        print "MODE: SENDFILE"
                    elif o in ("-h","--help"):
                        print webmonitor().help()
                    elif o in ("-H","--host"):
                        host = value
                    elif o in ("-f", "--file"):
                        filein = value
                    elif o in ("-c","--command"):
                        cmd = value
                    elif o in ("-R","--remotepath"):
                        rpath = value
                    elif o in ("-L","--localpath"):
                        lpath = value
                    if isset('host') and isset('lpath') and isset('rpath'):
                        webmonitor().sftp(host, 22, "root", lpath, rpath)
                        print '========================================================================='
                    elif isset('filein') and isset('lpath') and isset('rpath'):
                        threads = []
                        myqueue = Queue.Queue(maxsize = 0)
                        f = open(filein, "r")
                        for ip in f:
                            if ip[0] == '#':
                                break
                            if len(ip) == 0:
                                break
                            myqueue.put(ip)
                        f.close()
                        for x in xrange(0,myqueue.qsize()):
                            if myqueue.empty():
                                break
                            mutex = threading.Lock()
                            mutex.acquire()
                            threads.append(threading.Thread(target=webmonitor().sftp, args=(myqueue.get(),22,"root", lpath, rpath)))
                            mutex.release()
                        for t in threads:
                            t.start()
                        for t in threads:
                            t.join()
                        print '========================================================================='
            elif sys.argv[1] == "-C":#执行命令模式
                for o, value in opts:
                    if o in ("-C","--COMMAND"):
                        print "MODE: COMMAND"
                    elif o in ("-H","--host"):
                        host = value
                    elif o in ("-f","--file"):
                        filein = value
                    elif o in ("-c","--command"):
                        cmd = value
                    if isset('host') and isset('cmd'):#单台服务器执行命令
                        webmonitor().ssh(host, 22, "root", cmd)
                    elif isset('filein') and isset('cmd'):#多台服务器批量执行命令
                        threads = []
                        myqueue = Queue.Queue(maxsize = 0)
                        f = open(filein, "r")
                        for ip in f:
                            if ip[0] == '#':
                                break
                            if len(ip) == 0:
                                break
                            myqueue.put(ip)
                        f.close()
                        for x in xrange(0,myqueue.qsize()):
                            if myqueue.empty():#判断队列是否为空
                                break
                            mutex = threading.Lock()
                            mutex.acquire()
                            threads.append(threading.Thread(target=webmonitor().ssh, args=(myqueue.get(),22,"root", cmd)))
                            mutex.release()
                        for t in threads:
                            t.start()
                        for t in threads:
                            t.join()
            else:
                print webmonitor().help()
        except:
            print webmonitor().help()

关键字