OOP案例
python">import netmiko,timeclass Network_ssh(object):def __init__(self, device, host, username, password, port, command):self.device = deviceself.host = hostself.username = usernameself.password = passwordself.port = portself.command = commanddef connect_to_sw(self):self.conn = { "device_type": self.device,"host": self.host,"username": self.username,"password": self.password,"port": self.port}return self.conndef handler_conn(self):self.connect_to_sw()self.connect = netmiko.ConnectHandler(**self.conn)self.connect.config_mode()#相当于执行了system或conf t命令self.command2 = ["inter vlan 30", "ip add 192.168.3.1 24"]self.connect.send_config_set(self.command2)#send_config_set 取消了分屏,执行了system-vie,再执行命令。self.connect.save_config()#相当于wr或save保存配置self.output = self.connect.send_command("dis ip int br", strip_prompt=False, strip_command=False)#send_comman里面的值变量不能是列表,必须是字符查寻命令。#把传入的变量命令给执行了print(self.output) def write_txt(self):self.handler_conn() #把结果保存起来self.times = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())self.result_out = self.outputwith open(self.times + ".txt", "w") as f:f.write(self.result_out)def down_conn(self):self.handler_conn()self.connect.disconnect() #关闭handler处理 if __name__ == "__main__":print("please choose device:" + "\n" + "1:hp_comware" + "\n" + "2:cisco_ios" + "\n" + "3:ruijie_os" + "\n")device = input("device is: ").strip()host = input("login ip_address is: ").strip()username=input("login username is: ").strip()password = input("login passwd is: ").strip()port = input("device ssh port is: ").strip() command = input("input commend is: ").strip()obj_ssh = Network_ssh(device, host, username, password, port, command)obj_ssh.handler_conn()obj_ssh.write_txt()obj_ssh.down_conn()
多线程案例
python">import threading
import time# 第一个循环
def loop1():for i in range(5):print("Loop 1: ", i)time.sleep(1)# 第二个循环
def loop2():for i in range(5):print("Loop 2: ", i)time.sleep(0.5)# 创建两个线程并运行
thread1 = threading.Thread(target=loop1)
thread2 = threading.Thread(target=loop2)
thread1.start()
thread2.start()
thread1.join()
thread2.join()