mibacode
mibacode

Reputation: 404

C: How to kill a process on another machine through SSH?

I am looking to run a program written in C on my machine and have it SSH into another machine to kill a program running on it.

Inside my program, I have attempted:

system("ssh [email protected] && pkill sleep && exit");

which will cause my terminal to SSH into the remote machine, but it ends there. I have also tried:

execl("ssh","ssh","[email protected]",NULL);
execl("pkill","pkill","sleep",NULL);
execl("exit","exit",NULL);

but it will not kill my dummy sleep process I have running.

I can't seem to figure out what is wrong with my process.

Upvotes: 0

Views: 2421

Answers (2)

Allan
Allan

Reputation: 41

one can always run, over ssh, the command:

kill $(pgrep -o -f 'command optional other stuff')

Get your remote process to handle SIGTERM, where it can do its cleanup's. (including killing any processes its started)

Google 'man pgrep' to see what the -o and -f do. -f is important to correctly target the signal. the 'pgrep' returns the pid with trailing \n but this does not need to be stripped off before passing it to 'kill'. Yours Allan

Upvotes: 0

abligh
abligh

Reputation: 25129

Your second example won't do what you want as it will execute each execl on the local machine. IE it will

But, actually, unless you are surrounding these by fork, the first execl if it succeeds in running at all will replace the current process, meaning the second and third ones never get called.

So, let's work out why the first (more hopeful) example doesn't work.

This should do the equivalent of:

/bin/sh -c 'ssh [email protected] && pkill sleep && exit'

The && exit is superfluous. And you want the pkill to run on the remote machine. Therefore you want something that does:

/bin/sh -c 'ssh [email protected] pkill sleep'

(note the absence of && so the pkill is run on the remote machine).

That means you want:

system("ssh [email protected] pkill sleep");

If that doesn't work, check the command starting /bin/sh -c above works. Does ssh ask for a password, for instance? If so, it won't work. You will need to use a public key.

Upvotes: 4

Related Questions