shell_executor.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. """
  2. agent67.tools.shell_executor — Shell 命令执行器
  3. Lambda: λ cmd_json. exec(cmd)
  4. """
  5. import json
  6. import os
  7. import subprocess
  8. from .safety import is_dangerous, needs_confirmation, ask_user_confirm
  9. def execute_shell(input_json: str) -> str:
  10. """
  11. 执行 shell 命令。
  12. 输入格式: {"command": "ls -la ~/Desktop"}
  13. """
  14. try:
  15. data = json.loads(input_json)
  16. cmd = data.get("command", input_json)
  17. except (json.JSONDecodeError, AttributeError):
  18. cmd = str(input_json).strip()
  19. if is_dangerous(cmd):
  20. return f"🚫 危险命令已拦截: {cmd}"
  21. if needs_confirmation(cmd):
  22. if not ask_user_confirm(f"执行命令: {cmd}"):
  23. return "❌ 用户取消了操作"
  24. try:
  25. result = subprocess.run(
  26. cmd, shell=True, capture_output=True, text=True,
  27. timeout=30, cwd=os.path.expanduser("~"),
  28. )
  29. output = result.stdout.strip()
  30. if result.returncode != 0 and result.stderr:
  31. output += f"\n[stderr] {result.stderr.strip()}"
  32. return output[:3000] if output else "(命令执行成功,无输出)"
  33. except subprocess.TimeoutExpired:
  34. return f"⏰ 命令超时 (30s): {cmd}"
  35. except Exception as e:
  36. return f"❌ 执行错误: {e}"