SFTP basics

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the unix category.

Last Updated: 2024-04-19

Login exactly like ssh. It even seems to take the same CLI arguments

e.g. $ sftp jack@example.com -c aes128-cbc -i mykey

Once inside, type help to see all commands.

Run something in the underlying shell with ! command e.g. ! echo $UID

Set up (server side)

You basically create a special user that does not have regular login privileges:

useradd -g sftp_users -d /upload -s /sbin/nologin USERNAME

Explanation:

  1. -g add user to group sftp_users (arbitrary name),
  2. -d with home-dir /upload
  3. -s with shell /sbin/nologin which politely refuses a login attempt were that user to attempt to SSH in

Gotcha with log in

When working on the lab integration for Project S I had great trouble logging into both their SFTP and SSH servers. This was because they required both password (to login, not to de-encrypt the private key) and an SSH key.

The code for logging in would return false the first time(s) and this threw me. In reality the false represented a 3rd state "not yet".

Instead I should have simply run the remaining log in authentications.

<?php
  $sftp->login($username, $key)
  // returns false and tons of warnings
  $sftp->login($username, $password)
  // returns true

How to do this with ssh?

ssh user@ip -i mykey

Afterwards you will be asked for a password - then you are in.

Lesson

Even if something returns false for logged in, try the additional steps just in case.