一、安装easy_install工具
wget http://peak.telecommunity.com/dist/ez_setup.py
python ez_setup.py 安装easy_install工具(这个脚本会自动去官网搜索下载并安装)
python  ez_setup.py  -U setuptools  升级easy_install工具

二、安装pexpect
easy_install Pexpect

测试一下:
[root@OMS python]# python
Python 2.7.3rc1 (default, Nov  7 2012, 15:03:45)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pexpect
>>> import pxssh
>>>

ok已经安装完成。
三、写一个脚本给远程服务器发送命令,并返回结果。

脚本内容:

     
     
     
     
  1. #!/usr/bin/python 
  2. #2013-01-16 by larry 
  3. import pexpect 
  4. def login(port,user,passwd,ip,command): 
  5.     child=pexpect.spawn('ssh -p%s %s@%s "%s"' %(port,user,ip,command)) 
  6.     o='' 
  7.     try
  8.         i=child.expect(['[Pp]assword:','continue connecting (yes/no)?']) 
  9.         if i == 0:  
  10.             child.sendline(passwd) 
  11.         elif i == 1
  12.             child.sendline('yes'
  13.         else
  14.             pass 
  15.     except pexpect.EOF: 
  16.         child.close() 
  17.     else
  18.         o=child.read() 
  19.         child.expect(pexpect.EOF) 
  20.         child.close() 
  21.     return o 
  22.  
  23. hosts=file('hosts.list','r'
  24. for line in hosts.readlines(): 
  25.     host=line.strip("\n"
  26.     if host: 
  27.         ip,port,user,passwd,commands= host.split(":"
  28.         for command in commands.split(","): 
  29.             print "+++++++++++++++ %s run:%s ++++++++++++" % (ip,command), 
  30.             print login(port,user,passwd,ip,command)    
  31. hosts.close() 

使用方法:python scripts.py

host.list文件内容如下:

192.168.0.21:22999:root:123456:cat /etc/redhat-release,df -Th,whoami
192.168.0.21:22999:root:123456:cat /etc/redhat-release,df -Th,whoami

返回结果:
+++++++++++++++ 192.168.0.21 run:cat /etc/redhat-release ++++++++++++  
Red Hat Enterprise Linux Server release 4

+++++++++++++++ 192.168.0.21 run:df -Th ++++++++++++  
文件系统      类型    容量  已用 可用 已用% 挂载点
/dev/cciss/c0d0p6
              ext3    5.9G  4.4G  1.2G  80% /
/dev/cciss/c0d0p7
              ext3    426G  362G   43G  90% /opt
/dev/cciss/c0d0p5
              ext3    5.9G  540M  5.0G  10% /var
/dev/cciss/c0d0p3
              ext3    5.9G  4.1G  1.5G  74% /usr
/dev/cciss/c0d0p1
              ext3    487M   17M  445M   4% /boot
tmpfs        tmpfs    4.0G     0  4.0G   0% /dev/shm

+++++++++++++++ 192.168.0.21 run:whoami ++++++++++++  
root