Deepak Kr. Karn Deepak Kr. Karn - 2 months ago 20
Bash Question

How to pass username and password in a shell script using java

I have a shell script. Now I want to pass

NAME
and
PASS
in this script using java. Then I want to execute it using
java
. Below I have written here my
shell
script as well as java code.

Please help me out.

#!/bin/bash

# Create ftp user, create folders and set permissions
# Usage: ./create_ftp_user.sh [username] "[password]"
#

NAME=bimal
PASS=bimal

echo "USAGE: create_ftp_user.sh [username] [password]"

# check input parameters
if [ -z "$NAME" ]; then
echo "Error: username is not set"
exit
fi

if [ -z "$PASS" ]; then
echo "Error: password not set"
exit
fi

# create system user
echo "Creating user: $NAME"
echo "With password: $PASS"

useradd -p `openssl passwd -1 $PASS` -m $NAME -g ftpaccess -s /usr/sbin/nologin

# save to users log
echo "user: $NAME, pass: $PASS" >> new_ftp_users_list

# add user to ftp daemon list
echo "$NAME" >> /etc/vsftpd/chroot_list

# create user ftp dir
mkdir /var/ftpupload/$NAME

# Set Ownership
chown $NAME: /var/ftpupload/$NAME

# Set permissions
chmod 0777 /var/ftpupload/$NAME

# restart vsftp daemon
#/etc/init.d/vsftpd restart


/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package testscript;

/**
*
* @author deepak
*/
import java.io.IOException;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;

public class TestScript {
int iExitValue;
String sCommandString;

public void runScript(String command){
sCommandString = command;
CommandLine oCmdLine = CommandLine.parse(sCommandString);
DefaultExecutor oDefaultExecutor = new DefaultExecutor();
oDefaultExecutor.setExitValue(0);
try {
iExitValue = oDefaultExecutor.execute(oCmdLine);
} catch (ExecuteException e) {
// TODO Auto-generated catch block
System.err.println("Execution failed.");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
System.err.println("permission denied.");
e.printStackTrace();
}
}

public static void main(String args[]){
TestScript testScript = new TestScript();
testScript.runScript("gksudo sh /home/deepak/Desktop/ftpusers.sh");
}
}

Answer

The CommandLine can be used to set shell arguments:

CommandLine oCmdLine = new CommandLine(sCommandString);
oCmdLine.addArgument("bimal");
oCmdLine.addArgument("bimalPassword");

You can refer various options on Apache CommandLine documentation page.

Once done, the arguments will be available in shell script as $1 and $2 positional shell parameters:

NAME=$1
PASS=$2