From 7be72b845268991f61f16eb6682d462990c673fc Mon Sep 17 00:00:00 2001 From: Mateo FERON Date: Fri, 10 Apr 2020 15:56:01 +0200 Subject: [PATCH] shell: add script() --- include/shell.hpp | 3 +++ src/shell.cpp | 33 +++++++++++++++++++++++++++++++-- 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/include/shell.hpp b/include/shell.hpp index 6f9af4f..3242165 100644 --- a/include/shell.hpp +++ b/include/shell.hpp @@ -142,6 +142,9 @@ namespace ztd //! @brief @see exec(std::string const& bin, std::vector const& args) std::pair exec(std::string const& bin, std::vector const& args); + std::pair script(std::string const& data, std::vector const& args); + std::pair script(std::string const& data, std::vector const& args); + } #endif //SHELL_HPP diff --git a/src/shell.cpp b/src/shell.cpp index c5ac9e7..8bd022e 100644 --- a/src/shell.cpp +++ b/src/shell.cpp @@ -224,7 +224,36 @@ std::pair ztd::exec(std::string const& bin, std::vector std::pair ztd::exec(std::string const& bin, std::vector const& args) { std::vector rargs; - for(auto it: args) - rargs.push_back((char*) it.c_str()); + for(auto it=args.begin(); it!=args.end() ; it++) + rargs.push_back((char*) it->c_str()); return ztd::exec(bin, rargs); } + +std::pair ztd::script(std::string const& data, std::vector const& args) +{ + std::vector rargs; + for(auto it=args.begin(); it!=args.end() ; it++) + rargs.push_back((char*) it->c_str()); + return ztd::script(data, rargs); +} +std::pair ztd::script(std::string const& data, std::vector const& args) +{ + // create stream + std::string filepath = "/tmp/ztdscript" + ztd::sh("tr -dc '[:alnum:]' < /dev/urandom | head -c10"); + std::ofstream stream(filepath); + if(!stream) + throw std::runtime_error("Failed to write to file '"+filepath+'\''); + + // output + stream << data; + stream.close(); + ztd::sh("chmod +x "+filepath); + + // execute script + auto ret = ztd::exec(filepath, args); + + // delete file + if( remove(filepath.c_str()) != 0 ) + throw std::runtime_error("Failed to delete file '"+filepath+'\''); + return std::make_pair(ret.first, ret.second); +}