Вход в контроллер беспроводной сети Cisco через SSH

У меня есть рабочий сценарий Python, который войдет в устройство cisco (маршрутизатор / коммутатор) и получит от него любую информацию, которую вы хотите. Сейчас я работаю над тем же для cisco wlc, однако для ssh в wlc требуется имя «логин как» вместе с «именем пользователя / паролем». Я использую paramiko и не могу понять, как добавить дополнительный шаг подключения с именем «войти как». Есть ли другой модуль ssh, который позволил бы мне это сделать?

Вот пример входа в cisco wlc через ssh:

войти как: тест

(Контроллер Cisco)

Пользователь: test

Пароль:****

А это документация по использованию paramiko.connect:

connect (self, hostname, port = 22, username = None, password = None, pkey = None, key_filename = None, timeout = None, allow_agent = True, look_for_keys = True, compress = False)

Вот код, с которым я сейчас работаю, на случай, если он поможет:

import web
import paramiko
import time

urls = (
        '/wlc', 'Index'
)

app = web.application(urls, globals())

render = web.template.render('templates/')

class Index(object):
        def GET(self):
                return render.hello_form()

        def POST(self):
                form = web.input(user=" ", passwd=" ", device=" ")
                user = form.user
                passwd = form.passwd
                device = form.device

                #Used to change term length to 0 making it so we don't need to hit a key to scroll through the output
                def disable_paging(remote_conn, command="terminal length 0", delay=1):

                        #Send an enter
                        remote_conn.send("\n")
                        #Send 'terminal length 0'
                        remote_conn.send(command)

                        #Wait for command to complete
                        time.sleep(delay)

                        #Read output
                        output = remote_conn.recv(65535)

                        return output

                #Have remote_conn_pre equal to the SSHClient module in paramiko
                remote_conn_pre = paramiko.SSHClient()

                #This allows us to bypass the ssh key popup that comes up when you ssh into a device for the first time
                remote_conn_pre.set_missing_host_key_policy(
                        paramiko.AutoAddPolicy())

                remote_conn_pre.connect(device,username=user, password=passwd) #Connect to the device using our defind parameters

                remote_conn = remote_conn_pre.invoke_shell() #invoke_shell module gives us access to talk to the device via the cli

                output = disable_paging(remote_conn) #Run the disable_paging function that sets term length to 0

                remote_conn.send("\n")
                remote_conn.send("sh ap inventory")
                remote_conn.send("\n")

                time.sleep(2)

                output = remote_conn.recv(65535) #Read all output given

                return output #print output to screen

                remote_conn_pre.close() #Close the SSH connection


if __name__ == "__main__":
        app.run()

person JMarks    schedule 15.07.2014    source источник


Ответы (1)


Много играл с paramiko.transport, но не мог заставить его работать. Наконец, я просто попытался .send () информацию, и теперь он дает мне результат, который я ищу:

import web
import paramiko
import time

urls = (
        '/wlc', 'Index'
)

app = web.application(urls, globals())

render = web.template.render('templates/')

class Index(object):
        def GET(self):
                return render.hello_form()

        def POST(self):
                #Retrieve user input from web form
                form = web.input(user=" ", passwd=" ", device=" ")
                user = form.user
                passwd = form.passwd
                device = form.device

                #Make it so we don't need to hit a key to scroll through the output
                def disable_paging(remote_conn, command="config paging disable", delay=1):

                        remote_conn.send(command)
                        remote_conn.send("\n")
                        time.sleep(delay)


                #Have remote_conn_pre equal to the SSHClient module in paramiko
                remote_conn_pre = paramiko.SSHClient()

                #This allows us to bypass the ssh key popup that comes up when you ssh into a device for the first time
                remote_conn_pre.set_missing_host_key_policy(
                        paramiko.AutoAddPolicy())

                remote_conn_pre.connect(device, username=user, password=passwd) #Connect to the device using our defind parameters

                remote_conn = remote_conn_pre.invoke_shell() #invoke_shell module gives us access to talk to the device via the cli

                #Log into the WLC
                remote_conn.send(user)
                remote_conn.send("\n")
                remote_conn.send(passwd)
                remote_conn.send("\n")

                #Run the disable_paging function
                output = disable_paging(remote_conn)

                #Run command
                remote_conn.send("sh ap summary")
                remote_conn.send("\n")

                #Some WLCs can be slow to show output, have program wait 5 seconds
                time.sleep(5)

                output = remote_conn.recv(65535) #Read all output given

                return output #print output to screen

                remote_conn.close() #Close the SSH connection


if __name__ == "__main__":
        app.run()

Поле «Войти как» не указано в моих выводах, поэтому я не уверен, что туда помещается - возможно, только параметры из remote_conn_pre.connect(device, username=user, password=passwd). В любом случае, теперь, когда я могу войти в устройства, я могу начать анализировать вывод, чтобы получить нужную мне информацию.

person JMarks    schedule 18.07.2014