0

This question is related to this one: How to use sockets to send user and password to a devboard using ssh

How can I put CODE A into a function? Explain me what am I doing wrong.

CODE 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()

This is my attempt:

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

EDIT AFTER SUGGESTIONS FROM COMMENTS

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

quamrana
  • 37,849
  • 12
  • 53
  • 71
Aizzaac
  • 3,146
  • 8
  • 29
  • 61

1 Answers1

1

Your first change should be to return ssh:

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
quamrana
  • 37,849
  • 12
  • 53
  • 71