Skip to content

Instantly share code, notes, and snippets.

@ataliba
Created April 16, 2012 14:12
Show Gist options
  • Save ataliba/2399072 to your computer and use it in GitHub Desktop.
Save ataliba/2399072 to your computer and use it in GitHub Desktop.
Good code to limit logins of users on FreeBSD ( http://forums.freebsd.org/showthread.php?t=23683 )
#include <iostream>
#include <string>
using namespace std;
string Exec(const char *cmd);
void ReplaceAll(string& str, const string& from, const string& to);
int main(int argc, char **argv, char **envp) {
string whoami, users;
size_t found;
size_t pos1, pos2;
whoami = Exec("whoami");
users = Exec("who");
ReplaceAll(whoami, "\n", "");
pos1 = users.find(whoami.c_str());
pos2 = users.rfind(whoami.c_str());
if (pos1 != pos2) {
cout << endl
<< " * Too many logins for " + whoami
<< endl
<< " * Forcing logout..."
<< endl
<< endl
<< endl;
char command[100];
sprintf(command, "pkill -9 -U %d '.*'", getuid());
system(command);
}
return 0;
}
string Exec(const char *cmd) {
FILE *pipe = popen(cmd, "r");
if (!pipe)
return "3rr0r";
char buffer[128];
string result = "";
while (!feof(pipe)) {
if (fgets(buffer, 128, pipe) != NULL)
result += buffer;
}
pclose(pipe);
return result;
}
void ReplaceAll(string& str, const string& from, const string& to) {
size_t start_pos = 0;
while((start_pos = str.find(from, start_pos)) != string::npos) {
size_t end_pos = start_pos + from.length();
str.replace(start_pos, end_pos, to);
start_pos += to.length();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment