Created
November 28, 2016 19:47
-
-
Save andermoran/01d78c8a4258d5aa1e7cfdfde5c4b9a0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
string exec(const char* cmd); // Used for executing terminal commands in c++ | |
string getPassword(); // Prompts the user for their system password and checks to see if it is the correct password | |
// If the password is correct, it returns it in a string | |
int main(int argc, char *argv[]) { // Example implementation of getPassword() | |
string password = getPassword(); | |
cout << endl << "User password = " << password; | |
} | |
string exec(const char* cmd) { | |
char buffer[128]; | |
string result = ""; | |
shared_ptr<FILE> pipe(popen(cmd, "r"), pclose); | |
if (!pipe) throw runtime_error("popen() failed!"); | |
while (!feof(pipe.get())) { | |
if (fgets(buffer, 128, pipe.get()) != NULL) | |
result += buffer; | |
} | |
return result; | |
} | |
string getPassword() { | |
string status = "default"; | |
string password = ""; | |
while (status == "default" || (int) status[0] == 0) { | |
password = exec("read -s -p \"Password: \" password && echo $password"); | |
password.erase(remove(password.begin(), password.end(), '\n'), password.end()); | |
string command = "if [[ $(echo " + password + " | sudo -k -S echo valid) = \"valid\" ]] &>/dev/null; then echo \"Correct password\"; fi"; | |
status = exec(command.c_str()); | |
status.erase(remove(status.begin(), status.end(), '\n'), status.end()); | |
if (status != "Correct password") { | |
cout << "\nSorry, try again." << endl << flush; | |
} | |
} | |
return password; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment