免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 7151 | 回复: 1

pexpect通过ssh执行远程命令 [复制链接]

论坛徽章:
0
发表于 2009-08-17 15:50 |显示全部楼层
原文参见:http://hi.baidu.com/smallfish_xy ... 5a86202cf53447.html

pexpect是python一个模块,可以通过:easy_install pexpect 来安装。

这里主要是用pexpect执行ssh,查看远程uptime和df -h看硬盘状况。

  1. #ssh_cmd.py
  2. #coding:utf-8

  3. import pexpect

  4. def ssh_cmd(ip, user, passwd, cmd):
  5.     ssh = pexpect.spawn('ssh %s@%s "%s"' % (user, ip, cmd))
  6.     r = ''
  7.     try:
  8.         i = ssh.expect(['password: ', 'continue connecting (yes/no)?'])
  9.         if i == 0 :
  10.             ssh.sendline(passwd)
  11.         elif i == 1:
  12.             ssh.sendline('yes')
  13.     except pexpect.EOF:
  14.         ssh.close()
  15.     else:
  16.         r = ssh.read()
  17.         ssh.expect(pexpect.EOF)
  18.         ssh.close()
  19.     return r

  20. hosts = '''
  21. 192.168.0.12:smallfish:1234:df -h,uptime
  22. 192.168.0.13:smallfish:1234:df -h,uptime
  23. '''

  24. for host in hosts.split("\n"):
  25.     if host:
  26.         ip, user, passwd, cmds = host.split(":")
  27.         for cmd in cmds.split(","):
  28.             print "-- %s run:%s --" % (ip, cmd)
  29.             print ssh_cmd(ip, user, passwd, cmd)
复制代码


hosts数组格式是:主机IP:用户名:密码:命令 (多个命令用逗号, 隔开)
可以看出打印出相应的结果了,可以拼成html发送mail看起来比较美观些咯!

论坛徽章:
0
发表于 2009-08-18 14:12 |显示全部楼层
借鉴了
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP