使用paramiko SSH登陆交换机配置
paramiko是python的第三方库,需要安装,可以使用 pip来进行安装,也可以在pycharm上手动安装
云配置
云的配置是为了让主机能与交换机互相访问
交换机配置
interface Vlanif1
ip address 192.168.56.2 255.255.255.0
#
aaa
local-user admin password cipher Huawei@123 //创建python用户,密码为123
local-user admin privilege level 15
local-user admin service-type ssh
#
user-interface vty 0 4
authentication-mode aaa
protocol inbound ssh
#
stelnet server enable
ssh user admin authentication-type all
ssh user admin service-type all
ssh client first-time enable
这个时候我们就能与交换机互访,并SSH登陆了
拓扑
目的
使用SSH登陆交换机并为loop back 0创建 1.1.1.1/24的IP地址
代码
import paramiko #导入paramiko和time模块
import time
ip = "192.168.56.2" #设置目的IP,username,password
username = "admin"
password = "Huawei@123"
ssh_client = paramiko.SSHClient() #调用paramiko的SSHClient()方法
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #让paramiko接收SSH服务器提供的公钥
ssh_client.connect(hostname=ip, username=username, password=password, look_for_keys=False)
print("Successfully connected to ", ip) #如果成功登陆,打印出成功登陆
command = ssh_client.invoke_shell() #连接成功后建立shell会话
command.send(b"screen-length 0 temporary\n") #使用send给目的服务器发送指令
command.send(b"sys\n")
command.send(b"int lo 0\n")
command.send(b"ip address 1.1.1.1 24\n")
command.send(b"return\n")
time.sleep(2)
output = command.recv(65535)
print(output.decode("ascii"))
ssh_client.close()
结果
Successfully connected to 192.168.56.2
Info: The max number of VTY users is 5, and the number
of current VTY users on line is 1.
The current login time is 2023-11-26 21:19:17.
<Huawei>screen-length 0 temporary
Info: The configuration takes effect on the current user terminal interface only.
<Huawei>sys
Enter system view, return user view with Ctrl+Z.
[Huawei]int lo 0
[Huawei-LoopBack0]ip address 1.1.1.1 24
Error: The address already exists.
[Huawei-LoopBack0]return
<Huawei>