简体   繁体   中英

Facing issue while running a Python Script on Cisco CLI

I am trying to write a Python Script to enable port-security on one of the interfaces of a Cisco Switch and bind them to a group of MAC_addresses, wherein I am taking the following as input from the users:

  1. The number of MAC Addresses to be added
  2. The MAC Addresses to be added.

My code is below:

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")

When I am passing commands wherein I have to concatenate bytes and strings(after converted to bytes, my Cisco CLI is not recognozing those commands.Like for eg my Cisco CLI is not taking following 2 commands when passing through the script:

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")

However it is very well taking the authentication passwords when passing through the following commands:

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

I am facing some issue when my string commands(converted into bytes) are concatenated with an string user input(also converted into bytes) as shown above.

Please guide me,that in such a scenario what should be the correct way to pass the commands through the Cisco CLI.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM