1

We have a third-party Java application that uses System.console().readPassword() method. It cannot be modified. We need to call it from a non-interactive shell script that should pass password to that application. Piping password to the application does not appear to work. Is there a way to do this?

Test program:

import java.io.Console; public class Main { public static void main(String[] args) throws Exception { Console console = System.console(); if (console == null) { System.err.println("Cannot acquire console"); System.exit(-1); } char[] passwordArray = console.readPassword("Enter password: "); System.out.println("Password: " + String.valueOf(passwordArray)); } } 

Test shell script that does not work:

#!/bin/sh export TEST_PASSWORD="test password" echo "Test Password: $TEST_PASSWORD" echo $TEST_PASSWORD | java Main 
5
  • "Does not work" means that console equals null? Check out: stackoverflow.com/questions/5326406/… Commented Sep 26, 2024 at 14:25
  • use tools like expect or script Commented Sep 26, 2024 at 14:38
  • @elmiomar how? script "echo xx | java Main" still results in "Cannot acquire console". Voting to reopen so that someone can add a specific answer (the dupe is not directly relevant). Commented Sep 26, 2024 at 15:09
  • 2
    @k314159 If script doesn't work, try expect. You can find examples here: phoenixnap.com/kb/linux-expect. First, spawn your Java app, expect the "Enter password:" prompt, then send your password. Commented Sep 26, 2024 at 15:23
  • 1
    Thank you, @elmiomar. expect seems to do what I need. Commented Oct 3, 2024 at 14:00

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.