running shell script using c program
7,547
Here is a fixed version of your code:
// Compile with:
// gcc c-shellscript.c -o c-shellscript
#include <stdio.h>
#include <stdlib.h>
#define SHELLSCRIPT "\
printf 'Password Please:';\n\
stty -echo;\n\
read pass;\n\
stty echo;\n\
printf '\\n';\n\
sleep 2;\n\
echo $pass;"
int main()
{
puts("Will execute sh with following script:");
puts("---------");
puts(SHELLSCRIPT);
puts("---------");
puts("Starting now");
system(SHELLSCRIPT);
return 0;
}
However, I don't think it is good practice to do things this way. It is also much much easier to create a separate shellscript file and just call that instead, even if you generate the shellscript file from within your code.
Have a look at these for more info:
- https://stackoverflow.com/questions/3736210/how-to-execute-a-shell-script-from-c-in-linux
- https://stackoverflow.com/a/646260/105315
- https://stackoverflow.com/questions/245600/using-a-single-system-call-to-execute-multiple-commands-in-c
Related videos on Youtube
Author by
Deepansh Kapoor
Updated on September 18, 2022Comments
-
Deepansh Kapoor over 1 year
I wrote a script to hide user input during runtime it works as a simple script but i want to integrate into c program but gives following errors:
warning: missing whitespace after macro name error: expected ')' before 'Password'
can someone tell me what i'm doing wrong.
Here's the c program:
#include"header.h" #define SHELLSCRIPT"\ #bin/bash\n\ printf"Password Please:"\n\ stty -echo\n\ read pass\n\ stty echo\n\ printf'\n'\n\ sleep"2"\n\ echo "$pass"\n\ " int main() { puts("Will execute sh with following script:"); puts("SHELLSCRIPT"); puts("Starting now"); system(SHELLSCRIPT); return 0; }
-
KIAaze about 8 yearsThis is a programming question and is more appropriate for stackoverflow.com .
-
David Foerster about 8 yearsWhy do you even bother to write a C program if you end up running an Sh script anyway? That is not to say you can't change the
echo
state of the terminal in plain C. Alternatively you could use one of the existing programs that safely ask the user for a password.
-
-
ShadowRunner over 6 yearsone advantage of using c to launch a script is that you can then set the c program as executable but not readable (the script still needs to be readable to be executed, but can be "hidden" somewhere else)