1 Star 0 Fork 1

烈马青葱 / python_Device

forked from Ricky / python_Device 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
02.huawei_Config_SSH.py 3.43 KB
一键复制 编辑 原始数据 按行查看 历史
Ricky 提交于 2019-07-31 21:41 . 1
# -*- coding: utf-8 -*-
from netmiko import ConnectHandler
import netmiko
from datetime import datetime
import time
import os
import csv
# print('这是一个成功的登陆脚本')
def main():
Red = csv.reader(open('ip.csv', 'r'))
# print(Red)
host_list = []
for item in Red:
# print(item)
host_list.append(item)
pass
# print (host_list)
i = 1
for device in host_list:
print(device)
Host = '{}'.format(device[0])
print('设备IP:', Host)
Username = '{}'.format(device[1])
# print('登陆用户名:', Username)
Password = '{}'.format(device[2])
# print('登陆密码:', Password)
huawei_Device = {'device_type': 'huawei','ip' :'{}'.format(device[0]),'username':'{}'.format(device[1]) ,'password': '{}'.format(device[2]), 'port': '22'}
print(huawei_Device)
time.sleep(1)
# return huawei_Device
all_devices = [huawei_Device]
start_time = datetime.now()
print ('>>>>>>>>>>>>>开始相关命令输入,开始时间:', start_time,'<<<<<<<<<<<<<<<<<')
print(all_devices)
#下面这两条命令,是把所有配置文件放到(iosv_l2_config.txt)这个文件里面,一行一条命令,可以一直接执行
with open ('huawei_config.txt') as f:
lines = f.read().splitlines()
for devices in all_devices:
net_connect = ConnectHandler(**devices)
output = net_connect.send_config_set (lines)
# 上面这条命令发送的是命令合集。也可以使用下面命令一条一条的发;
# print(net_connect)
#下面是发送命令集合,有部分命令可能是没有办法放到配置文件里面,需要动态获取的就可以放在这里面进行
config_commands = [
'hwtacacs-server template tac-aaa',
'hwtacacs-server source-ip {}'.format(device[0]),
]
AAA = net_connect.send_config_set(config_commands)
print('输出上面输入的命令:',AAA)
# output = net_connect.send_command("dis cu")
print (output)
#下面是获取到设备的名称(hostname)
find_hostname = net_connect.find_prompt()
# print(find_hostname)
#下面是获取到设备名称后多了一个<> 号,把这个<>号进行替换
hostname1 = find_hostname.replace('<',"")
hostname2 = hostname1.replace('>',"")
# print(hostname2)
# print ('设备名称:', hostname)
#获取当前时间,(本地电脑时间)
timez = (time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime()))
# print(timez)
#存放配置文件的路径和文件名(设备名+IP+时间)
path = 'E:/PJ/python_Device/huawei_config/'
names = '{}_{}_{}.py'.format(hostname2, device[0], timez)
file_name = path + names
print(file_name)
if_pash = os.path.exists(path)
# print(if_pash)
if not if_pash:
print('保存目录不存在,新建', path, '目录成功')
os.mkdir(path)
else:
print('目录已经存在', path, '继续进行')
with open(file_name,"w") as f:
read_data = f.write(output)
f.close()
# output = net_connect.send_command("cisco")
print ("\n>>>>>>>>> 设备类型: {}, 已经配置了第%d台设备 <<<<<<<<<".format(huawei_Device['device_type']) %i)
end_time = datetime.now()
print (">>>>>>>>>>>>>所有命令执行完毕,结束时间:", end_time,'<<<<<<<<<<<<')
total_time = end_time - start_time
print ('总共耗时:', total_time)
i+= 1
main()
# print(xxx)
Python
1
https://gitee.com/jielonlfx/python_Device.git
git@gitee.com:jielonlfx/python_Device.git
jielonlfx
python_Device
python_Device
master

搜索帮助