Python腳本實現(xiàn)集群檢測和管理功能
場景是這樣的:一個生產(chǎn)機房,會有很多的測試機器和生產(chǎn)機器(也就是30臺左右吧),由于管理較為混亂導(dǎo)致了哪臺機器有人用、哪臺機器沒人用都不清楚,從而產(chǎn)生了一個想法--利用一臺機器來管理所有的機器,記錄設(shè)備責(zé)任人、設(shè)備使用狀態(tài)等等信息....那么,為什么選擇python,python足夠簡單并且擁有豐富的第三方庫的支持。
最初的想法
由于剛參加工作不久,對這些東西也都沒有接觸過,輪崗到某個部門需要做出點東西來(項目是什么還沒情況,就要做出東西來,沒辦法硬著頭皮想點子吧)。。。
本想做一個簡單點的自動化測試的工具,但這項目的測試方法和測試用例暫時不能使用這種通用的測試手段(輸入和輸出都確定不了),從而作罷...
那么做點什么東西,經(jīng)常發(fā)現(xiàn)同事們問208誰用的?201誰用的?那IP是我的?。?!你是不是把我得網(wǎng)線給拔掉了?242那機器到底是哪臺?
突然間,春天來了,是不是可以做一個系統(tǒng)用來檢測IP和記錄設(shè)備的使用人,甚至可以按需要在某臺設(shè)備上運行一個腳本或命令?把這個矮矬窮的想法和leader溝通過后,確認可以做,那么就開始吧?。?!
設(shè)計思想
該系統(tǒng)的大概思想:
1. 要獲得所有服務(wù)器的各種信息,需要在任意一臺服務(wù)器上部署一個agent作為信息獲取的節(jié)點,定時向管理服務(wù)器節(jié)點發(fā)送服務(wù)器信息數(shù)據(jù)。
2. server作為綜合管理節(jié)點,接收并儲存agent提交的信息。
3. 為了方便使用,采用web頁面的形式做展示。
開發(fā)工具選擇
1. 開發(fā)語言:python
之所以選擇python,簡單,第三方庫豐富,不用造輪子
2. 數(shù)據(jù)庫:mysql
簡單、易用
3. webpy:web框架
入門簡單、部署方便
4. bootstrap:前端框架
不要關(guān)心太多前端問題
5. paramiko:python庫,遵循SSH2協(xié)議,支持以加密和認證的方式,進行遠程服務(wù)器的連接
通過SSH方式連接agent服務(wù)器:遠程運行命令、傳輸文件
6. scapy: python庫,可用來發(fā)送、嗅探、解析和偽造網(wǎng)絡(luò)數(shù)據(jù)包,這里用來掃描IP
7. MySQLdb: 連接mysql
8. shell 和 python腳本接口: 為其他人提供shell腳本的接口
經(jīng)驗分享
1. 前端對我來說是新東西,從來沒弄過,頁面的動畫效果,腳本運行時的過渡都是需要考慮的,開始考慮利用倒計時,但是這個時間是不可控的,后來采用ajax來處理這個問題
2. agent要自動部署到每臺機器,并可以通過server來控制刷新時間
3. 建立一個可擴展的表是非常重要的,而且一些重要的信息需要寫入磁盤,在數(shù)據(jù)庫失效的情況下,可以從磁盤獲取數(shù)據(jù)
4. 數(shù)據(jù)庫的連接,如果長時間沒有操作的話會超時,要考慮到
... ...
項目結(jié)構(gòu)--webpy
1. website.py為webpy的主程序,設(shè)置了url映射
2. model.py為webpy的url映射類,處理請求和返回
3. static中存放靜態(tài)資源
4. scripts用來存放處理的腳本,這里起的名字有些問題
連接數(shù)據(jù)庫
使用MyQSLdb連接mysql,在這里我沒有使用webpy提供的數(shù)據(jù)庫接口,而是自己封裝了一套
ssh遠程連接服務(wù)器
paramiko實現(xiàn)ssh連接、與數(shù)據(jù)傳輸、執(zhí)行命令和腳本
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
相關(guān)文章
Django中STATIC_ROOT和STATIC_URL及STATICFILES_DIRS淺析
這篇文章主要給大家介紹了關(guān)于Django中STATIC_ROOT和STATIC_URL及STATICFILES_DIRS的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起看看吧2018-05-05python opencv圓、橢圓與任意多邊形的繪制實例詳解
在本篇文章里小編給大家整理的是關(guān)于python-opencv-圓、橢圓與任意多邊形的繪制內(nèi)容,需要的朋友們可以學(xué)習(xí)參考下。2020-02-02淺析Django 接收所有文件,前端展示文件(包括視頻,文件,圖片)ajax請求
這篇文章主要介紹了Django 接收所有文件,前端展示文件(包括視頻,文件,圖片)ajax請求,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值 ,需要的朋友可以參考下2020-03-03Python?Pipeline處理數(shù)據(jù)工作原理探究
如果你是一個Python開發(fā)者,你可能聽過"pipeline"這個術(shù)語,但?pipeline?到底是什么,它又有什么用呢?在這篇文章中,我們將探討?Python?中的?pipeline?概念,它們是如何工作的,以及它們?nèi)绾螏椭憔帉懜逦?、更高效的代碼2024-01-01