1

我正在尝试编写一个 Python 脚本以在 Cisco 交换机的一个接口上启用端口安全并将它们绑定到一组 MAC_addresses,其中我将以下内容作为用户的输入:

  1. 要添加的 MAC 地址数量
  2. 要添加的 MAC 地址。

我的代码如下:

tn = telnetlib.Telnet('192.168.1.10')
tn.read_until(b"Password:")
telpassword="P@ssw0rd"
tn.write(telpassword.encode('ascii')+ b'\r\n')
tn.write(b"enable"+b"\r\n")
tn.write(telpassword.encode('ascii')+ b'\r\n')
tn.write(b"config terminal"+ b"\r\n")
tn.write(b"interface gigabitEthernet 1/0/10"+ b"\r\n")
tn.write(b"switchport mode access"+ b"\r\n")
tn.write(b"switchport port-security"+ b"\r\n")
maxmac = input("How many MAC Addresses you want to add"+"\n")
tn.write(b"switchport port-security maximum"+ maxmac.encode('ascii') + b"\r\n")
macadd = input("Enter the MAC Address in the format xxxx.xxxx.xxxx"+"\n")
tn.write(b"switchport port-security mac-address"+ macadd.encode('ascii') + b"vlan access" + b"\r\n")
tn.write(b"switchport port-security violation shutdown" + b"\r\n")
tn.write(b"end" + b"\r\n")
tn.write(b"wr" + b"\r\n")
print("MAC_Address "+str(macadd)+" has been added")

当我传递必须连接字节和字符串的命令时(转换为字节后,我的 Cisco CLI 无法识别这些命令。例如,我的 Cisco CLI 在通过脚本时未采用以下 2 个命令:

tn.write(b"switchport port-security maximum"+ maxmac.encode('ascii') + b"\r\n")
tn.write(b"switchport port-security mac-address"+ strmacadd.encode('ascii') + b"vlan access" + b"\r\n")

但是,在通过以下命令时使用身份验证密码非常好:

tn.write(telpassword.encode('ascii')+ b'\r\n')

当我的字符串命令(转换为字节)与字符串用户输入(也转换为字节)连接时,我遇到了一些问题,如上所示。

请指导我,在这种情况下,通过 Cisco CLI 传递命令的正确方法应该是什么。

4

1 回答 1

0

也许你想看看这个库:https ://github.com/nickpegg/ciscolib

于 2015-08-18T17:07:02.900 回答