基于paramiko的简单主机管理

# -*- coding:utf-8 -*-
# @Time     : 2017-03-30 15:26
# @Author   : Vincen
# @Site     : 
# @File     : fortress.py
# @Software : PyCharm

import paramiko
import pymysql
from concurrent.futures import ThreadPoolExecutor


# database: paradb
# tables: user_type.dbf users.dbf hosts.dbf user_to_host.dbf
# user: alex 123456

class HostManage(object):
    def __init__(self):
        self.__conn = None
        self.__cursor = None
        self.__transport = None
        self.host = "127.0.0.1"
        self.port = 3306
        self.user = "root"
        self.passwd = "root"
        self.db = "paradb"
        self.command = None
        self.db_cursor = self.db_connect()

    def db_connect(self):
        conn = pymysql.connect(host=self.host, port=self.port, user=self.user, password=self.passwd, db=self.db)
        cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
        self.__conn = conn
        self.__cursor = cursor
        return cursor

    def auth(self, user_name, pass_word):
        self.db_cursor.execute("select * from users where username=%s and password=%s", (user_name, pass_word))
        if self.db_cursor.fetchall():
            return True

    def host_list(self, user_name):
        self.db_cursor.execute("select h.ip,h.port,h.username,h.password from users u "
                          "left join user_to_host uh on u.id=uh.uid "
                          "left join hosts h on h.id=uh.hid "
                          "where u.username=%s", (user_name,))

        return self.db_cursor.fetchall()

    def ssh_connect(self, hosts):
        ssh_client = paramiko.SSHClient()
        host = hosts["ip"]
        port = hosts["port"]
        user_name = hosts["username"]
        pass_word = hosts["password"]
        transport = paramiko.Transport((host, port))
        transport.connect(username=user_name, password=pass_word)
        ssh_client._transport = transport
        std_in, stdout, stderr = ssh_client.exec_command(self.command)
        if stdout:
            print(host.center(40, "-"))
            print(str(stdout.read(), encoding="utf-8"))
        else:
            print(str(stderr.read(), encoding="utf-8"))
        transport.close()

    def ssh(self, hosts, command):
        self.command = command
        t = ThreadPoolExecutor(max_workers=2)
        t.map(self.ssh_connect, hosts)

    def close(self):
        self.__conn.close()
        self.__cursor.close()
        self.__transport.close()

    def __del__(self):
        self.__conn.close()
        self.__cursor.close()


if __name__ == '__main__':
    host_manage = HostManage()
    while True:
        username = input("please input username >>>")
        password = input("please input password >>>")
        if host_manage.auth(username, password):
            print("Welcome to ForTress System!")
            break
        else:
            print("Authentication failed!")

    host_list = host_manage.host_list(username)
    for n, k in enumerate(host_list):
        print("host".center(40, "-"))
        print(n, ":", k["ip"])

    while True:
        numbers = input("please input host number >>>").strip()
        if numbers == "q":
            exit()
        hosts = []
        for num in numbers.split(" "):      # split host list use blankspace
            hosts.append(host_list[int(num)])
        command = input("please input shell command >>>")
        host_manage.ssh(hosts, command)

 

posted @ 2017-03-31 10:02  Vincen_shen  阅读(204)  评论(0)    收藏  举报