How to execute a bash command in C and retrieve output? - c

I'm trying to execute a bash command from c and retrieve and show the result.
I've tried with system but it doesn't work.
My code looks like:
char command[200];
sprintf(command,"lsof -iTCP:%d | cut -d\"\" -f1 | tail -1",port);
printf("Port %d is open\n and is listened by %s",port,system(command));
Please help. I need this .

Edit aside from the actual question, I'd be using
sudo netstat -tlpn
(shows the processes that are listening on TCP ports, not resolving the ports/addresses)
Perhaps combine it with a bit of grep:
sudo netstat -tlpn | grep :7761
to find where port :7761 is being listened?
You can use popen.
With popen you get the benefit that you receive the process output asynchronously (you will be able to stop processing if the answer is on the first line of output without having to wait for the subprocess to complete; simply pclose and the subprocess will die with SIGPIPE)
A sample straight from the Standards Documentation:
The following example demonstrates the use of popen() and pclose() to execute the command ls * in order to obtain a list of files in the current directory:
#include <stdio.h>
...
FILE *fp;
int status;
char path[PATH_MAX];
fp = popen("ls *", "r");
if (fp == NULL)
/* Handle error */;
while (fgets(path, PATH_MAX, fp) != NULL)
printf("%s", path);
status = pclose(fp);
if (status == -1) {
/* Error reported by pclose() */
...
} else {
/* Use macros described under wait() to inspect `status' in order
to determine success/failure of command executed by popen() */
...
}

system(command) returns the return code of the command, not its output.
If you want to read the output of a command, you should use popen
This returns a file descriptor to the output, which you can read from just like a normal file.

Related

How can i execute this shellcode " ls PathToDirectory > newFile.txt" in C to create a new file with the list of content of the directory [duplicate]

This question already has answers here:
Output redirection using fork() and execl()
(2 answers)
Closed 3 years ago.
How can I execute this shellcode ls PathToDirectory > newFile.txt in C to create a new file with the list of content of the directory.
I've tried but this gives me always an error. "ls: cannot access '>': No such file or directory"
I am using this code :
execl( "/bin/ls","ls","PathToTheDirectory" ,">","newFileTocreate.txt" , NULL);
Output:
ls: cannot access '>': No such file or directory
newFileTocreate.txt
"Show the content of the directory"
One way would be to use the system call like this example in dols.c
#include <stdio.h>
#include <stdlib.h>
int main(){
int ret = system("ls > listing.txt");
if (ret) printf("ERROR: non-zero return %d", ret);
}
compile and run and check
[C]$ gcc dols.c
[C]$ ./a.out
[C]$ more listing.txt
a.out
dols.c
Output redirection > is a shell construct that's not understood by execl family functions; they don't invoke a shell to run commands.
What happens is > is passed as an argument to ls which, therefore, says there's no such file in your current directory.
You have few options:
You can use popen(3) to run the command & read the output and then you can write to the file.
char buf[1024] = {0};
FILE *fp = popen("/bin/ls PathToTheDirectory");
while(fgets(buf, sizeof buf, fp)) {
/* write to newFileToCreate.txt */
}
open(2) the file and duplicate((with dup2) its stdout and then exec it so that output is written to the file.
int fd = open("newFileToCreate", O_WRONLY | O_CREAT | O_TRUNC);
dup2(fd, STDOUT_FILENO);
execl( "/bin/ls", "ls", "PathToTheDirectory", NULL);
Use system(3) which invokes a shell. So you can the command as you have. Although, be aware that this option should be avoided whenever possible. See Issuing system commands in Linux from C, C++
system("/bin/ls PathToTheDirectory > newFileTocreate.txt");

How to enter in to network namespace and read the file content using C program

In my Linux machine, i have configured the network namespace. With shell script or command line or system command I was able to fetch the file content present in the network namespace.
ip netns exec test_namespace cat /var/test_namespace/route.conf
Output:
cardIP=10.12.13.1
In a C program, I can use system("ip netns exec test_namespace cat /var/test_namespace/route.conf") command to get the output. But I prefer not to use this option.
Looking for an alternative method, I am not sure about the system call setns, how to use it. Any ideas?
If you're alergic to system, you can use popen to read the script output as a file:
Example
/* the command to execute */
FILE *f = popen("ls", "r");
/* Here, we should test that f is not NULL */
printf("result of `ls`:\n");
/* read process result */
char buffer[256];
while (fgets(buffer, sizeof buffer, f)
{
puts(buffer);
}
/* and close the process */
pclose(f);

get the text printed due to executing cmd command in c

I have a binary file which prints the result instead of returning the value, if I execute it using cmd I am getting printed text, I managed to execute it from C code but it seems like I can not get the text it usually prints to be stored in a variable I can use later for further decisions.
I do not have that much of experience in C and I googled a lot.
I came across the idea of using clip but my cmd is saying that clip command can not be found.
any help or ideas would be appreciated.
The correct function pair to use on POSIX systems is popen() and
pclose(). You can perhaps use Microsoft's _popen() and
_pclose() unless the warning 'This API cannot be used in applications that execute in the Windows Runtime' matters to you.
You would use it more or less like this. I've had to invent the name of the command you wish to execute since the question doesn't specify that. I chose ./example.exe as the name — and I'm assuming it needs no arguments.
char cmd[] = "./example.exe";
FILE *fp = popen(cmd, "r");
if (fp != NULL)
{
char buffer[4096];
size_t nbytes;
while ((nbytes = fread(buffer, sizeof(buffer), sizeof(char), fp)) != 0)
{
…process nbytes of data…
…it is not a null-terminated string unless you add the null byte…
}
pclose(fp);
}
else
{
…report error for failure to execute command…
}
You can use the system function from <stdlib.h> to run the command you want. To get the command's output, you modify your command like in this question to save the command's output to a file. Then you can use the file I/O functions in <stdio.h> to process the command output.
In Linux, you may do command substitution and pass its result as arguments to the program, Something like this
./your_program "$(/path/to/your/binary/file)"
Suppose your main is
int main(int argc,char* argv[]){
.
.
return 0;
}
Acess the arguments like argv[1] and so.
Here the $(command) does the substitution and it passes the printed values from the binary as arguments to the pgm. Hope this helps.
Use snprintf function. For e.g.
snprintf(cmdbuff, BUFFER_LEN, "dmidecode --type 17 | grep -i Size | grep -o '\\<[0-9]*\\>' | paste -sd+ | bc");
Here cmdbuff is character array where command will be stored , BUFFER_LEN is a size of the character array
Then use popen and fgets to get the output of command into some buffer as shown below
if((fd = popen(cmdbuff,"r")) != NULL)
{
fgets(buffer, BUFFER_LEN, fd);
sprintf(vnfc_configured_memory, "%s", buffer);
vnfc_configured_totalRAM = atof(vnfc_configured_memory);
}

how to write the output of a process run using execl to a file in c

I am writing a c program in which it calls a process using execl() function. I get the output of the process along with my c program output. I need to store the output of the process called using execl() to a file. I know programming basics and also file input and output.
Here is my program:
#include<stdio.h>
#include<unistd.h>
main()
{
printf("\nDisplaying output of ifconfig\n");
execl("/sbin/ifconfig","ifconfig",NULL);
}
Output:
Displaying output of ifconfig
eth1 Link encap:Ethernet HWaddr 02:00:00:a1:88:21
...........
lo Link encap:Local Loopback
........
I need to store the output of ifconfig in the file. How can i do it?
You can use popen to run the program instead of calling execl, and read the out and write it to a file. Or use the system function, which invokes a shell and therefore can contain full shell redirection.
Or open the file using open and then use dup2 to redirect it to STDOUT_FILENO.
Actually, using the exec functions like that is highly unusual. Normally you create a new process and call exec in the child process.
Using open and dup2 is what I suggest in this case:
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
...
/* Open the file for writing (create it if it doesn't exist) */
int fd = open("/path/to/file", O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP);
/* Make the standard output refer to the newly opened file */
dup2(fd, STDOUT_FILENO);
/* Now we don't need the file descriptor returned by `open`, so close it */
close(fd);
/* Execute the program */
execl("/sbin/ifconfig","ifconfig",NULL);
Note: I do not have any kind of error handling in the above code, which you should have.
/* Open the command for reading. */
fp = popen("COMMAND", "r");
if (fp == NULL) {
printf("Failed to run command\n" );
exit;
}
/* Read the output a line at a time - output it. */
while (fgets(buffer, sizeof(buffer)-1, fp) != NULL) {
printf("buffer = %s", buffer);
}
/* close */
pclose(fp);

calling commands using 'system()' from inside a program

I want to execute some executable files from inside a C program using system(). I want to ensure that the command executed completely; after that, I want to use the output of the previously executed command. For example:
{
...
...
sprintf(cmd, "./a1.out > temp.txt");
system(cmd);
fp = fopen("temp.txt", "r");
...
...
}
In this example, it is not ensured that cmd executed completely after that the file is opened for reading. And, I want to ensure that. Any help?
You can use popen() to execute the command and read its output directly.
fp = popen("./a1.out", "r");
if (fp) {
...
r = pclose(fp);
if (r < 0) {
/*...command exited abnormally */
}
} else {
/*...fork or pipe error */
}
You can choose to write the data to a file if that is what is required.
I don't know about the os you are using but under Linux the manual says
system() executes a command specified in command by calling /bin/sh -c command, and returns after the command has been completed.
Moreover Posix says
The system() function shall not return until the child process has terminated.
So you are sure that the command is completed.

Resources