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 user@000.000.000.000 -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?
nohup /bin/bash /root/reverse.sh
and I have also changed the ssh command inside the script tonohup /usr/bin/sshpass -p mypassword ssh -f -N -M -S /tmp/socketuser000.000.000.000 -p 0000 user@000.000.000.000 -R 21022:localhost:22 -R 21080:localhost:80 -o StrictHostKeyChecking=no
. Unfortunately I am getting the same behaviour where the SSH connection is closed when the service is stopped. – PauMAVA Mar 29 '21 at 10:39& disown
at the end of the commands as described here https://unix.stackexchange.com/questions/421539/nohup-is-not-working-as-i-am-exiting-the-terminal which also didn't work. – PauMAVA Mar 29 '21 at 10:48