python登陆华为交换机配置snmp

暗黄色的天际中像燃着一团百年都没有澌灭的野火,它肆无忌惮的吞噬着天间彩云,仿佛地狱使者受到差遣,来破坏天际的和谐。

我们需要做的事情基本上有三个,第一,读取excel文件获取相应的位置信息和ip地址信息;第二,登陆交换机执行命令;第三,如果有交换机没有配置成功可以捕获到这个ip以备后续分析。针对这三个问题我进行了如下的测试:

1. python读取excel文件

#encoding:utf-8
import xlrd

def read_excel():
    
    #打开问文件
    workbook = xlrd.open_workbook(r'message.xlsx')

    #获取所有sheet
    print workbook.sheet_names()
    sheet1_name = workbook.sheet_names()[0]

    #获取指定sheet
    sheet1 = workbook.sheet_by_index(0)
    sheet1 = workbook.sheet_by_name('Sheet1')

    #输出sheet名,行数,列数
    print sheet1.name,sheet1.nrows,sheet1.ncols

    #输出整行整列内容
    rows = sheet1.row_values(0)
    cols = sheet1.col_values(1)
    print rows
    print cols

    #获取指定单元格内容
    print sheet1.cell(0,0).value
    print sheet1.cell_value(0,0)
    print sheet1.row(1)[0].value

    #获取单元格数据类型
    print sheet1.cell(0,0).ctype

if __name__ == '__main__':
    read_excel()

这是xlrd库的应用,上面是通过这个库进行excel进行读取的一些简单测试,不过这些测试足够我们的目标脚本使用。

2. python登陆交换机

#encoding:utf-8
import paramiko

readGroup = "000000"
writeGroup = "1111111"
udpDomain = "192.168.3.101"
contact = "Mr.huajiao238-QQ:1032601165"
location = "F2-R110"

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.168.3.201',22,'huajiao238','huajiao238', allow_agent=False, look_for_keys=False)
stdin,stdout,stderr = ssh.exec_command('display current-configuration | include ssh')
print stdout.read()
def deploy():

def main():

if __name__ == '__main__':
    main()

这个小脚本是通过paramiko库进行ssh登陆,通过exec_command()执行命令,但是exec_command()无法连续执行多条命令,最后的脚本中我们使用的是invoke_shell()返回的ssh命令行的对象调用sendall()方法进行执行命令。

3. 实现批量配置snmp

#encoding:utf-8

#基本思路:
#通过read_excel()读取表格中的数据
#将读取到命令通过make_code()整合到命令中
#main函数中for循环来逐一读取交换机IP地址和位置信息
#并将ip地址存放入数组中将位置信息
#调用log_switch()登陆交换机进行配置

import paramiko
import xlrd
import time

#读取相关文件
def read_excel():

    print '[*]reading excel...'

    #打开文件
    workbook = xlrd.open_workbook(r'message.xlsx')
    #通过sheet名称确定sheet
    sheet1 = workbook.sheet_by_name('Sheet1')
    #获取列内容
    col0 = sheet1.col_values(0)
    col1 = sheet1.col_values(1)
    #去除字段名
    ip_list = col0[1:]
    location_list = col1[1:]

    return ip_list,location_list


def make_code(location_list):

    print '[*]making shell code...'
    shell_code_list = []

    for ip_address in location_list:
        shell_code = [
        'n',
        'system-view',
        'snmp-agent community read ci huajiao238',
        'snmp-agent community write ci huajiao238',
        'snmp-agent sys-info contact Mr.shiyan-QQ:1032601165',
        'snmp-agent sys-info location '+ip_address,
        'snmp-agent sys-info version v2c',
        'snmp-agent target-host trap address udp-domain 192.168.1.101 udp-port 5000 params securityname public',
        'quit',
        'save',
        'Y'
        ]
        shell_code_list.append(shell_code)

    return shell_code_list

#登陆交换机部署snmp信息
def deploy(ip,shell_code,error_list):

    try:
        #交换机账号密码
        username = 'huajiao238'
        password = 'huajiao238'

        #登陆获取会话
        print '[*]logging:'+ip
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(ip,22,username,password,allow_agent=False,look_for_keys=False)
        ssh_shell = ssh.invoke_shell()

        #配置
        print '[*]deploying at:'+ip
        for i in range(0,len(shell_code)):
            #print shell_code[i]
            res = ssh_shell.sendall(shell_code[i]+'\n')
            #time.sleep(float(1))
        print '[+]Finished it.'
        ssh.close()
    #输出错误
    except Exception as e:
        error_list.append(ip)
        print '[-]error: '+ ip
        print e

def main():

    #定义错误列表,将未配置成功的ipappend进去
    error_list = []
    
    #ip_list是通过excel文件中获取到的交换机IP地址
    #location_list是通过excel中获取到的交换机位置信息
    ip_list,location_list = read_excel()

    #shell_code_list是将excel表中读取到的信息整合到命令中
    shell_code_list = make_code(location_list)

    #登陆配置
    for i in range(0,len(ip_list)):
        result = deploy(ip_list[i],shell_code_list[i],error_list)
    print '[*]Ok, well done.'

    #输出配置失败的ip地址
    if error_list:
        print '[!]Error ips are as follow:'
        for ip in  error_list:
            print '[!]-->'+ip

if __name__ == '__main__':
    main()

基本上就是这样,整体比较顺利,实现也还好,最好在批量发送命令之间有一定的间歇,不然容易出现socket wrong报错,其实可以通过多线程进行优化一下,等有时间优化一下再做升级。

4. 运行结果

之前一直觉得自己之前学的东西有点儿乱,这个接触一点,那个接触一点,但是我相信日后我所学习的东西都会多多少少在我的生活中或是我的工作中有所影响,最后分一句话,我觉得说的挺对,学习的过程是痛苦的,而未来有一天你需要它的时候用得心应手,这才是快乐的时候。

本文python登陆华为交换机配置snmp到此结束。坚强,不是应对悲伤不流一滴泪,而是擦干眼泪后微笑着应对以后的生活。小编再次感谢大家对我们的支持!

标签: python snmp