來源:公眾號【網絡技術干貨圈】
作者:圈圈
ID:wljsghq
實驗拓撲:
cloud連接本機,ip地址為192.168.56.1,五臺交換機的配置的地址為192.168.1.11~55。現在通過paramiko,ssh進入五臺設備,并且在五臺設備上分別創建vlan10-vlan20這11個VLAN。
版本:python3.9
實驗步驟:
一、ssh配置:
##創建秘鑰 [sw2]dsalocal-key-paircreate ##配置SSH認證類型(密碼/其他) [sw2]sshuserprinauthentication-typepassword [sw2]sshuserprinservice-typestelnet [sw2]stelnetserverenable ##配置認證模式 [sw2]user-interfacevty04 [sw2-ui-vty0-4]authentication-modeaaa//配置認證模式 [sw2-ui-vty0-4]protocolinboundssh//允許ssh連接虛擬終端 ##配置本地用戶信息 [sw2]aaa [sw2-aaa]local-userprinpasswordcipherHuawei@123 [sw2-aaa]local-userprinprivilegelevel15 [sw2-aaa]local-userprinservice-typessh
二、python腳本:
importparamiko importtime importgetpass #使用input函數,輸入SSH的用戶名 username=input('Username:') #通過getpass()函數接收密碼,密碼是不可見的,但是在windows上有bug,密碼可見 password=getpass.getpass('Password:') #創建一個列表,表示五臺設備最后8位的地址 ip_tail_list=[11,22,33,44,55] #使用for循環,接受SSH的秘鑰,并分別依次連接到五臺設備,注意需要將i轉化為字符串 foriinip_tail_list: ip="192.168.56."+str(i) ssh_client=paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_client.connect(hostname=ip,username=username,password=password) print("Successfullyconnectto",ip) #使用invoke_shell()喚醒shell界面 command=ssh_client.invoke_shell() #使用command.send()函數創建VLAN,并且設置每個VLAN的描述;未來保證設備能夠正常接受配置,每次創建1個VLAN后休息1s command.send("system ") forninrange(10,21): print("CreatingVlan"+str(n)) command.send("vlan"+str(n)+" ") command.send("descriptionPythonVlan"+str(n)+" ") time.sleep(1) #保存配置,并且通過command.recv()函數得到回信的信息,最多接受65535個字符 command.send("return ") command.send("save "+"y "+" ") time.sleep(2) output=command.recv(65535) print(output.decode('ascii')) #關閉連接 ssh_client.close()
如果管理的設備數目過多,可以直接通過讀取txt文件的方式獲取IP地址,僅需要將如下代碼:
#創建一個列表,表示五臺設備最后8位的地址 ip_tail_list=[11,22,33,44,55] #使用for循環,接受SSH的秘鑰,并分別依次連接到五臺設備,注意需要將i轉化為字符串 foriinip_tail_list: ip="192.168.56."+str(i) ssh_client=paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_client.connect(hostname=ip,username=username,password=password) #......省略中間部分 ssh_client.close()
更換為下述即可:
#使用open()函數打開ip_list文件,并將讀取的結果賦予f f=open("ip_list.txt","r") #調用readlines()函數,返回IP地址的列表,并使用for循環遍歷;注意使用readlines()的每一個ip地址后帶有 ,需要通過strip()函數去除 foriinf.readlines(): ip=i.strip() ssh_client=paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_client.connect(hostname=ip,username=username,password=password) #.......省略中間部分,在完成文件操作后,關閉文件 f.close() ssh_client.close()
執行效果:
…
在設備上檢查是否配置成功,以SW1為例:
可以看到創建VLAN和添加VLAN描述成功。
-
交換機
+關注
關注
21文章
2720瀏覽量
101334 -
VLAN
+關注
關注
1文章
283瀏覽量
36294 -
網絡技術
+關注
關注
1文章
296瀏覽量
29953 -
python
+關注
關注
56文章
4823瀏覽量
86153 -
腳本
+關注
關注
1文章
396瀏覽量
28340
原文標題:使用paramiko在eNSP的交換機中批量創建VLAN
文章出處:【微信號:網絡技術干貨圈,微信公眾號:網絡技術干貨圈】歡迎添加關注!文章轉載請注明出處。
發布評論請先 登錄
評論