Search code examples
cscp

How to scp from a C program?


The following C program compiles and spits out a a directory listing of "/Users/home/tempdir" directory.

#include <stdio.h>
#include <unistd.h>
int main(int argc, const char * argv[])
{
        execl("/bin/ls", "ls", "/Users/home/tempdir");
        // execl("/usr/bin/scp", "scp", "myfile.txt home@127.0.0.1:/Users/home/scpdir");
    return 0;
}

This shows it is possible to execute a binary file from a C program. I am trying to figure out how to execute the "scp" binary file and input the required passphrase. How can I modify the above code to achieve a successful file transfer via scp ?

I attempted the line that is commented out above however I get the following message when it is uncommented:

usage: scp [-1246BCEpqrv] [-c cipher] [-F ssh_config] [-i identity_file]
           [-l limit] [-o ssh_option] [-P port] [-S program]
           [[user@]host1:]file1 ... [[user@]host2:]file2

So it's obviously trying to perform the scp without the password. How do I get around this?


Solution

  • While you could call scp from the command line using expect or something, you are much better off using a library if at all possible.

    The general rule when developing is to prefer libraries to system executions whenever possible. It keeps your code cleaner and more portable. The exception is if you are writing a shell script.

    http://www.libssh2.org/

    libssh2 is a free C library that supports password authentication as well as SCP/SFTP and supports OS X.

    http://curl.haxx.se/libcurl/

    libcurl supports pretty much every file transfer type you could want, works on just about every platform you could want, and has bindings for pretty much every language you could want.