MIRMIX MIRMIX - 6 months ago 59
Linux Question

Using ssh via C code

I tried to connect to ssh using following code in C

system("ssh DestinationPC")

It works now it wants password from me. What is the easiest way to send it and how can I send some terminal commands using C?

Any kind of good answers or suggestions will be appreciated!


You need to setup your ssh appropriately, e.g. using public keys, to avoid any password been asked. Any good ssh tutorial explains that.

(don't even think of sending the password programatically; it is possible, but is very unsecure and ugly)

Then you either need to give a command to run by ssh e.g.

 int err = system("ssh DestinationPC rm /tmp/badfile.txt")

or you could use popen(3) to send several commands (you need to redirect the output):

 FILE* remf = popen("ssh DestinationPC > remoteoutput.txt", "w");
 if (!remf) { perror("popen ssh failed"); exit(EXIT_FAILURE); };
 fprintf(remf, "gcc somesource.c -Wall -o somebinary\n");
 fprintf(remf, "./somebinary");

but this might be insecure.

Be sure to understand what code injection means and to carefully try to avoid it.

You probably will construct your command string (e.g. using snprintf(3). Be careful (buffer overflow, truncation, code injection, argument quoting...). Check every input-related data going into that command string.

You might be interested in OpenSSL.

You might also use two pipe(7)-s (one for input, one for output from the fork-ed ssh process) then you'll need some event loop probably around poll(2).

In general, be very careful about security issues.

Unless you know well what you are doing, coding system("ssh DestinationPC...") is often a bad idea (and a recipe for disasters). At least document when and how your software is doing that. Look also into MPI


(added in september 2016)

You might be interested in libssh instead of executing some ssh command with system or popen...