python实现hp刀片ilo地址配置

shell实现hp刀片ilo地址配置 篇中有提到通过python来实现HP管理口的配置,没事写了段python实现的代码。大意也是通过pexpect模块来实现相应的配置,不过这段代码初写的时候是基于paramiko模块获取信息,并找到可用IP的,后面又写了一段通过pexpect实现自动交互输入的。真正的实现的时候并不需要paramiko部分的,不过懒得的代码整合和美化了,凑合着全部堆上来吧。代码如下:

#!/usr/bin/python
#-*- coding: utf-8 -*-
# code from www.361way.com <itybku@139.com>
import re,paramiko
import commands
def ssh2(ip,username,passwd,cmd):
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(ip,22,username,passwd,timeout=5)
        stdin,stdout,stderr = ssh.exec_command(cmd)
        return stdout.readlines()
        #print x.strip("\n")
        #print '%s\tOK\n'%(ip)
        ssh.close()
    except :
        print '%s\tError\n'%(ip)
def stdoutsplit(stdout,keywords):
   for line in  stdout:
      if line.find(keywords) != -1:
         return re.split(r': ',line)[1].strip('\n')
def iprange(ip,mask):
    ipaddr = ip.split('.')
    netmask = mask.split('.')
    cidr = sum([bin(int(x)).count('1') for x in netmask])
    net_start = [str(int(ipaddr[x]) & int(netmask[x]))
             for x in range(0,4)]
    end = int(netmask[3]) + 2**(32-cidr) - 1
    firstip = '.'.join(net_start)
    endip = '.'.join(ipaddr[0:3]) + '.' + str(end)
    return firstip + '\t' + endip
stdout = ssh2("10.105.10.45","admin","password","SHOW OA NETWORK")
oaip = stdoutsplit(stdout,'IPv4 Address:')
mask = stdoutsplit(stdout,'Netmask:')
gate = stdoutsplit(stdout,'Gateway Address:')
#print oaip,mask,gate
cmd ="fping -g " + iprange(oaip,mask)
status, output = commands.getstatusoutput(cmd)
print 'Available IP follows:'
print '*'*40
for line in  output.split('\n'):
    if line.find('unreachable') != -1:
       print line
print '*'*40
iloip = raw_input("please input the ilo ip: ")
bid = raw_input("please input the blade bay id: ")
setip="set ebipa server " + iloip + '\t' + mask + '\t' + bid
setgate="set ebipa server gateway " + gate + '\t' + bid
print setip
print setgate
#---------------------------------------------------------------------
from pexpect.pxssh import pxssh
s  = pxssh()
s.login('10.105.10.45','admin','password',original_prompt='>',auto_prompt_reset=False)
s.sendline("set ebipa server 10.105.10.58 255.255.255.0 13")
s.expect('bays\?')
s.sendline('YES')
#print s.before
s.expect('>')
print s.before
s.logout()

算个半成品吧,需要的功能代码里都有了,想实现shell里的功能,只是简单的修改下就成了。实际代码要不了这么多的,后面重新IP规划,给所有代片全配置上连续的IP,HP管理口本身也有autofill 功能,配置起来也比较快。使用脚本无非是练习下,同时也对管理口增强更多的内部了解。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注