modify ssh_config ip addresses based on current ip

0

I'd like to be able to modify ssh_config aliases based on my current IP address.

I have a laptop which I carry around from network to network, and a camera which I do the same with. I have setup the dhcp on these networks to always give the camera the same IP address, and I calculate what it should be in my bashrc and put the camera IP into an environment variable.

Is there any way to do something like the following inside ~/.ssh/config:

Host camera
    HostName $CAMERA_IP
    User camuser

The above doesn't work as ssh complains:

ssh: Could not resolve hostname $CAMERA_IP: Name or service not known

Sandy Patterson

Posted 2014-01-31T13:14:08.410

Reputation: 33

you could just add an alias in your hosts file ... instead of the ssh_config – Paul Bastide – 2014-01-31T13:15:53.133

But I want to do it based on my IP. I don't think the hosts file is aware of my user's environment either is it? – Sandy Patterson – 2014-01-31T13:21:23.677

you can just alias it. add an entry like IP camera – Paul Bastide – 2014-01-31T13:21:47.460

Yeah, but if I get the ssh alias's to work I get scp and rsync aliases all too. – Sandy Patterson – 2014-01-31T13:24:42.657

it'll all work if you just reference camera – Paul Bastide – 2014-01-31T13:25:15.007

I'm not sure I understand, you want to create aliases like sshcamera and scpcamera to work around modifying ~/.ssh/config? – Sandy Patterson – 2014-01-31T13:26:27.367

Answers

2

Since you are doing calculation in your bashrc, you can also generate the ssh_config you need from a template using sed.

The template (.ssh/ssh_config_t):

Host camera
    Hostname IP_PH
    user camuser

The script in bashrc

sed -e "s/IP_PH/$CAMERA_IP/" ~/.ssh/ssh_config_t > ~/.ssh/ssh_config

M'vy

Posted 2014-01-31T13:14:08.410

Reputation: 3 540

+1 41 seconds faster than me :) – zelanix – 2014-01-31T14:56:46.913

That's a good idea. I can even edit the ~/.ssh/config directly with sed since I know what the IP addresses that I set are. – Sandy Patterson – 2014-01-31T15:21:44.257

0

I think how I would solve this would be to use a template config file as follows.

~/.ssh/config_template:

Host camera
    HostName $CAMERA_IP
    User camuser

And then a simple update script.

~/.ssh/update_config.sh:

#!/bin/bash

# Do whatever to set $CAMERA_IP
CAMERA_IP=192.168.1.1

# Update config file
sed "s/\$CAMERA_IP/$CAMERA_IP/" ~/.ssh/config_template > ~/.ssh/config

And then just call ~/.ssh/update_config.sh from your bashrc file. Just remember to not make any manual changes to ssh_config.

zelanix

Posted 2014-01-31T13:14:08.410

Reputation: 1 134