0

I'd like to call the bash script nsupdate from java, in order to implement a kind of DDNS. The problem is no matter what I do, nsupdate won't take the input I'm trying to write.

This is the current way I'm trying to do it:

    public static void main(String[] args) throws IOException, InterruptedException {
        
        ProcessBuilder builder = new ProcessBuilder("nsupdate", "-i");
        builder.redirectOutput(ProcessBuilder.Redirect.PIPE);
        Process process = builder.start();

        BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
        BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));

        PrintWriter w = new PrintWriter(process.getOutputStream());
        w.println("server 127.0.0.1\r");
        w.println("update delete sub.domain.dev. A\r");
        w.println("update add sub.domain.dev. 2 A 12.23.45.56\r");
        w.println("send\r");
        w.println("quit\r");

        process.waitFor(10, TimeUnit.SECONDS);
        
        process.destroy();
        

    }

I have tried a lot of ways, but nothing seems to work. Unfortunately, I can't use a file to pass as a parameter, even though that way worked the best so far.

László Stahorszki
  • 1,102
  • 7
  • 23

2 Answers2

1

I think you also need to redirect the process input:

builder.redirectInput(ProcessBuilder.Redirect.PIPE);
Allen D. Ball
  • 1,916
  • 1
  • 9
  • 16
  • no, I just needed to flush the output stream after every command – László Stahorszki Jul 19 '20 at 19:45
  • 1
    It it works... You could wrap your `PrintWriter` statement into a try-with-resources block to have it automatically closed (and flushed): `try PrintWriter w = new PrintWriter(process.getOutputStream())) { ... }` – Allen D. Ball Jul 19 '20 at 19:59
  • great idea, however I wouldn't want to close the stream every time I print a new line. I will wrap the whole function (the part where I use the writer) in it, thank you – László Stahorszki Jul 19 '20 at 20:41
0

I realized that I need to flush the output stream after every command

László Stahorszki
  • 1,102
  • 7
  • 23