-1

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.

Ap00rv
  • 128
  • 1
  • 11

1 Answers1

0

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();
Wilson
  • 11,339
  • 2
  • 29
  • 33
  • you can use `su username -c` to replace `bash -c` – Wilson Jul 01 '16 at 19:59
  • Which part do not work? the `su` command, `ssh-keygen` command or the Java code? I tested the command before I post and I works fine. I updated my answer a little bit. Please see whether it help. – Wilson Jul 02 '16 at 04:44