I want to create new User and give passwd from my java application which is developed using JAVA in the linux OS. maybe java call the shell script?
3 Answers
Java code to create a user in linux
public static void main(String[] args) {
try {
ProcessBuilder pb = new ProcessBuilder("sudo useradd username",
"sudo mkdir /home/username", "sudo passwd username",
"sudo chown username /home/username",
"sudo chgrp username /home/username",
"sudo adduser username", "sudo adduser username sudo");
pb.redirectErrorStream();
Process process = pb.start();
InputStream inputStream = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
process.waitFor();
} catch (Exception ex) {
ex.printStackTrace();
}
}
Comments
create/remove user accounts using the terminal
Adding A User Account
- You can add a user account from the terminal with this command:
sudo useradd username
Replace username with any name of your choice.
Create the home directory for this new user with this command:
sudo mkdir /home/username
Assign now a password for this user with this command:
sudo passwd username
Grant this user ownership and access to its home directory with these two commands:
sudo chown username /home/username
sudo chgrp username /home/username
You can also create a new user account with this command:
sudo adduser username
Grant Root Priviliges To A User Account (Optional)
If you want to give a user account root privileges so that it can execute "sudo" commands, run this command:
sudo adduser username sudo
Execute all commands using java Process class
Process p = Runtime.getRuntime().exec("////command////");
Comments
Sample shell script to add a user Based upon above discussion here is a sample shell script
#!/bin/bash
# Script to add a user to Linux system
if [ $(id -u) -eq 0 ]; then
read -p "Enter username : " username
read -s -p "Enter password : " password
egrep "^$username" /etc/passwd >/dev/null
if [ $? -eq 0 ]; then
echo "$username exists!"
exit 1
else
pass=$(perl -e 'print crypt($ARGV[0], "password")' $password)
useradd -m -p $pass $username
[ $? -eq 0 ] && echo "User has been added to system!" || echo "Failed to add a user!"
fi
else
echo "Only root may add a user to the system"
exit 2
fi
Close and save the script: $ ./adduser.sh
Only root may add a user to the system
Run as root:
./adduser
Output:
Enter username : manaf
Enter password : HIDDEN
User has been added to system!