#! /usr/bin/python3
# coding=utf-8

import telnetlib
import json
import paramiko
import time


class SSHSetup:
    def __init__(self, host, port, user, passwd, comlist=[]):
        self.host = host
        self.user = user
        self.passwd = passwd
        self.port = port
        try:
            self.client = paramiko.SSHClient()
            self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            self.client.connect(hostname=self.host, port=self.port, username=self.user, password=self.passwd,
                                look_for_keys=False, allow_agent=False)
            self.ssh = self.client.invoke_shell()
            time.sleep(1)
            self.ssh.recv(10000)
        except Exception as exc:
            raise Exception('ssh error: {}'.format(exc))
        if len(comlist) > 0:
            if 'exit' not in comlist:
                comlist.append('exit')
            self.sendall(comlist)
            self.close()

    def send(self, command):
        self.ssh.send(command + '\n')
        time.sleep(1)
        print(self.ssh.recv(10000).decode())

    def sendall(self, commlist=[]):
        for command in commlist:
            self.send(command)

    def close(self):
        self.ssh.close()


class TelnetSetup:
    def __init__(self, host, port, user, passwd, comlist=[]):
        self.host = host
        self.port = port
        self.user = user
        self.passwd = passwd
        try:
            self.tn = telnetlib.Telnet(host, port)
        except Exception as exc:
            raise Exception('telnet error: {}'.format(exc))

        if len(comlist) > 0:
            if 'exit' not in comlist:
                comlist.append('exit')
            self.login()
            self.sendall(comlist)
            self.close()

    def login(self):
        print(self.tn.read_until(b'login:'))
        self.tn.write(self.user.encode('utf8') + b'\n')
        print(self.tn.read_until(b'Password:'))
        self.tn.write(self.passwd.encode('utf8') + b'\n')
        self.tn.read_until(self.user.encode('utf8'))

    def send(self, command):
        self.tn.write(command.encode('utf8') + b'\n')
        print(self.tn.read_until(self.user.encode('utf8')).decode('utf8'))

    def sendall(self, comlist=[]):
        for command in comlist:
            self.send(command)

    def close(self):
        self.tn.close()


class SetupMiner:
    def __init__(self, host, conf={}, telnets=[], sshs=[]):
        self.host = host
        self.conf = conf
        if len(telnets) == 0:
            self.telnets = ["uname -a", "ps -A", "exit"]
        else:
            self.telnets = telnets
        if len(sshs) == 0:
            self.sshs = ["uname -a", "ps -A", "exit"]
        else:
            self.sshs = sshs
        try:
            TelnetSetup(self.host, self.conf['telnetport'], self.conf['telnetuser'], self.conf['telnetpass'],
                        self.telnets)
        except Exception as exc:
            print(exc)
            try:
                SSHSetup(self.host, self.conf['sshport'], self.conf['sshuser'], conf['sshpass'], self.sshs)
            except Exception as exc:
                raise exc


def read_conf():
    with open('config.json') as f:
        conf = json.load(f)
    return conf


def main():
    conf = read_conf()
    minerconf = {"sshuser": conf["sshuser"],
                 "sshpass": conf["sshpass"],
                 "sshport": conf["sshport"],
                 "telnetuser": conf["telnetuser"],
                 "telnetpass": conf["telnetpass"],
                 "telnetport": conf["telnetport"]}
    comlist = ["uname -a", "ps -A", "exit"]
    try:
        SetupMiner('10.100.0.48', minerconf)
    except Exception as exc:
        print(exc)


if __name__ == '__main__':
    main()