silverAndroid
silverAndroid

Reputation: 1050

How do I run a local command before starting SSH connection and after SSH connection closes?

Essentially what I want to do is run a Bash script I created that switches WiFi SSIDs before starting the SSH connection, and after the SSH connection closes.

I have added this to ~/.ssh/config by setting ProxyCommand to ./run-script; ssh %h:%p but by doing this, I feel like it would ignore any parameters I passed when I run the ssh command. Also, I have no idea how to get the script to run again when the SSH connection closes.

Upvotes: 10

Views: 11236

Answers (2)

Popup
Popup

Reputation: 376

For OpenSSH you can specify a LocalCommand in your ssh config (~/.ssh/config).

But for that to work you also need the system-wide option (in /etc/ssh/ssh_config) PermitLocalCommand to yes. (By default it is set to no.)

It gets executed on the local machine after authenticating but before the remote shell is started.

There appears to be no (easy) way of executing something after the connection has been closed, though.

Upvotes: 4

dash-o
dash-o

Reputation: 14452

Assuming that it is not possible to implement a wrapper to 'ssh' (using alias, or some other method), it is possible to implement the following in the proxyCommand.

Important to note that there is no protection against multiple invocation of 'ssh' - possible that during a specific invocation that WIFI is already connected. Also, it is possible that when a specific ssh is terminated, the WIFI has to stay active because of other pending conditions.

Possible implementation of the proxy script is ProxyCommand /path/to/run-script %h %p

#! /bin/sh
pre-command      # connect to WIFI
nc -N "$1" "$2"     # Tunnel, '%h' and '%p' are passed in
post-command     # Disconnect WIFI

You do not want to use simple ssh in the proxy script, as this will translate into another call to the 'run-script'. Also note that all options provided to the original ssh will be handled by the initial 'ssh' session that will be leveraging the proxy 'nc' tunnel.

Upvotes: 2

Related Questions