コード例 #1
0
ファイル: consumers.py プロジェクト: kevindwei/adminset
    def receive(self, text=None, bytes=None, **kwargs):
        try:
            if text:
                data = json.loads(text)
                begin_time = time.time()
                if data[0] == 'ip':
                    ip = data[1]
                    width = data[2]
                    height = data[3]
                    self.ssh.set_missing_host_key_policy(
                        paramiko.AutoAddPolicy())
                    try:
                        data = ServerInfor.objects.get(
                            ip=ip, credential__protocol__contains='ssh')
                        port = data.credential.port
                        method = data.credential.method
                        username = data.credential.username
                        audit_log = Log.objects.create(
                            user=UserInfo.objects.get(
                                username=self.message.user),
                            server=data,
                            channel=self.message.reply_channel.name,
                            width=width,
                            height=height)
                        audit_log.save()
                        if method == 'password':
                            password = data.credential.password
                        else:
                            key = data.credential.key
                    except ObjectDoesNotExist:
                        self.message.reply_channel.send(
                            {
                                "text":
                                json.dumps([
                                    'stdout',
                                    '\033[1;3;31mConnect to server! Server ip doesn\'t exist!\033[0m'
                                ])
                            },
                            immediately=True)
                        self.message.reply_channel.send({"accept": False})

                    try:
                        if method == 'password':
                            self.ssh.connect(ip,
                                             port=port,
                                             username=username,
                                             password=password,
                                             timeout=3)  #通过密码连接
                        else:
                            self.ssh.connect(ip,
                                             port=port,
                                             username=username,
                                             key_filename=key,
                                             timeout=3)  #通过key连接
                    except socket.timeout:
                        self.message.reply_channel.send(
                            {
                                "text":
                                json.dumps([
                                    'stdout',
                                    '\033[1;3;31mConnect to server time out\033[0m'
                                ])
                            },
                            immediately=True)
                        self.message.reply_channel.send({"accept": False})
                        return
                    except Exception:
                        self.message.reply_channel.send(
                            {
                                "text":
                                json.dumps([
                                    'stdout',
                                    '\033[1;3;31mCan not connect to server\033[0m'
                                ])
                            },
                            immediately=True)
                        self.message.reply_channel.send({"accept": False})
                        return

                    chan = self.ssh.invoke_shell(
                        width=width,
                        height=height,
                    )  #设置终端大小

                    #open a new threading to handle ssh to avoid global variable bug
                    sshterminal = SshTerminalThread(self.message, chan)
                    sshterminal.setDaemon = True
                    sshterminal.start()  #开启线程

                    directory_date_time = now()
                    #回访文件json格式,给asciinema调用
                    log_name = os.path.join(
                        '{0}-{1}-{2}'.format(directory_date_time.year,
                                             directory_date_time.month,
                                             directory_date_time.day),
                        '{0}.json'.format(audit_log.log))

                    #interactive_shell(chan,self.message.reply_channel.name,log_name=log_name,width=width,height=height)
                    interactivessh = InterActiveShellThread(
                        chan,
                        self.message.reply_channel.name,
                        log_name=log_name,
                        width=width,
                        height=height)
                    interactivessh.setDaemon = True
                    interactivessh.start()

                elif data[0] in ['stdin', 'stdout']:
                    self.queue().publish(self.message.reply_channel.name,
                                         json.loads(text)[1])
                elif data[0] == u'set_size':
                    self.queue().publish(self.message.reply_channel.name, text)
                else:
                    self.message.reply_channel.send(
                        {
                            "text":
                            json.dumps([
                                'stdout',
                                '\033[1;3;31mUnknow command found!\033[0m'
                            ])
                        },
                        immediately=True)
            elif bytes:
                self.queue().publish(self.message.reply_channel.name,
                                     json.loads(bytes)[1])
        except socket.error:
            #socket问题就记录下来
            audit_log = Log.objects.get(
                user=UserInfo.objects.get(username=self.message.user),
                channel=self.message.reply_channel.name)
            audit_log.is_finished = True
            audit_log.end_time = now()
            audit_log.save()
            self.closessh()
            self.close()
        except Exception, e:
            #代码问题
            import traceback
            print traceback.print_exc()
            self.closessh()
            self.close()
コード例 #2
0
    def openterminal(self,ip,id,channel,width,height,elementid=None):
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        try:
            Permission.objects.get(user__username=self.message.user.username,groups__servers__ip=ip,groups__servers__id=id,groups__servers__credential__protocol__contains='ssh')
        except ObjectDoesNotExist:
            self.message.reply_channel.send({"text":json.dumps(['stdout','\033[1;3;31mYou have not permission to connect server {0}!\033[0m'.format(ip),elementid.rsplit('_')[0]])},immediately=True)
            self.message.reply_channel.send({"accept":False})
            return
        except MultipleObjectsReturned:
            pass
        try:
            data = ServerInfor.objects.get(ip=ip,credential__protocol__contains='ssh')
            port = data.credential.port
            method = data.credential.method
            username = data.credential.username
            audit_log = Log.objects.create(user=User.objects.get(username=self.message.user),server=data,channel=elementid,width=width,height=height)
            audit_log.save()
            if method == 'password':
                password = data.credential.password
            else:
                key = data.credential.key
        except ObjectDoesNotExist:
            self.message.reply_channel.send({"text":json.dumps(['stdout','\033[1;3;31mConnect to server! Server ip doesn\'t exist!\033[0m',elementid.rsplit('_')[0]])},immediately=True)
            self.message.reply_channel.send({"accept":False})
        try:
            if method == 'password':
                self.ssh.connect(ip, port=port, username=username, password=password, timeout=3)
            else:
                private_key = StringIO.StringIO(key)
                if 'RSA' in key:
                    private_key = paramiko.RSAKey.from_private_key(private_key)
                elif 'DSA' in key:
                    private_key = paramiko.DSSKey.from_private_key(private_key)
                elif 'EC' in key:
                    private_key = paramiko.ECDSAKey.from_private_key(private_key)
                elif 'OPENSSH' in key:
                    private_key = paramiko.Ed25519Key.from_private_key(private_key)
                else:
                    self.message.reply_channel.send({"text":json.dumps(['stdout','\033[1;3;31munknown or unsupported key type, only support rsa dsa ed25519 ecdsa key type\033[0m',elementid.rsplit('_')[0]])},immediately=True)
                    self.message.reply_channel.send({"accept":False})
                self.ssh.connect(ip, port=port, username=username, pkey=private_key, timeout=3)
        except socket.timeout:
            self.message.reply_channel.send({"text":json.dumps(['stdout','\033[1;3;31mConnect to server time out\033[0m',elementid.rsplit('_')[0]])},immediately=True)
            self.message.reply_channel.send({"accept":False})
            return
        except Exception as e:
            self.message.reply_channel.send({"text":json.dumps(['stdout','\033[1;3;31mCan not connect to server: {0}\033[0m'.format(e),elementid.rsplit('_')[0]])},immediately=True)
            self.message.reply_channel.send({"accept":False})
            return

        chan = self.ssh.invoke_shell(width=width, height=height,)

        #open a new threading to handle ssh to avoid global variable bug
        sshterminal=SshTerminalThread(self.message,chan,elementid=elementid)
        sshterminal.setDaemon = True
        sshterminal.start()

        directory_date_time = now()
        log_name = os.path.join('{0}-{1}-{2}'.format(directory_date_time.year,directory_date_time.month,directory_date_time.day),'{0}'.format(audit_log.log))

        interactivessh = InterActiveShellThread(chan,self.message.reply_channel.name,log_name=log_name,width=width,height=height,elementid=elementid)
        interactivessh.setDaemon = True
        interactivessh.start()
        self.message.reply_channel.send({"text":json.dumps(['channel_name',elementid.rsplit('_')[0],elementid.rsplit('_')[0]])},immediately=True)
コード例 #3
0
    def receive(self, text=None, bytes=None, **kwargs):
        try:
            if text:
                data = json.loads(text)
                begin_time = time.time()
                if isinstance(data,
                              list) and data[0] == 'ip' and len(data) == 5:
                    ip = data[1]
                    width = data[2]
                    height = data[3]
                    id = data[4]
                    self.ssh.set_missing_host_key_policy(
                        paramiko.AutoAddPolicy())
                    try:
                        Permission.objects.get(
                            user__username=self.message.user.username,
                            groups__servers__ip=ip,
                            groups__servers__id=id,
                            groups__servers__credential__protocol__contains=
                            'ssh')
                    except ObjectDoesNotExist:
                        # self.message.reply_channel.send({"text": json.dumps(
                        # ['stdout', '\033[1;3;31mYou have not permission to connect server {0}!\033[0m'.format(ip)])}, immediately=True)
                        self.message.reply_channel.send(
                            {
                                "text":
                                '\033[1;3;31mYou have not permission to connect server {0}!\033[0m'
                                .format(ip)
                            },
                            immediately=True)
                        self.message.reply_channel.send({"accept": False})
                        logger.error(
                            "{0} have not permission to connect server {1}!".
                            format(self.message.user.username, ip))
                        return
                    except MultipleObjectsReturned:
                        pass
                    try:
                        data = ServerInfor.objects.get(
                            ip=ip, credential__protocol__contains='ssh')
                        port = data.credential.port
                        method = data.credential.method
                        username = data.credential.username
                        if method == 'password':
                            password = data.credential.password
                        else:
                            key = data.credential.key
                    except ObjectDoesNotExist:
                        # self.message.reply_channel.send({"text": json.dumps(
                        # ['stdout', '\033[1;3;31mConnect to server! Server ip doesn\'t exist!\033[0m'])}, immediately=True)
                        self.message.reply_channel.send(
                            {
                                "text":
                                '\033[1;3;31mConnect to server! Server ip doesn\'t exist!\033[0m'
                            },
                            immediately=True)
                        self.message.reply_channel.send({"accept": False})
                        logger.error(
                            "Connect to server! Server ip {0} doesn\'t exist!".
                            format(ip))
                    try:
                        if method == 'password':
                            self.ssh.connect(ip,
                                             port=port,
                                             username=username,
                                             password=password,
                                             timeout=3)
                        else:
                            private_key = StringIO(key)
                            if 'RSA' in key:
                                private_key = paramiko.RSAKey.from_private_key(
                                    private_key)
                            elif 'DSA' in key:
                                private_key = paramiko.DSSKey.from_private_key(
                                    private_key)
                            elif 'EC' in key:
                                private_key = paramiko.ECDSAKey.from_private_key(
                                    private_key)
                            elif 'OPENSSH' in key:
                                private_key = paramiko.Ed25519Key.from_private_key(
                                    private_key)
                            else:
                                # self.message.reply_channel.send({"text": json.dumps(
                                # ['stdout', '\033[1;3;31munknown or unsupported key type, only support rsa dsa ed25519 ecdsa key type\033[0m'])}, immediately=True)
                                self.message.reply_channel.send(
                                    {
                                        "text":
                                        '\033[1;3;31munknown or unsupported key type, only support rsa dsa ed25519 ecdsa key type\033[0m'
                                    },
                                    immediately=True)
                                self.message.reply_channel.send(
                                    {"accept": False})
                                logger.error(
                                    "unknown or unsupported key type, only support rsa dsa ed25519 ecdsa key type!"
                                )
                            self.ssh.connect(ip,
                                             port=port,
                                             username=username,
                                             pkey=private_key,
                                             timeout=3)
                        # when connect server sucess record log
                        audit_log = Log.objects.create(
                            user=User.objects.get(username=self.message.user),
                            server=data,
                            channel=self.message.reply_channel.name,
                            width=width,
                            height=height)
                        audit_log.save()
                    except socket.timeout:
                        # self.message.reply_channel.send({"text": json.dumps(
                        # ['stdout', '\033[1;3;31mConnect to server time out\033[0m'])}, immediately=True)
                        self.message.reply_channel.send(
                            {
                                "text":
                                '\033[1;3;31mConnect to server time out\033[0m'
                            },
                            immediately=True)
                        logger.error(
                            "Connect to server {0} time out!".format(ip))
                        self.message.reply_channel.send({"accept": False})
                        return
                    except Exception as e:
                        # self.message.reply_channel.send({"text": json.dumps(
                        # ['stdout', '\033[1;3;31mCan not connect to server: {0}\033[0m'.format(e)])}, immediately=True)
                        self.message.reply_channel.send(
                            {
                                "text":
                                '\033[1;3;31mCan not connect to server: {0}\033[0m'
                                .format(e)
                            },
                            immediately=True)
                        self.message.reply_channel.send({"accept": False})
                        logger.error(
                            "Can not connect to server {0}: {1}".format(ip, e))
                        return

                    chan = self.ssh.invoke_shell(width=width,
                                                 height=height,
                                                 term='xterm')

                    # open a new threading to handle ssh to avoid global variable bug
                    sshterminal = SshTerminalThread(self.message, chan)
                    sshterminal.setDaemon = True
                    sshterminal.start()

                    directory_date_time = now()
                    log_name = os.path.join(
                        '{0}-{1}-{2}'.format(directory_date_time.year,
                                             directory_date_time.month,
                                             directory_date_time.day),
                        '{0}'.format(audit_log.log))

                    # open ssh terminal
                    interactivessh = InterActiveShellThread(
                        chan,
                        self.message.reply_channel.name,
                        log_name=log_name,
                        width=width,
                        height=height)
                    interactivessh.setDaemon = True
                    interactivessh.start()

                elif isinstance(data, list) and data[0] in ['stdin', 'stdout']:
                    self.queue.publish(self.message.reply_channel.name,
                                       json.loads(text)[1])
                elif isinstance(data, list) and data[0] == u'set_size':
                    self.queue.publish(self.message.reply_channel.name, text)
                elif isinstance(data, list) and data[0] == u'close':
                    self.disconnect(self.message)
                    return
                else:
                    # self.message.reply_channel.send({"text": json.dumps(
                    # ['stdout', '\033[1;3;31mUnknow command found!\033[0m'])}, immediately=True)
                    #self.message.reply_channel.send({"bytes": '\033[1;3;31mUnknow command found!\033[0m'}, immediately=True)
                    self.queue.publish(self.message.reply_channel.name, text)
                    #logger.error("Unknow command found!")
            elif bytes:
                self.queue.publish(self.message.reply_channel.name, bytes)
        except socket.error:
            audit_log = Log.objects.get(
                user=User.objects.get(username=self.message.user),
                channel=self.message.reply_channel.name)
            audit_log.is_finished = True
            audit_log.end_time = now()
            audit_log.save()
            self.closessh()
            self.close()
        except ValueError:
            self.queue.publish(self.message.reply_channel.name,
                               smart_unicode(text))
        except Exception as e:
            logger.error(traceback.print_exc())
            self.closessh()
            self.close()