-
Notifications
You must be signed in to change notification settings - Fork 0
/
editHosts.js
103 lines (82 loc) · 2.6 KB
/
editHosts.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
const fs = require("fs");
const path = require("path");
const os = require("os");
// Define the log file path
const logFilePath = path.join(__dirname, "cron.log");
const HOSTS_FILE_PATH = "/etc/hosts";
const HOST_WWW_PREFIX = "www.";
const HOST_LOCAL_HOST = "127.0.0.1";
const BLOCKED_HOSTS_LIST = ["youtube.com", "reddit.com"];
// Logging function
const logMessage = (message) => {
const timestamp = new Date().toISOString();
const logEntry = `[${timestamp}] ${message}\n`;
console.log(logEntry);
fs.appendFile(logFilePath, logEntry, (err) => {
if (err) {
console.error("Error writing to log file:", err);
}
});
};
const buildHostsLine = (host, includeWWW = false) =>
includeWWW
? HOST_LOCAL_HOST + " " + HOST_WWW_PREFIX + host
: HOST_LOCAL_HOST + " " + host;
const addHostsEntry = () => {
try {
let hostsFile = fs.readFileSync(HOSTS_FILE_PATH, "utf8");
if (BLOCKED_HOSTS_LIST.length > 0) {
hostsFile += os.EOL;
}
BLOCKED_HOSTS_LIST.forEach((blockedHost) => {
if (!hostsFile.includes(blockedHost)) {
hostsFile += buildHostsLine(blockedHost) + os.EOL;
hostsFile += buildHostsLine(blockedHost, true) + os.EOL;
fs.writeFileSync(HOSTS_FILE_PATH, hostsFile, "utf8");
logMessage(`Added ${blockedHost} to ${HOSTS_FILE_PATH}`);
} else {
logMessage(`Host ${blockedHost} already in ${HOSTS_FILE_PATH}`);
}
});
} catch (err) {
console.error("Error editing hosts file:", err);
}
};
const removeHostsEntry = () => {
try {
let hostsFile = fs.readFileSync(HOSTS_FILE_PATH, "utf8");
BLOCKED_HOSTS_LIST.forEach((blockedHost) => {
if (hostsFile.includes(blockedHost)) {
hostsFile = hostsFile.replace(buildHostsLine(blockedHost), "");
hostsFile = hostsFile.replace(buildHostsLine(blockedHost, true), "");
fs.writeFileSync(HOSTS_FILE_PATH, hostsFile.trim(), "utf8");
logMessage(`Removed ${blockedHost} from ${HOSTS_FILE_PATH}`);
} else {
logMessage(`Host ${blockedHost} not in ${HOSTS_FILE_PATH}`);
}
});
} catch (err) {
logMessage("Error editing hosts file:", err);
}
};
const editHosts = () => {
const action = process.argv[2];
if (!action) {
console.error('Please provide an action: "add" or "remove"');
process.exit(1);
}
switch (action) {
case "add":
logMessage("Add hosts entry");
addHostsEntry();
break;
case "remove":
logMessage("Remove hosts entry");
removeHostsEntry();
break;
default:
logMessage("Invalid choice. Please try again.");
break;
}
};
editHosts();