Python脚本实现集群检测和管理功能


Posted in Python onMarch 06, 2015

场景是这样的:一个生产机房,会有很多的测试机器和生产机器(也就是30台左右吧),由于管理较为混乱导致了哪台机器有人用、哪台机器没人用都不清楚,从而产生了一个想法--利用一台机器来管理所有的机器,记录设备责任人、设备使用状态等等信息....那么,为什么选择python,python足够简单并且拥有丰富的第三方库的支持。

最初的想法

由于刚参加工作不久,对这些东西也都没有接触过,轮岗到某个部门需要做出点东西来(项目是什么还没情况,就要做出东西来,没办法硬着头皮想点子吧)。。。

本想做一个简单点的自动化测试的工具,但这项目的测试方法和测试用例暂时不能使用这种通用的测试手段(输入和输出都确定不了),从而作罢...

Python脚本实现集群检测和管理功能

那么做点什么东西,经常发现同事们问208谁用的?201谁用的?那IP是我的!!!你是不是把我得网线给拔掉了?242那机器到底是哪台?

突然间,春天来了,是不是可以做一个系统用来检测IP和记录设备的使用人,甚至可以按需要在某台设备上运行一个脚本或命令?把这个矮矬穷的想法和leader沟通过后,确认可以做,那么就开始吧!!!

设计思想

该系统的大概思想:

1.

要获得所有服务器的各种信息,需要在任意一台服务器上部署一个agent作为信息获取的节点,定时向管理服务器节点发送服务器信息数据。

2.

server作为综合管理节点,接收并储存agent提交的信息。

3.

为了方便使用,采用web页面的形式做展示。

Python脚本实现集群检测和管理功能

开发工具选择

1. 开发语言:python

之所以选择python,简单,第三方库丰富,不用造轮子

2. 数据库:mysql

简单、易用

3. webpy:web框架

入门简单、部署方便

4. bootstrap:前端框架

不要关心太多前端问题

5. paramiko:python库,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接

通过SSH方式连接agent服务器:远程运行命令、传输文件

6. scapy: python库,可用来发送、嗅探、解析和伪造网络数据包,这里用来扫描IP

7. MySQLdb: 连接mysql

8. shell 和 python脚本接口: 为其他人提供shell脚本的接口

经验分享

1. 前端对我来说是新东西,从来没弄过,页面的动画效果,脚本运行时的过渡都是需要考虑的,开始考虑利用倒计时,但是这个时间是不可控的,后来采用ajax来处理这个问题

2. agent要自动部署到每台机器,并可以通过server来控制刷新时间

3. 建立一个可扩展的表是非常重要的,而且一些重要的信息需要写入磁盘,在数据库失效的情况下,可以从磁盘获取数据

4. 数据库的连接,如果长时间没有操作的话会超时,要考虑到

... ...

项目结构--webpy

1. website.py为webpy的主程序,设置了url映射

2. model.py为webpy的url映射类,处理请求和返回

3. static中存放静态资源

4. scripts用来存放处理的脚本,这里起的名字有些问题

Python脚本实现集群检测和管理功能

连接数据库

 使用MyQSLdb连接mysql,在这里我没有使用webpy提供的数据库接口,而是自己封装了一套

ssh远程连接服务器

 paramiko实现ssh连接、与数据传输、执行命令和脚本

def executecmd(cmd, host, port=22, user='root', passwd='root'):

    try:

        s = paramiko.SSHClient()

        s.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    s.connect(host, port, user, passwd, timeout = 10)

    except Exception as e:

        s.close()

        print e

        print 'connet error...'

        return
    try:

        stdin,stdout,stderr=s.exec_command(cmd)

        #print 'Host: %s......' %host

        res = stdout.readlines()

    except Exception as e:

        print 'exec_commmand error...'

    s.close()

    return res
def executefile(file, host, port=22, user='root', passwd='root'):

    try:

        s = paramiko.SSHClient()

        s.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    s.connect(host, port, user, passwd,timeout=5)

        t = paramiko.Transport((host, port))

        t.connect(username=user, password=passwd)

        sftp =paramiko.SFTPClient.from_transport(t)

    except Exception as e:

        s.close()

        print e

        print 'connet error...'

        return ''
    try:

        filename = os.path.basename(file)

        if filename.find('.sh') >= 0:

            sftp.put(path+'/'+file, '/tmp/tmp_test.sh')

            stdin,stdout,stderr=s.exec_command('sh /tmp/tmp_test.sh 2>/dev/null', timeout=5)

        else:

            sftp.put(path+'/'+file, '/tmp/tmp_test.py')

            stdin,stdout,stderr=s.exec_command('python /tmp/tmp_test.py', timeout=5)

        #stdin,stdout,stderr=s.exec_command('rm -rf /tmp/tmp_test* 2>/dev/null') 

        res = stdout.readlines()

        s.exec_command('rm -rf /tmp/tmp_test* 2>/dev/null') 

    except Exception as e:

        s.exec_command('rm -rf /tmp/tmp_test* 2>/dev/null') 

        print 'timeout error...'

        print e

        return ''

    return res

IP扫描

使用scapy进行IP扫描

def pro(ip, cc, handle):

    global dict

    dst = ip + str(cc)

    packet = IP(dst=dst, ttl=20)/ICMP()

    reply = sr1(packet, timeout=TIMEOUT)

    if reply:

        print reply.src,' is online'

        tmp = [1, reply.src]

        handle.write(reply.src + '\n')

        #handle.write(reply.src+" is online"+"\n")

 

def main():

    threads=[]

    ip = '192.168.1.1'

    s = 2

    e = 254

    f=open('ip.log','w')

    for i in range(s, e):

        t=threading.Thread(target=pro,args=(ip,i,f))

        threads.append(t)

    print "main Thread begins at ",ctime()

    for t in threads :

        t.start()

    for t in threads :

        t.join()

    print "main Thread ends at ",ctime()

批量添加ssh-key

home_dir = '/home/xx'

id_rsa_pub = '%s/.ssh/id_rsa.pub' %home_dir
if not  id_rsa_pub:

    print 'id_rsa.pub Does not exist!'

    sys.exit(0)
file_object = open('%s/.ssh/config' %home_dir ,'w')

file_object.write('StrictHostKeyChecking no\n')

file_object.write('UserKnownHostsFile /dev/null')

file_object.close()


def up_key(host,port,user,passwd):

    try:

        s = paramiko.SSHClient()

    s.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    s.connect(host, port, user, passwd)
        t = paramiko.Transport((host, port))

        t.connect(username=user, password=passwd, timeout=3)

        sftp =paramiko.SFTPClient.from_transport(t)
        print 'create Host:%s .ssh dir......' %host

        stdin,stdout,stderr=s.exec_command('mkdir ~/.ssh/')

        print 'upload id_rsa.pub to Host:%s......' %host

        sftp.put(id_rsa_pub, "/tmp/temp_key")

        stdin,stdout,stderr=s.exec_command('cat /tmp/temp_key >> ~/.ssh/authorized_keys && rm -rf /tmp/temp_key')

        print 'host:%s@%s auth success!\n' %(user, host)

        s.close()

        t.close()

    except Exception, e:

        #import traceback

        #traceback.print_exc()

        print 'connect error...'

        print 'delete ' + host  + ' from database...'

        delip(host)

        #delete from mysql****

        try:

            s.close()

            t.close()

        except:

            pass
Python 相关文章推荐
Python中实现对Timestamp和Datetime及UTC时间之间的转换
Apr 08 Python
Python中文件操作简明介绍
Apr 13 Python
使用Python编写简单的端口扫描器的实例分享
Dec 18 Python
python3实现TCP协议的简单服务器和客户端案例(分享)
Jun 14 Python
python利用lxml读写xml格式的文件
Aug 10 Python
django 常用orm操作详解
Sep 13 Python
对python的输出和输出格式详解
Dec 08 Python
django foreignkey(外键)的实现
Jul 29 Python
pytorch 在sequential中使用view来reshape的例子
Aug 20 Python
Django admin.py 在修改/添加表单界面显示额外字段的方法
Aug 22 Python
基于Python实现剪切板实时监控方法解析
Sep 11 Python
python如何写try语句
Jul 14 Python
Python守护进程(daemon)代码实例
Mar 06 #Python
Python类方法__init__和__del__构造、析构过程分析
Mar 06 #Python
Python列表生成器的循环技巧分享
Mar 06 #Python
Python装饰器使用示例及实际应用例子
Mar 06 #Python
Python迭代器和生成器介绍
Mar 06 #Python
Python __setattr__、 __getattr__、 __delattr__、__call__用法示例
Mar 06 #Python
Python比较文件夹比另一同名文件夹多出的文件并复制出来的方法
Mar 05 #Python
You might like
1982年日本摄影师镜头下的中国孩子 那无忧无虑的童年
2020/03/12 杂记
用缓存实现静态页面的测试
2006/12/06 PHP
ThinkPHP模板中判断volist循环的最后一条记录的验证方法
2014/07/01 PHP
PHP连接MSSQL2008/2005数据库(SQLSRV)配置实例
2014/10/22 PHP
一个经典实用的PHP图像处理类分享
2014/11/18 PHP
php生成图片缩略图的方法
2015/04/07 PHP
Zend Framework教程之配置文件application.ini解析
2016/03/10 PHP
PHP实现生成模糊图片的方法示例
2017/12/21 PHP
PDO::commit讲解
2019/01/27 PHP
BOOM vs RR BO3 第一场2.13
2021/03/10 DOTA
jQuery实现标题有打字效果的焦点图代码
2015/11/16 Javascript
微信小程序 九宫格实例代码
2017/01/21 Javascript
Bootstrap进度条实现代码解析
2017/03/07 Javascript
JavaScript变量基本使用方法实例分析
2019/11/15 Javascript
viewer.js一个强大的基于jQuery的图像查看插件(支持旋转、缩放)
2020/04/01 jQuery
[00:35]DOTA2上海特级锦标赛 MVP.Phx战队宣传片
2016/03/04 DOTA
[02:36]DOTA2上海特锦赛 回忆电竞生涯的重要瞬间
2016/03/25 DOTA
zbar解码二维码和条形码示例
2014/02/07 Python
深入理解Python中的super()方法
2017/11/20 Python
python回调函数中使用多线程的方法
2017/12/25 Python
Python 多线程C段扫描、检测 Ping扫描脚本的实现
2020/09/03 Python
PyCharm2020.3.2安装超详细教程
2021/02/08 Python
LA MER海蓝之谜美国官网:传奇面霜
2016/08/27 全球购物
瑞典网上购买现代和复古家具:Reforma
2019/10/21 全球购物
财务管理专业毕业生求职信范文
2013/09/21 职场文书
高中自我鉴定范文
2013/11/03 职场文书
最新创业融资计划书
2014/01/19 职场文书
党校个人自我鉴定范文
2014/03/28 职场文书
啦啦队口号大全
2014/06/16 职场文书
2015年档案室工作总结
2015/05/23 职场文书
2015大学迎新晚会策划书
2015/07/16 职场文书
成本低的5个创业项目:投资小、赚钱快
2019/08/20 职场文书
2019年消防宣传标语集锦
2019/11/21 职场文书
python_tkinter事件类型详情
2022/03/20 Python
vue router 动态路由清除方式
2022/05/25 Vue.js
插件导致ECharts被全量引入的坑示例解析
2022/09/23 Javascript