批量管理python腳本

新出爐的腳本, 有錯的地方還望指出,謝謝。

#!/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()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章