netmiko单个或批量执行命令并保存结果

import pandas,netmiko,time

class Save_all(object):
	def __init__(self, device, command):
		self.device = device
		self.command = command
		self.result = pandas.read_excel("d:\\1.xlsx", sheet_name = "Sheet1")
		#读取对应的表格里面的记录
		
	def conn(self, host, username, password, port, pw):		
		sw1 = {"device_type": self.device, "host": host, 'username': username, "password": password, "port": port, "secret": pw}	
		connect = netmiko.ConnectHandler(**sw1)				
		output = connect.send_command(self.command, strip_prompt=False, strip_command=False)
		connect.disconnect()
		print(output)

		#把结果保存起来
		times = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
		result_out = output
		with open(times + ".txt", "w") as f:
			f.write(result_out)

	def read_one(self):
		host_ip = input("please your ip host: ").strip()
		for index,row in self.result.iterrows():
			if row["ip"] == host_ip:
				username = row[2]
				password = row[3]
				port = int(row[4])
				pw = row[5]					
				self.conn(host_ip,username,password,port,pw)
				break
		else:
			print("ip not exist!")
			
	def read_all(self):
		for index,row in self.result.iterrows():
			host = row[1]
			username = row[2]
			password = row[3]
			port = int(row[4])
			pw = row[5]
			self.conn(host,username,password,port,pw)
	
if __name__ == "__main__":
	print("选择设备系统型号:" + "\n" + "一、hp_comware" + "\n" + "二、cisco_ios" + "\n" + "三、ruijie_os" + "\n")	
	device = input("型号是(手输对应的英文): ").strip()
	commad = input("请输入查寻命令: ").strip()
	choose = input("请选择是单个设备执行还是表格里的全部设备都执行(one/all): ").strip()	
	
	if choose == "one":			
		obj_save1 = Save_all(device, commad)
		obj_save1.read_one()
	elif choose == "all":
		obj_save1 = Save_all(device, commad)
		obj_save1.read_all()		
	else:
		print("your error! choose one or all")
		
	print("查寻命令已执行成功,全部结果已保存在当前目录下!")
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

项目工程师余工

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值