python(pexpect)简单的自动ssh脚本
安装python的pexpect模块
# apt-get install python-pip
# pip install pexpect
# vi ssh.py
按a或i进入编辑模式
#!/usr/bin/python
#/usr/bin/python
import pexpect
child=pexpect.spawn('ssh zhiming@10.0.0.22',timeout=5)
ssh_newkey='Are you sure you want to continue connecting'
Down='No route to host'
i=child.expect([ssh_newkey,'password:',pexpect.EOF,pexpect.TIMEOUT,Down]) (下面的0、1、2、3分别对应“[]”里的序列)
if i == 0:
child.sendline('yes')
child.sendline('123456')
child.sendline('exit')
if i == 1:
child.sendline('123456')
child.sendline('exit')
if i == 2:
f=open('/log/ssh/ssh.log','a')
f.write('10.0.0.22 ssh(nis) is Bad')
f.write('\n')
f.close()
if i == 3:
f=open('/log/ssh/ssh.log','a')
f.write('10.0.0.22 ssh(nis) is Bad')
f.write('\n')
f.close()
if i == 4:
f=open('/log/ssh/ssh.log','a')
f.write('10.0.0.22 ssh(nis) is down')
f.write('\n')
f.close()
child.interact()
child.close()
按Esc键退出编辑模式
:wq(保存并退出)
# python ssh.py
脚本解释:
1、如果第1次连接,输入yes,然后再输入密码,如果不是第1次连接,输入密码
2、EOF表示服务器(ip)不存在或非linux类,TIMEOUT表连接超时
3、如果如果找不到该服务器或连接超时,将信息追加写入/log/ssh/ssh.log(建议第1台覆盖,后面追加,r为读,w为写即覆盖,a为追加)
4、if的下面内容前要缩进一格
再配合bash脚本
# vi mvlog.sh (因为python里log文件名是死的,可以借助bash让其更灵活)
#!/bin/bash
Date=`date +%Y%m%d`
Date2=`date +%Y%m%d -d "1 day ago"`
Date3=`date +%Y%m%d -d "2 day ago"`
Ssh=/log/ssh
if [ -f $Ssh/ssh_$Date2.log ];then
/bin/rm -rf /log/ssh/ssh_$Date3.log
else
/bin/mv /log/ssh/ssh.log /log/ssh/ssh_$Date2.log
/usr/bin/touch /log/ssh/ssh.log
fi
:wq
# vi ssh.sh(这个主要根据log文件内容及更新时间判断有服务器报警并发邮件通知)
#!/bin/bash
Date=`date +%H:%M`
Hour=`date +%H`
Hourr=`date +%M`
Size=`/bin/ls -l /log/ssh/ | grep ssh.log | awk -F[:" "]+ '{print $5}'`
Hour2=`/bin/ls -l /log/ssh/ | grep ssh.log | awk -F[:" "]+ '{print $8}'`
Hour22=`/bin/ls -l /log/ssh/ | grep ssh.log | awk -F[:" "]+ '{print $9}'`
if [ $Size -ge "4" ] && [ $Hour = "$Hour2" ] && [ $Hourr = "$Hour22" ]
then
/bin/echo "time $Date" >> /log/ssh/ssh.log
/usr/bin/mail -s "Android ssh(nis) is bad at $Date" zhi.yang@ming.com < /log/ssh/ssh.log
/usr/bin/mail -s "Android ssh(nis) is bad" 13732525252@139.com < /log/ssh/ssh.log
fi
本文转自linux博客51CTO博客,原文链接http://blog.51cto.com/yangzhiming/1677036如需转载请自行联系原作者
yangzhimingg