I want to run the following commands:-
# su - username
$ ssh-keygen -t rsa
enter 3 time to pass null to ssh-keygen options then
$ cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
$ chmod 0600 ~/.ssh/authorized_keys
$ tar xzf tarpath
$ mv untaredfile ~/somename
on shell terminal but via Java i.e I need to automate these commands,in which username and tarpath will be provided dynamically through gui.
I tried executing it with java Runtime but was not able to get the expected result each time I call
Runtime.getRuntime().exec("somecommand");
it creates a new instance of that command so all previous command doesn't exists in it.Like switching to user.
can anyone suggest me any solution either a custom shell script or through ProcessBuilder.
To pass to 3 times enter
for ssh-keygen -t rsa
, you can try:
echo -e "\n\n\n" | ssh-keygen -t rsa
or use following command to prevent the passphrase prompt and set the key-pair file path to default path:
ssh-keygen -t rsa -N "" -f ~/.ssh/id_rsa
To warp multiple command into one and execute it with a switched user, you can try su username -c
or other Shell language:
su username -c 'ssh-keygen -t rsa -N "" -f ~/.ssh/id_rsa ; cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys'
To execute the process with Java, you can try use ProcessBuilder
:
String username = "user";
String command = "ssh-keygen -t rsa -N \"\" -f ~/.ssh/id_rsa ; cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys";
ProcessBuilder processBuilder = new ProcessBuilder("su", username, "-c", command);
Process process = processBuilder.start();