This actually works pretty well, until I noticed that if the MySQL command fails for some reason, the return code of that pipe will still be 0, because ssh started and terminated successfully. SSH notices that, closes stdin for cat and cat terminates. your terminal.Īnd now comes the fun part: After that output, MySQL will close its output stream. The cat is sitting on the remote host (assh, i.e. It also instructs the local MySQL to connect to what it assumes to be the local host and run a command there. This will open an SSH connection to remotehost, set up port forwarding and call cat on the remote host. You might want to think about that for a second. (Note that I'm using 127.0.0.1 on purpose here: When using localhost, I found that MySQL often uses the Unix socket instead of TCP.) not do nasty things with sleep or whateverĪnd then I came up with this: mysql -e 'SHOW DATABASES ' -h 127.0.0.1 | ssh -L 3306:localhost:3306 remotehost cat.make SSH terminate after that command terminates and.start SSH when a certain command starts running and.(Yes, you could sleep 3 or something after backgrounding SSH with & or even do sophisticated checks, but that's really ugly and there's a far better way of doing it.) Not putting it in the background at all Without that, all following commands risk trying to connect to a port that has not been opened yet. And you want -f because it has a really cool feature: It waits until the connection and (if combined with -o ExitOnForwardFailure=yes) the port forwardings have been set up successfully before going into the background. If you background it with &, you can kill $! or kill %1, but not with -f. But then you have to close that SSH connection again when you're done, and even if your script crashes or is killed etc.Īlso, closing the connection isn't that easy. If you want your local script to continue to run, you'd possibly send that SSH process to the background using something like ssh -L 3306:localhost:3306 remotehost & (note the ampersand) or ssh -fN -L 3306:localhost:3306 remotehost (with -f for "fork into background" and -N for "run no command"). … well, and then what? Now you have a shell on the remote machine open and your script execution stops until that connection is terminated again. So, basically you would do something like ssh -L 3306:localhost:3306 remotehost We didn't want to open the MySQL port to the network, but it's possible to SSH from the Jenkins machine to the MySQL machine. That tool doesn't know that the database is on another host, plus the MySQL port on that host is firewalled and not accessible from other machines.From an unattended shell script (called by Jenkins), run a command-line tool that accesses the MySQL database on another host.Opening and closing an SSH tunnel in a shell script the smart way
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |