時(shí)間:2015-06-28 00:00:00 來源:IT貓撲網(wǎng) 作者:網(wǎng)管聯(lián)盟 我要評論(1)
一、Pexpect簡介
Pexpect 是一個(gè)用來啟動(dòng)子程序并對其進(jìn)行自動(dòng)控制的 Python 模塊,它可以用來和像 ssh、ftp、passwd、telnet 等命令行程序進(jìn)行自動(dòng)交互。本文介紹 Pexpect 的主要用法和在實(shí)際應(yīng)用中的注意點(diǎn)。 Python 語言的愛好者,系統(tǒng)管理人員,部署及測試人員都能使用 Pexpect 在自己的工作中實(shí)現(xiàn)與命令行交互的自動(dòng)化。
具體可以參考http://www.noah.org/wiki/Pexpect#Download_and_Installation
下載地址 http://pexpect.sourceforge.net/pexpect-2.3.tar.gz
今天介紹的內(nèi)容就是利用pexpect來實(shí)現(xiàn)的遠(yuǎn)程多服務(wù)器的管理。
二、Python腳本
以下是python的源代碼。程序的大概過程是使用pexpect的ssh命令循環(huán)登陸到遠(yuǎn)程服務(wù)器上,將服務(wù)和進(jìn)程的運(yùn)行情況紀(jì)錄到臨時(shí)文件中,然后再從文件中獲取服務(wù)和進(jìn)程的運(yùn)行情況,如果服務(wù)或進(jìn)程異常停止,程序則將其重新啟動(dòng),所有服務(wù)器的運(yùn)行狀況都將紀(jì)錄在日志文件中。
代碼
# coding=utf-8
#!/usr/bin/env python
import pexpect
import getpass, os
import string
import time
from datetime import datetime, date
ssh_newkey = 'Are you sure you want to continue connecting (yes/no)?'
hosts = []
hosts.append('xx.xx.xx.xx')
user = 'user'
password = 'pwd'
logFile = '/tmp/pexpect-2.3/monitor.log'
def restartService(host, user, password, service):
child = pexpect.spawn('ssh %s@%s' %(user, host))
i = child.expect([pexpect.TIMEOUT, ssh_newkey, 'password: '])
if i == 0: # Timeout
return None
if i == 1:
child.sendline('yes')
child.sendline(password)
child.sendline('sudo service %s restart' %service)
j = child.expect(['Password: ', '$', '#'])
if j == 0:
child.sendline(password)
if j == 1:
child.sendline(password)
time.sleep(30)
child.sendline('exit')
fout = file(logFile, 'a')
child.logfile_read = fout
return child
# restart one process
def restartProcess(host, user, password):
child = pexpect.spawn('ssh %s@%s' %(user, host))
i = child.expect([pexpect.TIMEOUT, ssh_newkey, 'password: '])
if i == 0: # Timeout
return None
if i == 1:
child.sendline('yes')
child.sendline(password)
child.sendline('sudo su')
j = child.expect(['Password: ', '$', '#'])
if j == 0:
child.sendline(password)
if j == 1:
child.sendline(password)
child.sendline('cd /processlocation/bin')
child.sendline('./processName.sh &')
time.sleep(20)
child.sendline('exit')
child.sendline('exit')
fout = file(logFile, 'a')
child.logfile_read = fout
return child
# log process' status to file tmpProc.txt
def logProcessInfo(host, user, password, process):
child = pexpect.spawn('ssh %s@%s' %(user, host))
i = child.expect([pexpect.TIMEOUT, ssh_newkey, 'password: '])
if i == 0: # Timeout
return None
if i == 1:
child.sendline('yes')
child.sendline(password)
child.sendline('ps -ef|grep %s' %process)
child.sendline('exit')
fout = file('tmpProc.txt', 'w')
child.logfile_read = fout
return child
#p#副標(biāo)題#e#
# get process' id from file tmpProc.txt
def getProcessId():
val = ''
f = file('tmpProc.txt', 'r')
f.seek(0)
while True:
line = f.readline()
if line.find('processName') > 0:
index = line.find(' ')
subline = line[index+1:]
while True:
if subline[0] == ' ':
index = subline.find(' ')
subline = subline[index+1:]
else:
break
index2 = subline.find(' ')
number = subline[:index2]
val = number
if len(line) == 0:
break
f.close()
return val
# log service's status to file tmpServ.txt
def logServiceInfo(host, user, password, serviceName):
child = pexpect.spawn('ssh %s@%s' %(user, host))
i = child.expect([pexpect.TIMEOUT, ssh_newkey, 'password: '])
if i == 0: # Timeout
return None
if i == 1:
child.sendline('yes')
child.sendline(password)
child.sendline('service %s status' %serviceName)
child.sendline('exit')
fout = file('tmpServ.txt', 'w')
child.logfile_read = fout
return child
# get servicee's status of start or stop from file tmpServ.txt
def hasServiceStart():
val = True
f = file('tmpServ.txt', 'r')
f.seek(0)
while True:
line = f.readline()
if line.find('stop') > 0:
val = False
if len(line) == 0:
break
f.close()
return val
def logOperation(content):
f = file(logFile, 'a')
f.write(content)
f.close()
current = datetime.now()
logOperation('\n\n***')
logOperation(current.strftime("%a %b %d %H:%M:%S %Y") + '\n')
for host in hosts:
processChild = logProcessInfo(host, user, password, 'processName')
processChild.expect(pexpect.EOF)
processId = getProcessId()
if processId == '':
logOperation('processName on ' + host + ' has been stopped\n')
processChild = restartProcess(host, user, password)
processChild.expect(pexpect.EOF)
else:
logOperation('processName on ' + host + ' is ok\n')
serviceChild = logServiceInfo(host, user, password, 'serviceName')
serviceChild.expect(pexpect.EOF)
if hasServiceStart():
logOperation('serviceName on ' + host + ' is ok\n')
else:
logOperation('serviceName on ' + host + ' has been stopped\n')
serviceChild = restartService(host, user, password, 'serviceName')
serviceChild.expect(pexpect.EOF)
print 'mission accomplished'
三、通過配置crond使腳本能夠定時(shí)執(zhí)行
1)登陸到腳本所在的linux服務(wù)器上
2)運(yùn)行命令crontab -e
說明:系統(tǒng)默認(rèn)的編輯器是VIM,如果不是請加上以下shell:
$EDITOR=vi
$export EDITOR
3)添加0 * * * * python /tmp/pexpect-2.3/autoMonitor.py
4)重起crond
cd /etc/init.d
./crond restart
這樣每個(gè)小時(shí)0分的時(shí)候105上會(huì)自動(dòng)運(yùn)行autoMonitor.py腳本
關(guān)鍵詞標(biāo)簽:crond,Python腳本,lin
相關(guān)閱讀
熱門文章 安裝紅帽子RedHat Linux9.0操作系統(tǒng)教程 Tomcat9.0如何安裝_Tomcat9.0環(huán)境變量配置方法 多種操作系統(tǒng)NTP客戶端配置 Linux操作系統(tǒng)修改IP
人氣排行 Linux下獲取CPUID、硬盤序列號與MAC地址 dmidecode命令查看內(nèi)存型號 linux tc實(shí)現(xiàn)ip流量限制 安裝紅帽子RedHat Linux9.0操作系統(tǒng)教程 linux下解壓rar文件 lcx.exe、nc.exe、sc.exe入侵中的使用方法 Ubuntu linux 關(guān)機(jī)、重啟、注銷 命令 查看linux服務(wù)器硬盤IO讀寫負(fù)載