|
| 1 | +#include <iostream> |
| 2 | +#include <fstream> |
| 3 | +#include <vector> |
| 4 | + |
| 5 | +using namespace std; |
| 6 | + |
| 7 | +#define FAIL 1 |
| 8 | +#define SUCCESS 0 |
| 9 | +#define FILENAME "/home/diman91/Documents/Cpp-STL-Examples/Firewall.txt" |
| 10 | + |
| 11 | +bool cat_file(const char* filename) |
| 12 | +{ |
| 13 | + char ch; |
| 14 | + |
| 15 | + ifstream in_file; |
| 16 | + in_file.open(filename); |
| 17 | + |
| 18 | + if(!in_file.is_open()) { |
| 19 | + cout << "File was not opened! ERROR! Aborting...\n"; |
| 20 | + return FAIL; |
| 21 | + } |
| 22 | + |
| 23 | + do { |
| 24 | + in_file.get(ch); |
| 25 | + |
| 26 | + if(!in_file.eof() && ( in_file.fail() || in_file.bad() )) { |
| 27 | + cout << "ERROR! Aborting ..."; |
| 28 | + in_file.close(); |
| 29 | + return FAIL; |
| 30 | + } |
| 31 | + |
| 32 | + if(!in_file.eof()) |
| 33 | + cout << ch; |
| 34 | + } while(!in_file.eof()); |
| 35 | + |
| 36 | + in_file.clear(); // needed for eof and fail |
| 37 | + |
| 38 | + in_file.close(); |
| 39 | + |
| 40 | + if(!in_file.good()){ |
| 41 | + cout << "ERROR! ... in closing file ... Aborting ..."; |
| 42 | + return FAIL; |
| 43 | + } |
| 44 | + |
| 45 | + return SUCCESS; |
| 46 | +} |
| 47 | + |
| 48 | + |
| 49 | +// Function to write contents to a file |
| 50 | +bool write_file(const char* filename, const char* content) |
| 51 | +{ |
| 52 | + ofstream out_file; |
| 53 | + out_file.open(filename, ios::out | ios::app); |
| 54 | + |
| 55 | + if(!out_file.is_open()) { |
| 56 | + cout << "File was not opened! ERROR! Aborting...\n"; |
| 57 | + return FAIL; |
| 58 | + } |
| 59 | + |
| 60 | + out_file << content << endl; |
| 61 | + |
| 62 | + out_file.close(); |
| 63 | + |
| 64 | + if(!out_file.good()){ |
| 65 | + cout << "ERROR! Aborting ..."; |
| 66 | + return FAIL; |
| 67 | + } |
| 68 | + |
| 69 | + return SUCCESS; |
| 70 | +} |
| 71 | + |
| 72 | + |
| 73 | +int main() |
| 74 | +{ |
| 75 | + vector<const char*> commands = {"iptables -A INPUT -p tcp -s 192.168.16.0/16 --dport 24 -j ACCEPT", |
| 76 | + "iptables -A INPUT -p tcp -s 192.168.17.0/16 --dport 24 -j ACCEPT", |
| 77 | + "iptables -A INPUT -p tcp -s 192.168.16.0/16 --dport 21 -j ACCEPT", |
| 78 | + "iptables -A INPUT -p tcp -s 192.168.17.0/16 --dport 21 -j ACCEPT", |
| 79 | + "iptables -A INPUT -j DROP" |
| 80 | + }; |
| 81 | + vector<const char*>::iterator itr = commands.begin(); |
| 82 | + while(itr != commands.end()) { |
| 83 | + //cout << *itr << endl; |
| 84 | + write_file(FILENAME, *itr); |
| 85 | + itr++; |
| 86 | + } |
| 87 | + |
| 88 | + cat_file(FILENAME); |
| 89 | + |
| 90 | + return 0; |
| 91 | +} |
0 commit comments