Python自動化
一、安裝Paramiko模塊
首先安裝Python3
然後安裝pip解釋器
最後安裝Paramiko模塊
Windows+R打開Cmd,輸入命令:
pip3 install paramiko
進入python,導入 paramiko模塊:
import paramiko
二、搭建實驗環境
1、橋接電腦網卡
2、配置交換機IP地址
交換機配置
<Huawei>sys
[Huawei]sys SW1
[SW1]
[SW1]vlan 10
[SW1-vlan10]qu
[SW1]
[SW1]int Vlanif 10
[SW1-Vlanif10]ip add 192.168.1.254 24
[SW1]int g0/0/1
[SW1-GigabitEthernet0/0/1]port link-type access
[SW1-GigabitEthernet0/0/1]port default vlan 10
測試ensp的交換機與電腦的連通性
交換機配置SSH
[SW1]dsa local-key-pair create
Info: The key name will be: SW1_Host_DSA.
Info: The key modulus can be any one of the following : 512, 1024, 2048.
Info: If the key modulus is greater than 512, it may take a few minutes.
Please input the modulus [default=512]:2048
Info: Generating keys...
[SW1]user-interface vty 0 4
[SW1-ui-vty0-4]authentication-mode aaa
[SW1-ui-vty0-4]protocol inbound ssh
[SW1-ui-vty0-4]
[SW1]aaa
[SW1-aaa]local-user huawei password cipher huawei@123
[SW1-aaa]local-user huawei privilege level 15
[SW1-aaa]local-user huawei service-type ssh
[SW1-aaa]
[SW1]ssh user huawei authentication-type password
[SW1]ssh user huawei service-type stelnet
[SW1]stelnet server enable
Xshell驗證
登錄成功
三、Python腳本
import paramiko
import time
ip = "192.168.1.254"
user = "huawei"
pw = "huawei@123"
#歡迎關注喜歡華爲的李工
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=ip, username=user , password=pw)
print("恭喜您成功登錄到ensp上的交換機了!" , ip)
#連接成功後,調用invoke_shell()方法來喚醒shell,也就是華爲系統命令行,同時把它賦值給command,方便後續調用。
command = ssh.invoke_shell()
#向設備發送命令,需要執行的命令。
command.send("system\n")
command.send("vlan 20\n")
command.send("quit \n")
command.send("int vlan 20 \n")
command.send("ip add 192.168.20.1 24 \n")
command.send("vlan 30\n")
command.send("quit \n")
command.send("int vlan 30 \n")
command.send("ip add 192.168.30.1 24 \n")
command.send("vlan 40\n")
command.send("quit \n")
command.send("int vlan 40 \n")
command.send("ip add 192.168.40.1 24 \n")
command.send("vlan 50\n")
command.send("quit \n")
command.send("int vlan 50 \n")
command.send("ip add 192.168.50.1 24 \n")
command.send("vlan 60\n")
command.send("quit \n")
command.send("int vlan 60 \n")
command.send("ip add 192.168.60.1 24 \n")
command.send("quit \n")
#歡迎關注喜歡華爲的李工
#使用sleep函數,讓腳步執行後休息2s,再回顯內容。65535是回顯多少個字符
time.sleep(2)
output = command.recv(65535)
print(output.decode("ascii"))
#配置完後,用close方法退出ssh
ssh.close()
在執行前還沒有vlanif 20、vlanif 30、vlanif 40、vlanif 50、vlanif 60的接口及ip地址
1、執行python腳本
腳本執行成功