As discussed in the following StackOverflow question I am creating a Java program that starts a reverse SSH tunnel. I have created a script
/root/reverse.sh that starts a subshell and creates a detached ssh reverse session:
#!/bin/bash ( /usr/bin/sshpass -p mypassword ssh -f -N -M -S /tmp/socketuser000.000.000.000 -p 0000 firstname.lastname@example.org -R 21022:localhost:22 -R 21080:localhost:80 -o StrictHostKeyChecking=no )
Then this script is executed from java as:
Process process = Runtime.getRuntime().exec("/bin/bash /root/reverse.sh"); int result = process.waitFor();
The connection works just fine, the problem comes when I stop the java program, which is registered as a system service:
systemctl stop myapp
When the java process is killed the reverse ssh connection is killed too. I have checked via
pstree that the reverse ssh process parent is PID 1 and not Java.
$ pstree -sg 2185 systemd(1)───ssh(2185)
I don't understand why when I kill the Java process the ssh process is killed too as it's not a child of the Java process. Why does this happen? Has this something to do with process groups? How can I prevent the ssh process from being killed?