- 論壇徽章:
- 0
|
原文參見:http://hi.baidu.com/smallfish_xy ... 5a86202cf53447.html
pexpect是python一個模塊,可以通過:easy_install pexpect 來安裝。
這里主要是用pexpect執(zhí)行ssh,查看遠(yuǎn)程uptime和df -h看硬盤狀況。
- #ssh_cmd.py
- #coding:utf-8
- import pexpect
- def ssh_cmd(ip, user, passwd, cmd):
- ssh = pexpect.spawn('ssh %s@%s "%s"' % (user, ip, cmd))
- r = ''
- try:
- i = ssh.expect(['password: ', 'continue connecting (yes/no)?'])
- if i == 0 :
- ssh.sendline(passwd)
- elif i == 1:
- ssh.sendline('yes')
- except pexpect.EOF:
- ssh.close()
- else:
- r = ssh.read()
- ssh.expect(pexpect.EOF)
- ssh.close()
- return r
- hosts = '''
- 192.168.0.12:smallfish:1234:df -h,uptime
- 192.168.0.13:smallfish:1234:df -h,uptime
- '''
- for host in hosts.split("\n"):
- if host:
- ip, user, passwd, cmds = host.split(":")
- for cmd in cmds.split(","):
- print "-- %s run:%s --" % (ip, cmd)
- print ssh_cmd(ip, user, passwd, cmd)
復(fù)制代碼
hosts數(shù)組格式是:主機IP:用戶名:密碼:命令 (多個命令用逗號, 隔開)
可以看出打印出相應(yīng)的結(jié)果了,可以拼成html發(fā)送mail看起來比較美觀些咯! |
|