Skip to main content
Glama
sfz009900

Kali Linux MCP Server

by sfz009900

execute_command

Execute commands in a Kali Linux penetration testing environment via MCP server, enabling security testing, vulnerability scanning, and password cracking without interactive prompts.

Instructions

(无需交互式比如ping 127.0.0.1)在Kali Linux渗透测试环境中执行命令。支持所有Kali Linux内置的安全测试工具和常规Linux命令。

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
commandYes要在Kali Linux环境中执行的命令。可以是任何安全测试、漏洞扫描、密码破解等渗透测试命令。

Implementation Reference

  • Tool schema definition for 'execute_command', including input schema requiring 'command' parameter.
    {
      name: "execute_command",
      description: "(无需交互式比如ping 127.0.0.1)在Kali Linux渗透测试环境中执行命令。支持所有Kali Linux内置的安全测试工具和常规Linux命令。",
      inputSchema: {
        type: "object",
        properties: {
          command: {
            type: "string",
            description: "要在Kali Linux环境中执行的命令。可以是任何安全测试、漏洞扫描、密码破解等渗透测试命令。"
          }
        },
        required: ["command"]
      }
    },
  • src/index.ts:73-156 (registration)
    Registration of 'execute_command' tool in the ListToolsRequestSchema handler.
    server.setRequestHandler(ListToolsRequestSchema, async () => {
      return {
        tools: [
          {
            name: "execute_command",
            description: "(无需交互式比如ping 127.0.0.1)在Kali Linux渗透测试环境中执行命令。支持所有Kali Linux内置的安全测试工具和常规Linux命令。",
            inputSchema: {
              type: "object",
              properties: {
                command: {
                  type: "string",
                  description: "要在Kali Linux环境中执行的命令。可以是任何安全测试、漏洞扫描、密码破解等渗透测试命令。"
                }
              },
              required: ["command"]
            }
          },
          {
            name: "start_interactive_command",
            description: "(需要交互式比如mysql -u root -p)在Kali Linux环境中启动一个交互式命令,并返回会话ID。交互式命令可以接收用户输入,可以在不close_interactive_command的情况下同时执行execute_command。",
            inputSchema: {
              type: "object",
              properties: {
                command: {
                  type: "string",
                  description: "要在Kali Linux环境中执行的交互式命令。"
                }
              },
              required: ["command"]
            }
          },
          {
            name: "send_input_to_command",
            description: "(自行判断是AI输入还是用户手动输入)向正在运行的交互式命令发送用户输入。",
            inputSchema: {
              type: "object",
              properties: {
                session_id: {
                  type: "string",
                  description: "交互式会话ID。"
                },
                input: {
                  type: "string",
                  description: "发送给命令的输入文本。"
                },
                end_line: {
                  type: "boolean",
                  description: "是否在输入后添加换行符。默认为true。"
                }
              },
              required: ["session_id", "input"]
            }
          },
          {
            name: "get_command_output",
            description: "获取交互式命令的最新输出。",
            inputSchema: {
              type: "object",
              properties: {
                session_id: {
                  type: "string",
                  description: "交互式会话ID。"
                }
              },
              required: ["session_id"]
            }
          },
          {
            name: "close_interactive_command",
            description: "关闭交互式命令会话。",
            inputSchema: {
              type: "object",
              properties: {
                session_id: {
                  type: "string",
                  description: "交互式会话ID。"
                }
              },
              required: ["session_id"]
            }
          }
        ]
      };
    });
  • MCP CallToolRequest handler case for 'execute_command' that validates input, calls CommandExecutor.executeCommand with realtime, and formats response.
    case "execute_command": {
      const command = String(request.params.arguments?.command);
      if (!command) {
        throw new McpError(ErrorCode.InvalidParams, "命令是必需的");
      }
      const env = {};
      const timeout = 30000000;
    
      try {
        log.info(`准备执行命令: ${command}`);
        
        // 执行命令,启用实时推送
        const result = await commandExecutor.executeCommand(command, {
          timeout: timeout,
          env: env as Record<string, string>,
          enableRealtime: true
        });
        
        log.info("命令执行成功");
        
        return {
          content: [{
            type: "text",
            text: `命令输出:\nstdout: ${result.stdout}\nstderr: ${result.stderr}`
          }]
        };
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        log.error(`命令执行失败: ${errorMessage}`);
        throw new McpError(
          ErrorCode.InternalError,
          `无法执行Kali Linux命令: ${errorMessage}`
        );
      }
    }
  • Core implementation of command execution via SSH in CommandExecutor.executeCommand, supporting realtime delegation, timeout, env vars, and output cleaning.
    async executeCommand(
      command: string,
      options: {
        timeout?: number; // 命令执行超时时间(毫秒)
        cwd?: string; // 工作目录
        env?: Record<string, string>; // 环境变量
        enableRealtime?: boolean; // 是否启用实时推送
      } = {}
    ): Promise<{ stdout: string; stderr: string }> {
      const { timeout = 30000000, cwd = '/', env = {}, enableRealtime = false } = options;
      
      if (!this.isConnected) {
        throw new Error('SSH未连接,请先调用connect方法');
      }
    
      // 如果启用实时推送,使用实时执行方法
      if (enableRealtime) {
        return await this.executeCommandWithRealtime(command, { timeout, cwd, env });
      }
    
      try {
        log.info(`执行命令: ${command}`);
        log.debug(`命令超时: ${timeout}ms, 工作目录: ${cwd}`);
        
        // 如果有环境变量,构建环境变量设置命令
        let execCommand = command;
        if (Object.keys(env).length > 0) {
          const envSetup = Object.entries(env)
            .map(([key, value]) => `export ${key}="${String(value).replace(/"/g, '\\"')}"`)
            .join(' && ');
          execCommand = `${envSetup} && ${command}`;
        }
        
        // 执行命令,带超时控制
        const result = await Promise.race([
          this.ssh.execCommand(execCommand, { cwd }),
          new Promise<never>((_, reject) => {
            setTimeout(() => {
              reject(new Error('命令执行超时'));
            }, timeout);
          })
        ]) as { stdout: string; stderr: string };
        
        log.debug(`命令执行完成,stdout长度: ${result.stdout.length}, stderr长度: ${result.stderr.length}`);
        
        // 清理输出中的ANSI转义序列
        return {
          stdout: stripAnsiCodes(result.stdout),
          stderr: stripAnsiCodes(result.stderr)
        };
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        log.error(`命令执行失败: ${errorMessage}`);
        
        if (errorMessage.includes('超时')) {
          // 超时情况返回已收集的输出
          return { stdout: '命令执行时间过长,已被中断', stderr: '命令执行超时' };
        }
        
        throw error;
      }
    }
  • Helper function to strip ANSI escape codes from command output for clean text response.
    export function stripAnsiCodes(str: string): string {
      if (!str) return '';
      
      // 先移除所有零值字符(\u0000)和其他控制字符
      const strWithoutControlChars = str.replace(/[\x00-\x08\x0B-\x1F]/g, '');
      
      // 分步处理不同类型的ANSI序列和控制码
      let result = strWithoutControlChars
        // 移除标准ANSI转义序列
        .replace(/\x1B(?:[@-Z\\-_]|\[[0-9?;]*[0-9A-Za-z])/g, '')
        // 移除括号B开头的控制序列 (B[0;7m(B[m 等
        .replace(/\(B\[[0-9;]*m/g, '')
        // 移除单纯的(B序列
        .replace(/\(B/g, '')
        // 移除[?数字h格式的序列 [?2004h 等
        .replace(/\[\?[0-9]+[a-z]/g, '')
        // 移除单独出现的控制序列(如[0m, [4m等)
        .replace(/\[[0-9;]+m/g, '');
      
      // 处理可能遗漏的其他特殊序列
      result = result.replace(/\[[0-9;]*[A-Za-z]/g, '');  // 任何剩余的 [数字字母 序列
      
      return result;
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions the environment (Kali Linux penetration testing) and command types, but lacks critical behavioral details: it doesn't specify execution context (e.g., shell, permissions, isolation), output handling, error behavior, security implications, or rate limits. For a command execution tool with zero annotation coverage, this is a significant gap.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is concise and front-loaded, with two sentences that directly address the tool's function and scope. The first sentence states the core purpose with a clarifying exclusion, and the second sentence expands on supported commands. There's minimal wasted text, though it could be slightly more structured.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity of a command execution tool in a security context, with no annotations and no output schema, the description is incomplete. It lacks details on execution behavior, output format, error handling, and security warnings, which are crucial for safe and effective use. The description doesn't compensate for the absence of structured data.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema has 100% description coverage, with the 'command' parameter well-documented in the schema itself. The description adds marginal value by reinforcing the command types (security testing, vulnerability scanning, password cracking) and the Kali Linux context, but doesn't provide additional syntax, format, or constraint details beyond what the schema already states.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: '在Kali Linux渗透测试环境中执行命令' (execute commands in a Kali Linux penetration testing environment). It specifies the verb (execute) and resource (commands) with context (Kali Linux, penetration testing). However, it doesn't explicitly differentiate from sibling tools like 'start_interactive_command' or 'get_command_output', which appear related to command execution workflows.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides some implied usage context by mentioning '(无需交互式比如ping 127.0.1)' (no interactive commands like ping 127.0.0.1) and listing supported command types (security testing, vulnerability scanning, password cracking). However, it doesn't explicitly state when to use this tool versus alternatives like 'start_interactive_command' or provide clear exclusions beyond the interactive example.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Related Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/sfz009900/kalilinuxmcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server