I want to query user credentials against an Active Directory without the user entering his credentials. i.e The user logs into his corporate system(Intranetwork) i need to use these credentials to verify against an AD and retrieve his email address if the user exists.(NO single sign on required)
Of course, It is too late to answer, but ... someone like me can search same answer...
I'm just not sure why do you need to verify user credentials?
If user already logged-in then ... credentials are verified.
Getting his email (and other info from AD) is possible by using Windows powershell.
public class TestWindowsAD {
public static void main(String... args) throws Exception {
System.out.println("Current user e-mail: " + getCurrentUserEmail());
}
private static String getCurrentUserEmail() {
String cmd = "powershell \"Add-Type -AssemblyName System.DirectoryServices.AccountManagement;[System.DirectoryServices.AccountManagement.UserPrincipal]::Current.EmailAddress;\"";
String userEmail = "";
if (!System.getProperty("os.name").toLowerCase().startsWith("win")) { throw new RuntimeException(
"We are not in Windows! OS is " + System.getProperty("os.name")); }
Runtime rt = Runtime.getRuntime();
Process pr;
try {
pr = rt.exec(cmd);
pr.waitFor();
BufferedReader bf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String nextLine = null;
while (true) {
nextLine = bf.readLine();
if (nextLine == null) break;
userEmail = nextLine;
}
bf.close();
} catch (Exception e) {
System.err.println("Failed to get user email: " + e.getMessage());
throw new RuntimeException(e);
}
return userEmail;
}
P.S. if you need more info just run in command prompt:
powershell "Add-Type -AssemblyName System.DirectoryServices.AccountManagement;[System.DirectoryServices.AccountManagement.UserPrincipal]::Current"
and pick what you need.
Related
I want to run a PowerShell command for create user using Java on a remote windows machine, I am writing this code in eclipse.
And below is the output, tried every reference and forms to resolve this issue can someone help me with this.
The command works on PowerShell command line, but it is not working in Java.
public class PowerShellSession {
private static String subModule = "PowerShellSession";
String targetIpAddress;
String username;
String password;
public static Object connectPShellLock = new Object();
public PowerShellSession() {}
public void exec(String cmd, String credentials) {
//String ex = "New-LocalUser -Name \"User02\" -Description \"Description of this account.\" -NoPassword";
String ex = credentials +" Invoke-Command -ScriptBlock {" + cmd + "} -ComputerName " + targetIpAddress +" -Credential $mycred";
String[] args = new String[] { "powershell", ex};
try {
execRemote(args);
} catch (IOException e) {
e.printStackTrace();
}
}
public void close() {
String command = "Exit-PSSession";
String[] args = new String[] { "powershell", command};
try {
execRemote(args);
} catch (IOException e) {
e.printStackTrace();
}
}
private String getCredentials(String domain, String userName,
String password) throws IOException {
String creds = "$Username = '"+userName+"';$PlainPassword ='" + password
+ "'; $SecurePassword = ConvertTo-SecureString -AsPlainText $PlainPassword -Force;"
+ "$mycred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username, $SecurePassword;";
//creds += "$session = New-PSSession -ComputerName " + domain + " -Credential $mycred;";
String[] args = new String[] { "powershell", creds};
execRemote(args);
return creds;
}
private void execRemote(String[] arguments) throws IOException {
ProcessBuilder builder = new ProcessBuilder(arguments);
builder.redirectErrorStream(true);
Process process = builder.start();
doProcessIO(process);
}
// Do the IO for a passed process
private void doProcessIO(Process p) throws IOException {
p.getOutputStream().close();
String line;
System.out.println("Output:");
BufferedReader stdout = new BufferedReader(new InputStreamReader(
p.getInputStream()));
while ((line = stdout.readLine()) != null) {
System.out.println(line);
}
stdout.close();
System.out.println("Error:");
BufferedReader stderr = new BufferedReader(new InputStreamReader(
p.getErrorStream()));
while ((line = stderr.readLine()) != null) {
System.out.println(line);
}
stderr.close();
System.out.println("Done");
}
public static void main(String[] args) throws IOException {
String ip_add = "192.168.193.101";
String user = "gs-259412";
String pass = "Windows412";
PowerShellSession psSession = new PowerShellSession();
String credentials = psSession.getCredentials(ip_add, user, pass);
psSession.targetIpAddress = ip_add;//;
String cmdd = "New-LocalUser -Name \"User02\" -Description \"Description of this account.\" -NoPassword";//"Get-Culture";
if(!credentials.equals("")) {
psSession.exec(cmdd, credentials);
System.out.println("Finished PowerShell remote session.");
}
psSession.close();
}
}
Output of this program :
Output:
Error:
Done
Output:
A positional parameter cannot be found that accepts argument 'of'.
+ CategoryInfo : InvalidArgument: (:) [New-LocalUser], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.NewLocalUserCommand
+ PSComputerName : 192.168.193.131
Error:
Done
Finished PowerShell remote session.
I tried this link also enter link description here
Hi Im using eclipse in Windows 10 OS.
Every time the user logins.I'm checking that particular user id last but one entry in the file and checking if the user is logged out or not.The file entries looks like
Here first parameter is timestamp,second is INFO,third is login or logout status and the numbers 10,1 and 3 are the userid
Now i need to check the last but one entry of that particular userid and change the value based on login or logged out.
I'm passing the userid to the function has an arguement so the JAVA code needs to check that particular userid's (which is passed as parameter) last but one entry
i have written the java code like this
public static boolean User(String userid) {
try {
String acc = userid;
File file = new File("C:\\Temp\\log\\bank.log");
Scanner myReader = new Scanner(file);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
String[] substrings = data.split("[:]");
if (substrings[5].contains(acc) && substrings[4].contains("Login Successful for user")) {
a = true;
} else {
a = false;
}
}
} catch (Exception e) {
e.printStackTrace();
}
Here I'm passing userid in User() function.What changes should be made so that i will be getting the information of the last but one entry of that particular userid in java.Could anyone please help me with the changes that should be made.
Try this:
public static boolean isLogin(String userId) {
try {
File file = new File("C:\\Temp\\log\\bank.log");
Scanner myReader = new Scanner(file);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
String[] substrings = data.split("[:]");
if (substrings[5].contentEquals(" " + userId) && substrings[4].contentEquals(" Login Successful for user")) {
return true;
} else {
return false;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
Below method return me below path
Output - "C:\ProgramData\MySQL\MySQL Server 5.5\bin\"
private String getPath() {
String mysqlpath = "";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(dbUrl, user, password);
Statement stmt = con.createStatement();
ResultSet res = stmt.executeQuery("select ##datadir");
while (res.next()) {
mysqlpath = res.getString(1);
}
mysqlpath = mysqlpath.replace("\\Data", "\\bin").replace("\\", "\\\\");
System.out.println("Mysql path is :" + mysqlpath);
} catch (Exception ee) {
System.out.println(ee);
}
return mysqlpath;
}
Now i run below command to export mysql dump.
Runtime runtime = Runtime.getRuntime();
Process p = runtime.exec(batchCommand);
batchCommand - "C:\ProgramData\MySQL\MySQL Server 5.5\bin\mysqldump" -h localhost --port 3306 -u root --password=root123 --add-drop-database -B accountingbook -r "E:\softwares\Tomcat_accountingBook\webapps\accountingbookaccountingbook-localhost-(02-08-2017).sql"
Exception - java.io.IOException: Cannot run program ""C:\ProgramData\MySQL\MySQL": CreateProcess error=2, The system cannot find the file specified
I also tried below, but same issue:-
1.) Process p = runtime.exec(batchCommand.split(" "));
2.) Adding double quotes like "C:\ProgramData\MySQL\MySQL Server 5.5\bin\"
Problem is it breaks as soon as it encounters space.
From the Exception, it looks like JVM is not able to find MYSQL executable file at the location given.
This can be due to "\" file separator. Try using "\\" to separate your paths. Then your path would be : "C:\\ProgramData\\MySQL\\MySQL.
I'v written one class this might help you click here
public class RuntimeExample {
private final String commandCode = "cmd /c";
private final Scanner scanner = new Scanner(System.in);
private Process process;
private BufferedReader reader;
private String input = "";
private final String defaultCode = "help";
public RuntimeExample() {
UserInput();
}
private void UserInput() {
System.out.println("Enter command (ex: ipconfig)");
input = scanner.nextLine();
if (input.isEmpty()) {
System.out.println("You didn't give any command please take a look at these available Commands." + "\n");
sendCommand(defaultCode);
} else {
sendCommand(input);
}
}
private void sendCommand(String command) {
try {
process = Runtime.getRuntime().exec(commandCode + " " + command);
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
showResult(line);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
private void showResult(String result) {
System.out.println(result + "\n");
}
public static void main(String[] args) {
new RuntimeExample();
}
}
I have 3 classes (Client, Server, and Protocol) that allow a user to login and send a message to another user. I'm trying to add a password feature to the program but nothing I've tried has worked so far. I've added my code below, I want to prompt the user to put the password in after the error checking on the username has been done. The password should be compared and checked that it is a match, and only then should the user be able to view their messages and send messages.
Any tips would really be appreciated, thanks!
Client.java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
String messages = "";
// Makes sure there are only two arguments entered
if(args.length != 2) {
System.err.println("Usage: java Client <host name> <port number>");
System.exit(1);
}
// Stores the command line arguments for readability further in the program
String host = args[0];
int port = Integer.parseInt(args[1]);
try (
// Creates the socket to be used
Socket s = new Socket(host, port);
// Reader and Writer to talk with Server
PrintWriter pw =
new PrintWriter(s.getOutputStream(), true);
BufferedReader bf = new BufferedReader(
new InputStreamReader(s.getInputStream()));
) {
// Reader to read from standard input (keyboard)
BufferedReader keyboard =
new BufferedReader(new InputStreamReader(System.in));
// User interface
while (true) {
System.out.println("Please enter your username: ");
String username = keyboard.readLine();
// Check that the login is valid
if (username == null) {
System.out.println("No username entered");
}
else if (username.contains(" ")) {
System.out.println("Username cannot contain spaces");
}
// Send username to server and return number of messages
else {
pw.println(username);
messages = bf.readLine();
System.out.println("You have " + Integer.parseInt(messages) + " messages");
break;
}
}
// Enable the user to continue reading and composing messages until
// they choose to exit
while (true) {
System.out.println("Would you like to READ, COMPOSE or EXIT?");
String choice = keyboard.readLine();
// Shows the messages left for the user
if (choice.equals("READ")) {
pw.println("READ");
messages = bf.readLine();
if (messages == "0") {
System.out.println("NO MESSAGES");
}
else {
String incoming = bf.readLine();
System.out.println(incoming);
incoming = bf.readLine();
System.out.println(incoming);
}
}
// Allows user to write a message to another user
else if (choice.equals("COMPOSE")) {
pw.println("COMPOSE");
System.out.println("Enter message recipient");
String recipient = keyboard.readLine();
if (recipient == null) {
System.out.println("No recipient username entered");
}
else if (recipient.contains(" ")) {
System.out.println("Recipient username cannot contain spaces");
}
else {
pw.println(recipient);
System.out.println("Enter message to be sent");
String im = keyboard.readLine();
pw.println(im);
System.out.println(bf.readLine());
}
}
else if (choice.equals("EXIT")) {
pw.println("EXIT");
System.exit(1);
}
else {
System.out.println("Error: you must either READ, COMPOSE or EXIT");
}
}
}
// Catches the exception in which the server cannot be found
catch(IOException e) {
System.out.println("Error, could not connect to Server");
System.exit(1);
}
}
}
Server.java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) {
String request;
// Makes sure that the user has specified the correct number of command line arguments
if(args.length != 1) {
System.err.println("Usage: java Server <port number>");
System.exit(1);
}
int port = Integer.parseInt(args[0]);
try (
// Creates a server socket and waits for a connection
ServerSocket ss = new ServerSocket(port);
// A socket to communicate with the client
Socket cs = ss.accept();
// Reader and Writer to talk with Client
PrintWriter pw =
new PrintWriter(cs.getOutputStream(), true);
BufferedReader bf = new BufferedReader(
new InputStreamReader(cs.getInputStream()));
)
// Links the server to the protocol
{
Protocol protocol = new Protocol();
protocol.storeUsername(bf.readLine());
pw.println(protocol.messagesNumber());
// Loop through user input until EXIT is entered
while (true) {
request = bf.readLine();
// Controls output if user inputs READ
if (request.equals("READ")) {
pw.println(protocol.messagesNumber());
pw.println(protocol.readSender());
pw.println(protocol.readMessage());
}
// Controls input if user inputs COMPOSE
else if (request.equals("COMPOSE")) {
String sender = bf.readLine();
String message = bf.readLine();
if (protocol.append(sender, message)) {
pw.println("MESSAGE SENT");
}
else {
pw.println("MESSAGE FAILED");
}
}
// Exits the server
else {
System.exit(1);
}
}
}
// Catches the exception in which the server cannot find a client
catch(IOException e) {
System.out.println("Failed to find a client");
System.exit(1);
}
}
}
Protocol.java
import java.net.*;
import java.io.*;
import java.util.*;
public class Protocol {
private String username;
private String recipient;
private String sender;
private HashMap<String, ArrayList<String>> senderMap = new HashMap<String, ArrayList<String>>();
private HashMap<String, ArrayList<String>> messageMap = new HashMap<String, ArrayList<String>>();
// Stores the username for the logged in user
public void storeUsername(String user) {
username = user;
}
// Stores the recipient name
public void storeRecipient(String name) {
recipient = name;
}
// Returns how many messages the logged in user has
public int messagesNumber() {
if(messageMap.containsKey(username))
return messageMap.get(username).size();
else
return 0;
}
public boolean append(String recipient, String message) {
boolean success = false;
// If there is an entry for that name, just add the message to the end
if(messageMap.containsKey(recipient)) {
senderMap.get(recipient).add(username);
messageMap.get(recipient).add(message);
success = true;
}
// If there is no entry for that name, create a new entry with a list of messages and add the first message
else {
senderMap.put(recipient, new ArrayList<String>());
senderMap.get(recipient).add(username);
messageMap.put(recipient, new ArrayList<String>());
messageMap.get(recipient).add(message);
success = true;
}
return success;
}
public String readSender() {
// If the user has an entry and has at least 1 sender, return the least recent sender and then remove it (the sender first in the list)
if(senderMap.containsKey(username)) {
if(senderMap.get(username).size() > 0) {
String temp = senderMap.get(username).get(0);
senderMap.get(username).remove(0);
return temp;
}
else
// If there are no messages left to read
return "NO MESSAGES";
}
else
// If the login hasn't been created yet
return "NO MESSAGES";
}
public String readMessage() {
// If the user has an entry and has at least 1 unread message, return the least recent unread message and then remove it (the first message in the list)
if(messageMap.containsKey(username)) {
if(messageMap.get(username).size() > 0) {
String temp = messageMap.get(username).get(0);
messageMap.get(username).remove(0);
return temp;
}
else
// If there are no messages left to read
return "NO MESSAGES";
}
else
// If the login hasn't been created yet
return "NO MESSAGES";
}
}
I have written a very simple program that reads in a username and password from a text file, where the username and password are separated by a comma. The contents of the text file contains the following
accounts.txt
Alex,1234
David,5678
My java application is written as follows
public class Authenticate {
public void signIn(String username, String password) throws IOException {
FileReader fr = new FileReader("location/accounts.txt");
BufferedReader br = new BufferedReader(fr);
while (true) {//read file line by line
String line = br.readLine();
if (line == null) {
break;
}
String splitByComma = ",";
String[] details = line.split(splitByComma);
String registeredUser = details[0];
String registeredPass= details[1];
if(username.equals(registeredUser) && password.equals(registeredPass)){
System.out.println("signed in successfully!");
}
else{
System.out.println("sign in failed");
}
}
br.close();
}
}
My App class which called the program:
public class App {
public static void main(String[] args) throws IOException {
Register register = new Register("location/accounts.txt");
Authenticate auth = new Authenticate();
auth.signIn("David", "5678");
}
}
The problem is when I pass in "Alex" "1234" in method for example, the output is
signed in successfully!
sign in failed
And when I pass in "David" "5678" i get
sign in failed
signed in successfully!
I want the application to output "signed in successfully" and "sign in failed" only once depending on the credentials entered.
Many thanks!
This means you are calling your method twice with different values. Check the calling code (which you haven't provided to us).
Other remarks:
Please don't consider something like this for serious authentication. Passwords should at least be hashed in your file (for example using BCrypt). There are many frameworks which offer industry strength authentication solutions which you should use instead of 'rolling your own'.
You should close resources in one of these ways:
1) in a finally block:
BufferedReader br = null;
try {
br = new BufferedReader(...);
// do stuff
}
finally {
if (br != null) {
br.close();
}
}
2) using the Java 8 try-with-resources idiom:
try (BufferedReader br = new BufferedReader(...)) {
// do stuff
}
(the BufferedReader will be automatically closed by the runtime environment)
In your example above you should probably check the input for null values before checking the values with .equals.
First search for the user name. Once found, check the password and exit the loop:
public class Authenticate {
public void signIn(String username, String password) throws IOException {
try (
FileReader fr = new FileReader("location/accounts.txt");
BufferedReader br = new BufferedReader(fr);
) {
boolean success = false;
String line;
while ((line = br.readLine()) != null) {
String[] details = line.split(",");
String registeredUser = details[0];
if (registeredUser.equals(username)) {
String registeredPass = details[1];
success = registeredPass.equals(password);
break;
}
}
System.out.println(success ? "signed in successfully!" : "sign in failed");
}
}
}