crond运行python脚本实现多台linux服务器的监控

  一、pexpect简介

  pexpect 是一个用来启动子程序并对其进行自动控制的 python 模块,它可以用来和像 ssh、ftp、passwd、telnet 等命令行程序进行自动交互。本文介绍 pexpect 的主要用法和在实际应用中的注意点。 python 语言的爱好者,系统管理人员,部署及测试人员都能使用 pexpect 在自己的工作中实现与命令行交互的自动化。

  具体可以参考http://www.noah.org/wiki/pexpect#download_and_installation

  下载地址 http://pexpect.sourceforge.net/pexpect-2.3.tar.gz

  今天介绍的内容就是利用pexpect来实现的远程多服务器的管理。

  二、python脚本

  以下是python的源代码。程序的大概过程是使用pexpect的ssh命令循环登陆到远程服务器上,将服务和进程的运行情况纪录到临时文件中,然后再从文件中获取服务和进程的运行情况,如果服务或进程异常停止,程序则将其重新启动,所有服务器的运行状况都将纪录在日志文件中。

  代码

  # 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

[1] [2] 下一页

发表评论