AttributeError: объект 'NoneType' не имеет атрибута 'exec_command' при преобразовании строк кода в функцию в python - PullRequest
0 голосов
/ 17 июня 2020

Этот вопрос связан со следующим: Как использовать сокеты для отправки пользователя и пароля на плату разработчика с помощью s sh

Как я могу поместить КОД A в функцию? Объясни мне, что я делаю не так.

КОД A

import paramiko
import os

#Server's data
IP = '172.16.2.82'
PORT = 22
USER = 'mendel'
PASSWORD = 'mendel'


ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname = IP, port=PORT, username = USER, password = PASSWORD)

stdin, stdout, stderr = ssh.exec_command('cd coral/tflite/python/examples/classification/Auto_benchmark\n python3 auto_benchmark.py')
output = stdout.readlines()
type(output)
print('\n'.join(output))
ssh.close()

Это моя попытка:

def initialize_ssh():
    n = 0
    while n <= 10:
        try:
            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh.connect(hostname = IP, port=PORT, username = USER, password = PASSWORD)
            return
        except paramiko.AuthenticationException:
            print("Authentication failed, please verify your credentials: %s")
        except paramiko.SSHException as sshException:
            print("Unable to establish SSH connection: %s" % sshException)
            n += 1
            continue
    raise Exception


def main():
    ssh = initialize_ssh()
    stdin, stdout, stderr = ssh.exec_command('cd coral/tflite/python/examples/classification/Auto_benchmark\n python3 auto_benchmark.py')
    output = stdout.readlines()
    type(output)
    print('\n'.join(output))
    ssh.close()


if __name__ == '__main__':
    main() 

ИЗМЕНИТЬ ПОСЛЕ ПРЕДЛОЖЕНИЙ ИЗ КОММЕНТАРИЙ

def main():
    ssh = initialize_ssh()
    stdin, stdout, stderr = ssh.exec_command('ls')
    output = stdout.readlines()
    type(output)
    print('\n'.join(output))
    ssh.close()
    return ssh    <------------------- HERE IS THE CHANGE

1 Ответ

1 голос
/ 17 июня 2020

Ваше первое изменение должно возвращать s sh:

def initialize_ssh():
    n = 0
    while n <= 10:
        try:
            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh.connect(hostname = IP, port=PORT, username = USER, password = PASSWORD)
            return ssh # the return is here
        except paramiko.AuthenticationException:
            print("Authentication failed, please verify your credentials: %s")
        except paramiko.SSHException as sshException:
            print("Unable to establish SSH connection: %s" % sshException)
            n += 1
            continue
    raise Exception
...