Example #1
0
    def execute_script(self, local_path, node, timeout=10, json_out=True):
        """Copy local_path script to node, execute it and return result.
        
        Returns (rc, stdout, stderr tuple).
        """

        ssh = SSH()
        ssh.connect(node)

        local_basename = os.path.basename(local_path)
        remote_file_path = self.__TMP_DIR + local_basename
        remote_file_out = remote_file_path + ".out"

        ssh.scp(local_path, remote_file_path)

        cmd = "sudo -S {vat} {json} < {input}".format(
            vat=self.__VAT_BIN,
            json="json" if json_out == True else "",
            input=remote_file_path)
        (ret_code, stdout, stderr) = ssh.exec_command(cmd, timeout)
        self._ret_code = ret_code
        self._stdout = stdout
        self._stderr = stderr

        logger.trace("Command '{0}' returned {1}'".format(cmd, self._ret_code))
        logger.trace("stdout: '{0}'".format(self._stdout))
        logger.trace("stderr: '{0}'".format(self._stderr))

        #TODO: download vpp_api_test output file
        self._delete_files(node, remote_file_path, remote_file_out)
Example #2
0
    def execute_script(self, local_path, node, timeout=10, json_out=True):
        """Copy local_path script to node, execute it and return result.
        
        Returns (rc, stdout, stderr tuple).
        """

        ssh = SSH()
        ssh.connect(node)

        local_basename = os.path.basename(local_path)
        remote_file_path = self.__TMP_DIR + local_basename
        remote_file_out = remote_file_path + ".out"

        ssh.scp(local_path, remote_file_path)

        cmd = "sudo -S {vat} {json} < {input}".format(vat=self.__VAT_BIN, 
                json="json" if json_out == True else "",
                input=remote_file_path)
        (ret_code, stdout, stderr) = ssh.exec_command(cmd, timeout)
        self._ret_code = ret_code
        self._stdout = stdout
        self._stderr = stderr

        logger.trace("Command '{0}' returned {1}'".format(cmd, self._ret_code))
        logger.trace("stdout: '{0}'".format(self._stdout))
        logger.trace("stderr: '{0}'".format(self._stderr))

        #TODO: download vpp_api_test output file
        self._delete_files(node, remote_file_path, remote_file_out)
Example #3
0
    def __extract_tarball_at_node(self, tarball, node):
        logger.console('Extracting tarball to {0} on {1}'.format(
            con.REMOTE_FW_DIR, node['host']))
        ssh = SSH()
        ssh.connect(node)

        cmd = 'rm -rf {1}; mkdir {1} ; sudo -Sn tar -zxf {0} -C {1};'.format(
            tarball, con.REMOTE_FW_DIR)
        (ret_code, stdout, stderr) = ssh.exec_command(cmd, timeout=30)
        if 0 != ret_code:
            logger.error('Unpack error: {0}'.format(stderr))
            raise Exception('Failed to unpack {0} at node {1}'.format(
                tarball, node['host']))
Example #4
0
    def setup_dut(self, node):
        ssh = SSH()
        ssh.connect(node)

        ssh.scp('resources/libraries/bash/dut_setup.sh', '/tmp/dut_setup.sh')
        (ret_code, stdout, stderr) = \
            ssh.exec_command('sudo -Sn bash /tmp/dut_setup.sh')
        logger.trace(stdout)
        if 0 != int(ret_code):
            logger.error('DUT {0} setup script failed: "{1}"'.
                    format(node['host'], stdout + stderr))
            raise Exception('DUT test setup script failed at node {}'.
                    format(node['host']))
Example #5
0
    def __extract_tarball_at_node(self, tarball, node):
        logger.console('Extracting tarball to {0} on {1}'.format(
            con.REMOTE_FW_DIR, node['host'])) 
        ssh = SSH()
        ssh.connect(node)

        cmd = 'rm -rf {1}; mkdir {1} ; sudo -Sn tar -zxf {0} -C {1};'.format(
                tarball, con.REMOTE_FW_DIR)
        (ret_code, stdout, stderr) = ssh.exec_command(cmd, timeout=30)
        if 0 != ret_code:
            logger.error('Unpack error: {0}'.format(stderr))
            raise Exception('Failed to unpack {0} at node {1}'.format(
                tarball, node['host']))
Example #6
0
def main(self, line):
    args = line.split()
    ssh = SSH()
    if len(args) == 0:
        print '''Usage: 
    addhost save_name hostname user [password]
    connect save_name
    connect hostname user password
    '''
        return
    if args[0] == 'addhost':
        ssh.addhost(' '.join(args[1:]))
    elif args[0] == 'connect':
        ssh.connect(' '.join(args[1:]))
    elif args[0] == 'listhost':
        ssh.listhost()
    elif args[0] == 'delhost':
        ssh.delhost(' '.join(args[1:]))
    else:
        print __file__.__doc__
        return
Example #7
0
    def __copy_tarball_to_node(self, tarball, node):
        logger.console('Copying tarball to {0}'.format(node['host']))
        ssh = SSH()
        ssh.connect(node)

        ssh.scp(tarball, "/tmp/")
Example #8
0
    def __copy_tarball_to_node(self, tarball, node):
        logger.console('Copying tarball to {0}'.format(node['host']))
        ssh = SSH()
        ssh.connect(node)

        ssh.scp(tarball, "/tmp/")
Example #9
0
 def _delete_files(self, node, *files):
     ssh = SSH()
     ssh.connect(node)
     files = " ".join([str(x) for x in files])
     ssh.exec_command("rm {0}".format(files))
Example #10
0
 def _delete_files(self, node, *files):
     ssh = SSH()
     ssh.connect(node)
     files = " ".join([str(x) for x in files])
     ssh.exec_command("rm {0}".format(files))
Example #11
0
class WebSSH(WebsocketConsumer):
    message = {'status': 0, 'message': None}
    """
    status:
        0: ssh 连接正常, websocket 正常
        1: 发生未知错误, 关闭 ssh 和 websocket 连接
    message:
        status 为 1 时, message 为具体的错误信息
        status 为 0 时, message 为 ssh 返回的数据, 前端页面将获取 ssh 返回的数据并写入终端页面
    """

    # status = {'code': 1001, 'error': ''}

    def connect(self):
        try:
            self.accept()
            query_string = self.scope['query_string']
            connect_argv = QueryDict(query_string=query_string,
                                     encoding='utf-8')
            server_id = connect_argv.get('server_id')
            user = connect_argv.get('user')
            width = connect_argv.get('width')
            height = connect_argv.get('height')

            width = int(width)
            height = int(height)

            connect_info = get_object_or_404(models.Server, id=server_id)

            host = connect_info.alias
            port = connect_info.ssh_port
            # auth = ''
            # pkey = ''

            # connect_info.delete()

            if user == str("root"):
                #     # password = base64.b64decode(pwd).decode('utf-8')
                password = connect_info.ssh_user_root_password
            else:
                password = connect_info.ssh_user_other_password

            self.ssh = SSH(websocker=self, message=self.message)
            # self.ssh = SSH(websocker=self)

            self.ssh.connect(host=host,
                             user=user,
                             password=password,
                             port=port,
                             pty_width=width,
                             pty_height=height)

            # if auth == 'key':
            #     pkey = pkey
            #     obj = StringIO()
            #     obj.write(pkey)
            #     obj.flush()
            #     obj.seek(0)
            #     self.pkey = obj
            #
            #     self.ssh.connect(
            #         host=host,
            #         user=user,
            #         password=password,
            #         pkey=self.pkey,
            #         port=port,
            #         pty_width=width,
            #         pty_height=height
            #     )
            # else:
            #     self.ssh.connect(
            #         host=host,
            #         user=user,
            #         password=password,
            #         port=port,
            #         pty_width=width,
            #         pty_height=height
            #     )
        except Exception as e:
            self.message['status'] = 1
            self.message['message'] = str(e)
            message = json.dumps(self.message)
            self.send(message)
            self.close()

    def disconnect(self, close_code):
        try:
            self.ssh.close()
        except:
            pass

    def receive(self, text_data=None, bytes_data=None):
        data = json.loads(text_data)
        if type(data) == dict:
            status = data['status']
            if status == 0:
                data = data['data']
                self.ssh.shell(data)
            else:
                cols = data['cols']
                rows = data['rows']
                self.ssh.resize_pty(cols=cols, rows=rows)