時間:2015/6/28來源:IT貓撲網(wǎng)作者:網(wǎng)管聯(lián)盟我要評論(0)
一、Pexpect簡介
Pexpect 是一個用來啟動子程序并對其進行自動控制的 python 模塊,它可以用來和像 ssh、ftp、passwd、telnet 等命令行程序進行自動交互。本文介紹 Pexpect 的主要用法和在實際應(yīng)用中的注意點。 Python 語言的愛好者,系統(tǒng)管理人員,部署及測試人員都能使用 Pexpect 在自己的工作中實現(xiàn)與命令行交互的自動化。
具體可以參考https://www.noah.org/wiki/Pexpect#Download_and_Installation
下載地址 https://pexpect.sourceforge.net/pexpect-2.3.tar.gz
今天介紹的內(nèi)容就是利用pexpect來實現(xiàn)的遠程多服務(wù)器的管理。
二、Python腳本
以下是python的源代碼。程序的大概過程是使用pexpect的ssh命令循環(huán)登陸到遠程服務(wù)器上,將服務(wù)和進程的運行情況紀(jì)錄到臨時文件中,然后再從文件中獲取服務(wù)和進程的運行情況,如果服務(wù)或進程異常停止,程序則將其重新啟動,所有服務(wù)器的運行狀況都將紀(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使腳本能夠定時執(zhí)行
1)登陸到腳本所在的linux服務(wù)器上
2)運行命令crontab -e
說明:系統(tǒng)默認的編輯器是VIM,如果不是請加上以下shell:
$EDITOR=vi
$export EDITOR
3)添加0 * * * * python /tmp/pexpect-2.3/autoMonitor.py
4)重起crond
cd /etc/init.d
./crond restart
這樣每個小時0分的時候105上會自動運行autoMonitor.py腳本
關(guān)鍵詞標(biāo)簽:crond,Python腳本,lin
相關(guān)閱讀
熱門文章 安裝紅帽子RedHat Linux9.0操作系統(tǒng)教程使用screen管理你的遠程會話GNU/Linux安裝vmware如何登錄linux vps圖形界面 Linux遠程桌面連
人氣排行 Linux下獲取CPUID、硬盤序列號與MAC地址linux tc實現(xiàn)ip流量限制dmidecode命令查看內(nèi)存型號linux下解壓rar文件安裝紅帽子RedHat Linux9.0操作系統(tǒng)教程Ubuntu linux 關(guān)機、重啟、注銷 命令lcx.exe、nc.exe、sc.exe入侵中的使用方法查看linux服務(wù)器硬盤IO讀寫負載