0

I'm trying to learn python on my own. Wrote a script to get the configuration from the cisco switch. When executed, a message is displayed:

['\r\n', 'Line has invalid autocommand "show running-config\r\n', '"']

import paramiko

sw_ip = "*****"
sw_username = "****"
sw_password = "*****"
port = 22

ssh = paramiko.SSHClient()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect(hostname=sw_ip, username=sw_username, password=sw_password,
        port=port)

stdin,stdout,stderr = ssh.exec_command("show running-config\n")

list = stdout.readlines()
print(list)


ssh.close()

As I understand from the message, you need to add '/r/n' literals at the end of the command, but adding literals did not fix the situation. I would like to know what other reasons could be, in which direction to move. Internet searches have not yielded any results. Thank you!

I checked the script on the H3C switch, everything works, apparently the problem is in the availability on the Cisco switch.

Here's what I ended up with. I think the code can be optimized, but I still do not have enough experience to do this.

import paramiko
import time

sw_ip = "****"
sw_username = "****"
sw_password = "****"
port = 22

ssh = paramiko.SSHClient()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect(hostname=sw_ip, username=sw_username, password=sw_password,
            port=port)

stdout = ssh.invoke_shell(height=1000)
stdout.send('enable\n')
stdout.send('show running-config\n')
time.sleep(20)

ssh.close()

output = str(stdout.recv(30000))

strout = output[2:len(output)-2]

i = 0
conflist = ['']
confel = ''
rn = ''
while i <= len(strout)-1:
    rn = rn + strout[i:i+2]
    if rn == r'\n' or rn == r'\r':
        conflist.append(confel)
        rn = ''
        confel = ''
        i = i + 2
    else:
        confel = confel + strout[i]
        i = i + 1
        rn = ''

for el in conflist:
    conflist.remove('')
    
print(conflist)

with open('test2.txt', 'w') as f:
    for line in conflist:
        f.write(line)
        f.write('\n')
f.close()
Cow
  • 2,543
  • 4
  • 13
  • 25
ggs
  • 1
  • 1
  • @Martin Prikryl Thanks, your answer helped. Exec_command does not work with Cisco, but .invoke_shell() does. This [python-paramiko-ssh-and-network-devices](https://pynet.twb-tech.com/blog/python-paramiko-ssh-and-network-devices.html) helped. – ggs May 14 '23 at 23:53
  • Using `AutoAddPolicy` this way makes your connection insecure. For a correct solution, see https://stackoverflow.com/q/10670217/850848#43093883. – Martin Prikryl May 18 '23 at 04:57

0 Answers0