Development for mail

Manage SSH authorized_keys in PHP

Today we’ll introduce a new convenient package to manage your SSH authorized_keys file via PHP.

If you want to manage SSH keys on a remote server, you’d usually use ssh-copy-id to add your public SSH key to the authorized_keys file on the server. This is actually nice since it will ask you for a password for this single moment where you can not authorize via public key. It also is smart enough to only add each key once.

However, for a small management tool we wanted to define a full list of all available SSH keys and a subset for each remote server. Thus we were in need for slightly more complex workflows including:

  • Update key comments (the last part of a key line), e.g. in case someone did not provide a useful one from the beginning.
  • Remove keys from remote servers, e.g. if someone leaves the company.

Since the management tool should be based on PHP and we didn’t want to fiddle with overly complex shell scripting we created a new package aptly named Authorized Keys. You can install it via Composer right now:

composer require pagemachine/authorized-keys

So what does it do?

This package manages the SSH authorized_keys file and allows us (and you) to add, update and remove arbitrary public keys. First of all you need to load your file:

$path = '/home/foo/.ssh/authorized_keys';
$authorizedKeys = AuthorizedKeys::fromFile($path);

Now you can add a key easily:

$key = new PublicKey('ssh-rsa AAA...');

The great thing here: you can call this method as often as you want, each key (identified by its content) will only be added once. But updates to options, type and comment will be performed. Removing a key looks basically the same:

$key = new PublicKey('ssh-rsa AAA...');

Again, it doesn’t matter how often you call this method, each key will only be removed once which makes these actions idempotent.

Comment lines and other keys are left untouched when adding/updating/removing keys. You can check the current state of the file content at any time by simply converting it to a string:

echo (string) $authorizedKeys;

Once you are done you can conveniently write back your changes to a file:


Aside from writing the file content this also ensures proper permissions.

This package will help us improve our workflows and we hope it can do the same for yours!

Unser erfahrenes Team steht Ihnen gerne bei der Entwicklung Ihrer Website zur Seite – von der Konzeption über das Design bis zur Codierung. Erfahren Sie mehr über unsere Dienstleistungen:

Kontaktieren Sie gerne uns unter .

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert