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("查寻命令已执行成功,全部结果已保存在当前目录下!")

你可能感兴趣的:(python,网络工程,python)