文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

批量管理python脚本

2023-01-31 07:20

关注

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

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

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯