6

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!

3
  • 1
    Why do you try to do this? Please edit your question to explain more the actual use case. Commented Mar 15, 2015 at 11:30
  • Please explain more why you want to do that, and what exactly are the remote commands you intend to run. It smells very bad. Commented Mar 15, 2015 at 11:45
  • I will downvote the question, because you don't explain the context and why you want to do that. There might be other better ways to achieve your goal. Commented Mar 15, 2015 at 11:49

1 Answer 1

7

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");
 fclose(remf);

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

addenda

(added in september 2016)

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

Sign up to request clarification or add additional context in comments.

3 Comments

Regarging the use of popen() it might be worth mentioning that the ssh-client's output cannot be read if the call is to popen() was done to write to the ssh-client.
This is why I was redirecting to remoteoutput.txt
Oh yes, nice. I overlooked this, sorry.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.