I have a jar file which will let me connect to an instance. Once I run the command java -jar jarname in command line it will ask for username and password. Is there a way I can give the username and password as parameter in command line ?
Is there a way I can give the username and password as parameter in command line while running a jar
Asked
Active
Viewed 3,781 times
-1
-
I tries by proving the username and password but its still prompting for the same – user3825800 Jun 24 '19 at 06:00
-
Perhaps `java -jar bla.jar < credentials.txt` will do ? Put user and pass each on its own line. This is not very secure but might do the job if you can't modify the jar. If you can: show the source – Marged Jun 24 '19 at 06:00
-
giving error Username: Password: Exception in thread "main" java.util.NoSuchElementException: No line found at java.util.Scanner.nextLine(Unknown Source) – user3825800 Jun 24 '19 at 06:03
-
1We have no idea what it is that you're running and how it asks for username and password, or what command line options or configurations it has. You should contact the company or person who wrote the software that you're running. In addition it doesn't seem like a programming question either (unless you're running a programming-related tool) – Erwin Bolwidt Jun 24 '19 at 06:07
1 Answers
3
Here are 3 options:
Option 1
If you want to read the arguments in main method, use :
java -jar yourjar.jar user1 pass1
and then in your code:
public static void main(String [] args) {
String user = args[0]; // = user1
String passwd = args[1]; // = pass1
}
Option 2
Alternatively if you want to pass system properties, then use -D
:
java -jar -Duser=user1 -Dpasswd=pass1 yourjar.jar
And then in java:
String user = System.getProperty("user"); // user1
String passwd = System.getProperty("pass"); // pass1
Option 3
You can also pass data via Environment Variables, but you should set them first in some script:
set USER_NAME = "user1"
set PASSWD = "passwd1"
Then you run:
java -jar yourjar.jar // note, nothing is passed here
In java you can read the environment variables like this:
System.getenv("USER_NAME"); // user1
System.getenv("PASSWD"); // passwd1

Mark Bramnik
- 39,963
- 4
- 57
- 97
-
I also have similar requirement where i have a java code (jar file) that will connect to another instance based on username and pass provided in the cmd line on execution, did the above solution worked for you? – user803860 Aug 19 '19 at 18:22