来源:公众号【网络技术干货圈】
作者:圈圈
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描述成功。
-
交换机
+关注
关注
23文章
2870浏览量
103935 -
VLAN
+关注
关注
1文章
288浏览量
37539 -
网络技术
+关注
关注
1文章
296浏览量
31056 -
python
+关注
关注
57文章
4858浏览量
89596 -
脚本
+关注
关注
1文章
407浏览量
29054
原文标题:使用paramiko在eNSP的交换机中批量创建VLAN
文章出处:【微信号:网络技术干货圈,微信公众号:网络技术干货圈】欢迎添加关注!文章转载请注明出处。
发布评论请先 登录

使用paramiko在eNSP的交换机中批量创建VLAN
评论