I have a function like this
void smbProcess(){
string smbTargetIP;
cout<<"Target IP: ";
cin>>smbTargetIP;
string commandSmb_S = "crackmapexec smb " + smbTargetIP;
int smbLength = commandSmb_S.length();
char commandSmb_C[smbLength + 1];
strcpy(commandSmb_C, commandSmb_S.c_str());
system("xterm -hold -e commandSmb_C");
}
I want to create a new terminal and run my command (like this "crackmapexec smb 192.168.1.0/24"). But it doesn't work. When I try this, it works
system("xterm -hold -e date");
These are also doesn't work
system("xterm -hold -e 'commandSmb_C'");
system("xterm -hold -e "commandSmb_C"");
If you know another way to do this it will works too
Add "xterm -hold -e" to commandSmb_S
void smbProcess(){
string smbTargetIP;
cout<<"Target IP: ";
cin>>smbTargetIP;
string commandSmb_S = "xterm -hold -e crackmapexec smb " + smbTargetIP;
int smbLength = commandSmb_S.length();
char commandSmb_C[smbLength + 1];
strcpy(commandSmb_C, commandSmb_S.c_str());
system(commandSmb_C);
}
I'm using the Boost process header and I can't seem to get the boost::process::system to take in my .cpp file path due to a space in the directory.
auto path = bp::search_path("g++");
int result = bp::system(path, "\"C:\\Users\\Sachin Chopra\\Documents\\rchat\\console_process\\src\\main.cpp\"");
I get the following error when I execute my code:
g++.exe: error: "C:\Users\Sachin: Invalid argument
g++.exe: error: Chopra\Documents\rchat\console_process\src\main.cpp": No such file or directory
g++.exe: fatal error: no input files
The file path formatting works for me .exe file, and will launch from boost if I use it. e.g.
bp::system("\"C:\\Users\\Sachin Chopra\\Documents\\rchat\\build\\console_process\\consoleproc.exe\"");
But when I introduce the g++ path, it seems to mess up. Any help would be appreciated.
Cheers.
You're confusing shell script with the system interface.
You can either use old style, error-prone system:
bp::system(R"(bash -c "echo hello; echo world")");
Or you can pass raw arguments instead of relyng on shell escaping
bp::system(bp::search_path("bash"),
std::vector<std::string>{
"-c",
"echo foo; echo bar",
});
Which could also be written more like
bp::system(bp::search_path("bash"), "-c", "echo 42; echo answer");
In fact, you should probably use the bp::child interace instead of the
system compatible one:
bp::child compiler_job(
bp::search_path("g++"),
R"(C:\Users\Sachin Chopra\Documents\rchat\console_process\src\main.cpp)");
compiler_job.wait_for(5s);
if (compiler_job.running()) {
compiler_job.terminate();
}
int result = compiler_job.exit_code();
std::cout << "compiler_job exit_code: " << result << "\n";
Live Demo
Live On Coliru
#include <boost/process.hpp>
#include <iostream>
namespace bp = boost::process;
using namespace std::chrono_literals;
int main() {
// either use old style, error-prone system
bp::system(R"(bash -c "echo hello; echo world")");
// or pass raw arguments instead of relyng on shell escaping
bp::system(bp::search_path("bash"),
std::vector<std::string>{
"-c",
"echo foo; echo bar",
});
// Which can aslo be written as
bp::system(bp::search_path("bash"), "-c", "echo 42; echo answer");
// in fact, you should probably use the `bp::child` interace instead of the
// `system` compatible one:
bp::child compiler_job(
bp::search_path("g++"),
R"(C:\Users\Sachin Chopra\Documents\rchat\console_process\src\main.cpp)");
compiler_job.wait_for(5s);
if (compiler_job.running()) {
compiler_job.terminate();
}
int result = compiler_job.exit_code();
std::cout << "compiler_job exit_code: " << result << "\n";
}
Prints e.g.
hello
world
foo
bar
42
answer
g++: error: C:\Users\Sachin Chopra\Documents\rchat\console_process\src\main.cpp: No such file or directory
g++: fatal error: no input files
compilation terminated.
compiler_job exit_code: 1
Qt 5.12
I am trying to get the volume ID on macOS and using the following function:
QString getVolumeInfo()
{
QString volumeID = "Cannot find the volumeID";
QProcess p;
//diskutil info $(df -h / | tail -1 | cut -d' ' -f 1)
QString command = "diskutil";
QStringList args;
args << "info" << "$(df -h / | tail -1 | cut -d' ' -f 1)";
p.start(command, args);
p.waitForStarted();
p.waitForFinished();
foreach(QString line, QString(p.readAll()).split("\n"))
{
if(line.contains("Volume UUID:"))
volumeID = line;
}
return volumeID;
}
I have to use the diskutil because of the limitation with macOS. However, QProcess, reading the object has nothing in it.
Command on terminal: diskutil info $(df -h / | tail -1 | cut -d' ' -f 1)
which returns a ton of information like:
...
SMART Status: Verified
Volume UUID: 954BACF1-EBC5-4D14-86FB-0912CF7F839C
Disk / Partition UUID: 954BACF1-EBC5-4D14-86FB-0912CF7F839C
Disk Size: 500.1 GB (500068036608 Bytes) (exactly 976695384 512-Byte-Units)
....
When I try to add qDebug() to debug I get the following: true - "Could not find disk: $(df -h / | tail -1 | cut -d' ' -f 1)\n"
So seem like the arguments is not formatted or something?
I am trying to implement: https://apple.stackexchange.com/questions/50302/how-can-i-tell-which-volume-the-operating-system-is-on
The slight modification after Eelke explained.
QStringList args;
args << "-c" << "diskutil info $(df -h / | tail -1 | cut -d' ' -f 1)";
p.start("/bin/bash", args);
I have the following code :
char command[256];
sprintf(command,"addr2line %p -e xcep_app", trace[i]);
addr2lineWriter = popen(command, "r");
if (addr2lineWriter == NULL)
flag = false;
if (flag == true) //execute parsing the output only if the command ran in the first place
{
while (fgets(addr2line_output, sizeof(addr2line_output)-1, addr2lineWriter) != NULL)
{
std::string addr2line_output_(addr2line_output);
complete_backtrace_.push_back(addr2line_output_);
}
pclose(addr2lineWriter);
}
Everything works fine, but I always get the following message :
sh: 1: Syntax error: word unexpected (expecting ")")
Why is it coming and how to stop it. also, what does it mean ?
I have the gnome terminal installed.
This is a guess based on the error message. trace[i] is NULL, so the command generated is:
addr2line (nil) -e xcep_app
And so the shell that is invoked to execute the command complains about the parentheses. #WumpusQ.Wumbley reports that ash will reproduce this message:
ash -c 'addr2line (nil) -e xcep_app'
So this is probably a long shot, but is there any way to run a C or C++ file as a script? I tried:
#!/usr/bin/gcc main.c -o main; ./main
int main(){ return 0; }
But it says:
./main.c:1:2: error: invalid preprocessing directive #!
Short answer:
//usr/bin/clang "$0" && exec ./a.out "$#"
int main(){
return 0;
}
The trick is that your text file must be both valid C/C++ code and shell script. Remember to exit from the shell script before the interpreter reaches the C/C++ code, or invoke exec magic.
Run with chmod +x main.c; ./main.c.
A shebang like #!/usr/bin/tcc -run isn't needed because unix-like systems will already execute the text file within the shell.
(adapted from this comment)
I used it in my C++ script:
//usr/bin/clang++ -O3 -std=c++11 "$0" && ./a.out; exit
#include <iostream>
int main() {
for (auto i: {1, 2, 3})
std::cout << i << std::endl;
return 0;
}
If your compilation line grows too much you can use the preprocessor (adapted from this answer) as this plain old C code shows:
#if 0
clang "$0" && ./a.out
rm -f ./a.out
exit
#endif
int main() {
return 0;
}
Of course you can cache the executable:
#if 0
EXEC=${0%.*}
test -x "$EXEC" || clang "$0" -o "$EXEC"
exec "$EXEC"
#endif
int main() {
return 0;
}
Now, for the truly eccentric Java developer:
/*/../bin/true
CLASS_NAME=$(basename "${0%.*}")
CLASS_PATH="$(dirname "$0")"
javac "$0" && java -cp "${CLASS_PATH}" ${CLASS_NAME}
rm -f "${CLASS_PATH}/${CLASS_NAME}.class"
exit
*/
class Main {
public static void main(String[] args) {
return;
}
}
D programmers simply put a shebang at the beginning of text file without breaking the syntax:
#!/usr/bin/rdmd
void main(){}
See:
https://unix.stackexchange.com/a/373229/23567
https://stackoverflow.com/a/12296348/199332
For C, you may have a look at tcc, the Tiny C Compiler. Running C code as a script is one of its possible uses.
$ cat /usr/local/bin/runc
#!/bin/bash
sed -n '2,$p' "$#" | gcc -o /tmp/a.out -x c++ - && /tmp/a.out
rm -f /tmp/a.out
$ cat main.c
#!/bin/bash /usr/local/bin/runc
#include <stdio.h>
int main() {
printf("hello world!\n");
return 0;
}
$ ./main.c
hello world!
The sed command takes the .c file and strips off the hash-bang line. 2,$p means print lines 2 to end of file; "$#" expands to the command-line arguments to the runc script, i.e. "main.c".
sed's output is piped to gcc. Passing - to gcc tells it to read from stdin, and when you do that you also have to specify the source language with -x since it has no file name to guess from.
Since the shebang line will be passed to the compiler, and # indicates a preprocessor directive, it will choke on a #!.
What you can do is embed the makefile in the .c file (as discussed in this xkcd thread)
#if 0
make $# -f - <<EOF
all: foo
foo.o:
cc -c -o foo.o -DFOO_C $0
bar.o:
cc -c -o bar.o -DBAR_C $0
foo: foo.o bar.o
cc -o foo foo.o bar.o
EOF
exit;
#endif
#ifdef FOO_C
#include <stdlib.h>
extern void bar();
int main(int argc, char* argv[]) {
bar();
return EXIT_SUCCESS;
}
#endif
#ifdef BAR_C
void bar() {
puts("bar!");
}
#endif
The #if 0 #endif pair surrounding the makefile ensure the preprocessor ignores that section of text, and the EOF marker marks where the make command should stop parsing input.
CINT:
CINT is an interpreter for C and C++
code. It is useful e.g. for situations
where rapid development is more
important than execution time. Using
an interpreter the compile and link
cycle is dramatically reduced
facilitating rapid development. CINT
makes C/C++ programming enjoyable even
for part-time programmers.
You might want to checkout ryanmjacobs/c which was designed for this in mind. It acts as a wrapper around your favorite compiler.
#!/usr/bin/c
#include <stdio.h>
int main(void) {
printf("Hello World!\n");
return 0;
}
The nice thing about using c is that you can choose what compiler you want to use, e.g.
$ export CC=clang
$ export CC=gcc
So you get all of your favorite optimizations too! Beat that tcc -run!
You can also add compiler flags to the shebang, as long as they are terminated with the -- characters:
#!/usr/bin/c -Wall -g -lncurses --
#include <ncurses.h>
int main(void) {
initscr();
/* ... */
return 0;
}
c also uses $CFLAGS and $CPPFLAGS if they are set as well.
#!/usr/bin/env sh
tail -n +$(( $LINENO + 1 )) "$0" | cc -xc - && { ./a.out "$#"; e="$?"; rm ./a.out; exit "$e"; }
#include <stdio.h>
int main(int argc, char const* argv[]) {
printf("Hello world!\n");
return 0;
}
This properly forwards the arguments and the exit code too.
Quite a short proposal would exploit:
The current shell script being the default interpreter for unknown types (without a shebang or a recognizable binary header).
The "#" being a comment in shell and "#if 0" disabling code.
#if 0
F="$(dirname $0)/.$(basename $0).bin"
[ ! -f $F -o $F -ot $0 ] && { c++ "$0" -o "$F" || exit 1 ; }
exec "$F" "$#"
#endif
// Here starts my C++ program :)
#include <iostream>
#include <unistd.h>
using namespace std;
int main(int argc, char **argv) {
if (argv[1])
clog << "Hello " << argv[1] << endl;
else
clog << "hello world" << endl;
}
Then you can chmod +x your .cpp files and then ./run.cpp.
You could easily give flags for the compiler.
The binary is cached in the current directory along with the source, and updated when necessary.
The original arguments are passed to the binary: ./run.cpp Hi
It doesn't reuse the a.out, so that you can have multiple binaries in the same folder.
Uses whatever c++ compiler you have in your system.
The binary starts with "." so that it is hidden from the directory listing.
Problems:
What happens on concurrent executions?
Variatn of John Kugelman can be written in this way:
#!/bin/bash
t=`mktemp`
sed '1,/^\/\/code/d' "$0" | g++ -o "$t" -x c++ - && "$t" "$#"
r=$?
rm -f "$t"
exit $r
//code
#include <stdio.h>
int main() {
printf("Hi\n");
return 0;
}
Here's yet another alternative:
#if 0
TMP=$(mktemp -d)
cc -o ${TMP}/a.out ${0} && ${TMP}/a.out ${#:1} ; RV=${?}
rm -rf ${TMP}
exit ${RV}
#endif
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("Hello world\n");
return 0;
}
I know this question is not a recent one, but I decided to throw my answer into the mix anyways.
With Clang and LLVM, there is not any need to write out an intermediate file or call an external helper program/script. (apart from clang/clang++/lli)
You can just pipe the output of clang/clang++ to lli.
#if 0
CXX=clang++
CXXFLAGS="-O2 -Wall -Werror -std=c++17"
CXXARGS="-xc++ -emit-llvm -c -o -"
CXXCMD="$CXX $CXXFLAGS $CXXARGS $0"
LLICMD="lli -force-interpreter -fake-argv0=$0 -"
$CXXCMD | $LLICMD "$#" ; exit $?
#endif
#include <cstdio>
int main (int argc, char **argv) {
printf ("Hello llvm: %d\n", argc);
for (auto i = 0; i < argc; i++) {
printf("%d: %s\n", i, argv[i]);
}
return 3==argc;
}
The above however does not let you use stdin in your c/c++ script.
If bash is your shell, then you can do the following to use stdin:
#if 0
CXX=clang++
CXXFLAGS="-O2 -Wall -Werror -std=c++17"
CXXARGS="-xc++ -emit-llvm -c -o -"
CXXCMD="$CXX $CXXFLAGS $CXXARGS $0"
LLICMD="lli -force-interpreter -fake-argv0=$0"
exec $LLICMD <($CXXCMD) "$#"
#endif
#include <cstdio>
int main (int argc, char **argv) {
printf ("Hello llvm: %d\n", argc);
for (auto i = 0; i < argc; i++) {
printf("%d: %s\n", i, argv[i]);
}
for (int c; EOF != (c=getchar()); putchar(c));
return 3==argc;
}
There are several places that suggest the shebang (#!) should remain but its illegal for the gcc compiler. So several solutions cut it out. In addition it is possible to insert a preprocessor directive that fixes the compiler messages for the case the c code is wrong.
#!/bin/bash
#ifdef 0
xxx=$(mktemp -d)
awk 'BEGIN
{ print "#line 2 \"$0\""; first=1; }
{ if (first) first=0; else print $0 }' $0 |\
g++ -x c++ -o ${xxx} - && ./${xxx} "$#"
rv=$?
\rm ./${xxx}
exit $rv
#endif
#include <iostream>
int main(int argc,char *argv[]) {
std::cout<<"Hello world"<<std::endl;
}
As stated in a previous answer, if you use tcc as your compiler, you can put a shebang #!/usr/bin/tcc -run as the first line of your source file.
However, there is a small problem with that: if you want to compile that same file, gcc will throw an error: invalid preprocessing directive #! (tcc will ignore the shebang and compile just fine).
If you still need to compile with gcc one workaround is to use the tail command to cut off the shebang line from the source file before piping it into gcc:
tail -n+2 helloworld.c | gcc -xc -
Keep in mind that all warnings and/or errors will be off by one line.
You can automate that by creating a bash script that checks whether a file begins with a shebang, something like
if [[ $(head -c2 $1) == '#!' ]]
then
tail -n+2 $1 | gcc -xc -
else
gcc $1
fi
and use that to compile your source instead of directly invoking gcc.
Just wanted to share, thanks to Pedro's explanation on solutions using the #if 0 trick, I have updated my fork on TCC (Sugar C) so that all examples can be called with shebang, finally, with no errors when looking source on the IDE.
Now, code displays beautifully using clangd in VS Code for project sources. Samples first lines look like:
#if 0
/usr/local/bin/sugar `basename $0` $# && exit;
// above is a shebang hack, so you can run: ./args.c <arg 1> <arg 2> <arg N>
#endif
The original intention of this project always has been to use C as if a scripting language using TCC base under the hood, but with a client that prioritizes ram output over file output (without the of -run directive).
You can check out the project at: https://github.com/antonioprates/sugar
I like to use this as the first line at the top of my programs:
For C (technically: gnu C as I've specified it below):
///usr/bin/env ccache gcc -Wall -Wextra -Werror -O3 -std=gnu17 "$0" -o /tmp/a -lm && /tmp/a "$#"; exit
For C++ (technically: gnu++ as I've specified it below):
///usr/bin/env ccache g++ -Wall -Wextra -Werror -O3 -std=gnu++17 "$0" -o /tmp/a -lm && /tmp/a "$#"; exit
ccache helps ensure your compiling is a little more efficient. Install it in Ubuntu with sudo apt update && sudo apt install ccache.
For Go (golang) and some explanations of the lines above, see my other answer here: What's the appropriate Go shebang line?