How to check whether user exists in Linux (JSch)

Viewed 435

I am connecting/creating users in Linux machine using JSch. I am successfully able to connect Linux machine and create users. But i'm not able to check whether that user already exists or not in machine, while creating user. For this i tried command: id -u name

And my implementation is:

System.out.println("Connected");

Channel channel=session.openChannel("exec");
((ChannelExec)channel).setCommand("id -u name");
channel.setInputStream(null);
((ChannelExec)channel).setErrStream(System.err);

InputStream in=channel.getInputStream();
channel.connect();

But it doesn't tell whether its true or false. How to do this using JSch to check whether user exists in Linux?.

1 Answers

You are reading the InputStream that will have the user's id if you are asking for an existing user, but if you are asking for a user that is not in the system, the output will be written in the error stream. If you want to read one stream, you could modify your command to print the exit status of the last command executed.

session.connect();
ChannelExec channel = (ChannelExec) session.openChannel("exec");
channel.setCommand("id -u name; echo $?");
channel.connect();

The output if you ask for an exist user will have 2 lines, the first one will be the user's id, and the second one will be 0 that means executed successfully, if the user doesn't exists the content of the stream will be different of 0 that means command failed to execute.

Related