Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

C++ Easy command runner

Hi all, this is nothing crazy, but I made this last night to assist with some startup commands on a server. I created a C++ file that would run commands, and then I set this program to run on server reboots. However, I didn't want to have to recompile the code every time I change the startup commands, so I made a program that reads the commands (by line) from a file, and then runs each one as-is.

Please note that this is technically a security issue: If you give this C++ program escalated/admin permissions, then someone could modify the commands.txt file and then run the program. It would be important to ensure that the commands.txt file is only editable by a secure account (root, admin, etc) and also that the program only has the permissions it needs for your specific use case.

Here is the source code for the very very small C++ program:
Code
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>

int main() {
    std::ifstream file("commands.txt");
    std::string command;

    if (file.is_open()) {
        while (getline(file, command)) {
            std::system(command.c_str());
        }
        file.close();
    } else {
        std::cerr << "Unable to open file" << std::endl;
        return 1;
    }

    return 0;
}

Here is an example of some commands in commands.txt, in same folder as compiled program:
Code
cd /home/username/cron && pm2 start ecosystem.config.js
cd /home/sitename && pm2 start ecosystem.config.js
screen -dmS screen-demo-example.com bash -c 'cd /home/screen-demo-example && npm run start; exec sh'

In this example I am starting 1 site with pm2 and 1 cron-style node app with pm2, and also starting a screen to start a forever process for a 3rd project.

I compiled with:
Code
g++ -static startup_run.cpp -o startup_run
All you do once you compile is just run your program from the same folder as commands.txt :)


Possibly Related Threads...
Thread / Author Replies Views Last Post
[Shell] by ImDeepWithWindowsJul 4, 2020 06:19 PM 0 167 Jul 4, 2020 06:19 PM
Last Post: ImDeepWithWindows
[Shell] by friiz1337May 14, 2020 04:09 AM 2 207 May 14, 2020 04:09 AM
Last Post: sed-i
[Shell] by DеathJul 30, 2017 06:01 PM 51 2,441 Jul 30, 2017 06:01 PM
Last Post: motherfawker666