Не удалось подключиться по SSH к Ruckus AP с помощью Paramiko

Я работаю над автоматизацией сценария для входа в точку доступа Ruckus (H510 Unleashed) и сбора информации с нее с помощью Paramiko. Я использовал тот же скрипт Paramiko для входа в различные другие устройства (linux, HP/Aruba и т. д.) без проблем, но когда я пытаюсь подключиться к точке доступа Ruckus, даже без отправки команды, я получаю вывод «Недопустимый аргумент». У меня есть встроенная проверка ошибок, которая обнаруживает неверные пароли и тому подобное, так что этого быть не должно. Я также могу использовать SSH с той же машины, на которой я запускаю скрипт Python, без проблем и без каких-либо странных заголовков в сеансе SSH.

У кого-нибудь есть идеи? Код ниже:

import paramiko
import csv
from datetime import datetime
import getpass
from socket import error as socket_error


###Define Variables
ip_port = input("Enter Device IP and Port (xxx.xxx.xxx.xxx:yy):")   #Gets the IP address AND port number used to SSH to the devices - will be split apart later
username = input("Enter Username:")                                 #Gets the username for authentication to the device
passwd = input("Enter Password:")                                   #Gets the password for authentication to the device
command = input("Enter the command you wish to execute:")           #Gets the command that is to be executed on the machine
dev_ip_addr = ""                                                    #Variable holding just the IP address or FQDN for the device
dev_port = 0                                                        #Variable holding just the port number for the device

log_file = datetime.now().strftime("D:\\Networking\\Python Testing\\SSH Automation\\User Input with Pamaiko\\Command_Log_%Y%m%d-%H%M%S.csv") #Output file to write command audit log to
log_file_headers = ["Device IP", "Port", "User", "Device Auth Username", "Time", "Command", "Output", "Errors"]     #Headers for the CSFV log file
file_lines = []                                                                                     #Holds the lines for output into the csv file
current_user = getpass.getuser()    #Gets the user currently running the program for logging purposes


###Do Something
#Split IP from the port number for SSH session
dev_ip_addr = ip_port.split(':')[0]
dev_port = ip_port.split(':')[1]

#Try and except section for actuall ssh connection and handeling errors during connection (authentication, socket, and no response errors)
try:
    #Set up Paramiko SSH session
    ssh=paramiko.SSHClient()

    #Host key section for SSH connections
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    #Make the SSH connection
    ssh.connect(dev_ip_addr,dev_port,username,passwd)

    #Execute Command using the inputs from the user
    stdin,stdout,stderr=ssh.exec_command(command)
    stdin.close()

    #Clean up the command output for displaying on screen and to log file, close SSH session
    stdout = stdout.readlines()
    clean_command_output = ("".join(stdout))


    #Set and append inputs and outputs for log file
    output_line = [dev_ip_addr, dev_port, current_user, username, datetime.now(), command, clean_command_output]
    file_lines.append(output_line)

#Handles authentication errors while connecting to device
except paramiko.AuthenticationException:
    print("Authentication failed, please verify your credentials to ", dev_ip_addr)
    #Set and append inputs and outputs for log file, including error
    output_line = [dev_ip_addr, dev_port, current_user, username, datetime.now(), command, "", "AUTHENTICATION ERROR"]
    file_lines.append(output_line)
    print()

#Handles host key verification issues from the device
except paramiko.BadHostKeyException:
    print("Host key could not be verified from ", dev_ip_addr)
    #Set and append inputs and outputs for log file, including error
    output_line = [dev_ip_addr, dev_port, current_user, username, datetime.now(), command, "", "UNABLE TO VERIFY HOST KEY"]
    file_lines.append(output_line)
    print()

#Handles SSH errors while connecting to device
except paramiko.SSHException as sshException:
    print("Unable to establish SSH connection: %s" % sshException)
    #Set and append inputs and outputs for log file, including error
    output_line = [dev_ip_addr, dev_port, current_user, username, datetime.now(), command, "", "SSH CONNECTION EXCEPTION OCCURRED"]
    file_lines.append(output_line)
    print()

#Handles socket and refusal errors while connecting to device
except socket_error as socket_error:
    print("Connection refused/no response to ", dev_ip_addr)
    #Set and append inputs and outputs for log file, including error
    output_line = [dev_ip_addr, dev_port, current_user, username, datetime.now(), command, "", "CONNECTION REFUSED OR NO RESPONSE"]
    file_lines.append(output_line)
    print()

#Create CSV file for logging of what device, port, user, and commands were run along with a time stamp
with open(log_file, 'w', newline='') as log_out:
            csvwriter = csv.writer(log_out)
            csvwriter.writerow(log_file_headers)
            csvwriter.writerows(file_lines)

person scooter_118    schedule 07.01.2021    source источник
comment
«Недопустимый аргумент» — это то, что возвращается от точки доступа Ruckus в качестве вывода при попытке подключиться к ней по протоколу ssh. Это не исключение из Paramiko. Просматривая журналы точки доступа, я вижу шум (rkscli): недопустимый аргумент, полученный от клиента, что заставляет меня думать, что Paramiko передает точке доступа что-то, что ей не нравится.   -  person scooter_118    schedule 08.01.2021


Ответы (1)


Хорошо, поэтому с некоторым тестированием других методов SSH с использованием Paramiko я смог заставить опцию «invoke_shell()» действительно работать для меня, чтобы войти в систему. Кажется, что есть аргумент, переданный точке доступа во время SSH-соединения, когда используя «ssh.exec_command», что приводит к сбою. Мне также пришлось добавить таймер time.sleep между всеми командами, чтобы верхняя точка доступа успела распознать их и передать вывод обратно в скрипт.

person scooter_118    schedule 08.01.2021