python脚本实现集群检测和管理

python脚本实现集群检测和管理

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

最初的想法

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

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

  

  

  那么作点什么东西,常常发现同事们问208谁用的?201谁用的?那IP是个人!!!你是否是把我得网线给拔掉了?242那机器究竟是哪台?web

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

设计思想

  该系统的大概思想:sql

  1.  要得到全部服务器的各类信息,须要在任意一台服务器上部署一个agent做为信息获取的节点,定时向管理服务器节点发送服务器信息数据。shell

  2.  server做为综合管理节点,接收并储存agent提交的信息。数据库

  3.  为了方便使用,采用web页面的形式作展现。bootstrap

  

开发工具选择

  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用来存放处理的脚本,这里起的名字有些问题 

    

 

  链接数据库

    使用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
View Code

  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()
View Code

  批量添加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
View Code

 

知识共享许可协议
本做品采用 知识共享署名-非商业性使用-相同方式共享 3.0 未本地化版本许可协议进行许可。欢迎转载,请注明出处:
转载自: cococo点点 http://www.cnblogs.com/coder2012
相关文章
相关标签/搜索