How to user droplet UserData to change sshd_config

January 27, 2017 164 views
Deployment Debian

I'm trying the following code to change the IP ssh listens to. Unfortunately this doesn't work as I can't successfully connect after droplet is created.

Tested in an existing dropley with su privileges it works. I'm creating a droplet from an image where su only have access after authentication. Does it have any connection?

I'm trying this on a Debian 8.

!/bin/bash

apt-get update
export PRIVATEIPV4=$(curl -s http://169.254.169.254/metadata/v1/interfaces/private/0/ipv4/address)
sed -i "s/.ListenAddress./ListenAddress $PRIVATE
IPV4 /g" /etc/ssh/sshd_config
ssh restart

2 Answers

@admin87f7492443

You should be able to use something such as:

sed -i "0,/ListenAddress.*/c\ListenAddress $PRIVATEIPV4" /etc/ssh/sshd_config

Since there's two instances of ListenAddress in the default Debian sshd_config file, when you run your sed, it actually modifies both instances as the s/ and /g matches all instances, not just one.

By default, you'll see:

#ListenAddress ::
#ListenAddress 0.0.0.0

When running your sed replacement, you end up with:

ListenAddress PRIVATE_IP ::
ListenAddress PRIVATE_IP 0.0.0.0

Where PRIVATE_IP is your Droplet Private IP.

When running the command I've provided, it'll only modify the first instance and it'll remove the line entirely and replace it with just:

ListenAddress PRIVATE_IP

That said, unless you're connecting over a VPN, you won't be able to connect to SSH using the Private IP, so if you plan on connecting sans VPN, you'd need to change that to the public IP.

Hi Thanks for answering.
Indeed, my sed command was replacing both lines. But that is not an issue to log in to ssh, after I manually give a reset cycle from dashboard.

The problem is that ssh restart doesn't do anything.
I assume this is because in the image I'm building from I removed root access, and the other 2 users have not access to run commands without password.

I also added

#cloud-config
power_state:
  mode: reboot

with no success

Have another answer? Share your knowledge.