-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.mjs
executable file
·293 lines (248 loc) · 10.5 KB
/
index.mjs
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
#!/usr/bin/env node
import os from 'os';
import inquirer from 'inquirer';
import { spawn } from 'child_process'; // Import the spawn function
import fs from 'fs';
import { loadCachedTags, saveCachedTags, manageTags, cachedTags } from './cacheManager.mjs';
import { monitor, logToFile } from './monitor.mjs';
import { loadSession, saveSession, getUserPassphrase} from './session.mjs';
import { checkRAMandMemory } from './checkRam.mjs';
import('inquirer-file-tree-selection-prompt').then((promptModule) => {
inquirer.registerPrompt('file-tree-selection', promptModule.default);
// Kick off the main function that starts your CLI interaction
initializeSession().catch((error) => {
console.error('Failed to initialize session:', error);
});
}).catch((error) => {
console.error('Failed to load inquirer-file-tree-selection-prompt:', error);
});
(async function() {
console.log(`
▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄ ▄▄ ▄▄▄▄▄▄▄▄▄▄▄
▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░▌ ▐░░▌▐░░░░░░░░░░░▌
▐░█▀▀▀▀▀▀▀▀▀ ▐░█▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀█░▌▐░▌░▌ ▐░▐░▌▐░█▀▀▀▀▀▀▀▀▀
▐░▌ ▐░▌ ▐░▌▐░▌▐░▌ ▐░▌▐░▌▐░▌
▐░█▄▄▄▄▄▄▄▄▄ ▐░▌ ▐░▌▐░▌ ▐░▐░▌ ▐░▌▐░█▄▄▄▄▄▄▄▄▄
▐░░░░░░░░░░░▌▐░▌ ▄▄▄▄▄▄▄▄▄█░▌▐░▌ ▐░▌ ▐░▌▐░░░░░░░░░░░▌
▐░█▀▀▀▀▀▀▀▀▀ ▐░▌ ▐░░░░░░░░░░░▌▐░▌ ▀ ▐░▌ ▀▀▀▀▀▀▀▀▀█░▌
▐░▌ ▐░▌ ▐░█▀▀▀▀▀▀▀▀▀ ▐░▌ ▐░▌ ▐░▌
▐░█▄▄▄▄▄▄▄▄▄ ▐░█▄▄▄▄▄▄▄▄▄ ▐░█▄▄▄▄▄▄▄▄▄ ▐░▌ ▐░▌ ▄▄▄▄▄▄▄▄▄█░▌
▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░▌ ▐░▌▐░░░░░░░░░░░▌
▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀ ▀ ▀▀▀▀▀▀▀▀▀▀▀
` );
})();
let isBusy = false;
let passphrase = null;
async function initializeSession() {
let sessionData = null;
if (fs.existsSync('session.json')) {
passphrase = await getUserPassphrase('Enter your passphrase to unlock the saved session:');
sessionData = await loadSession(passphrase);
if (!sessionData) {
console.log('Failed to load session. Starting a new one.');
}
} else {
passphrase = await getUserPassphrase('Set your passphrase:');
console.log('\x1b[31m%s\x1b[0m', '⚠️ WARNING: Do not forget your passphrase, as it is required to decrypt your session. IF YOU FORGET IT, IT WILL NOT BE RECOVERABLE ⚠️');
}
await mainMenu(sessionData || null); // call main menu
}
async function mainMenu(sessionData) {
if (isBusy) {
return; // Skip calling mainMenu if isBusy is true
}
const { mainChoice } = await inquirer.prompt([
{
type: 'list',
name: 'mainChoice',
message: 'What would you like to do?',
choices: ['Continue from last session', 'Manage EC2 instances', 'Manage saved tags', 'Check Ram', 'Exit'],
default: 'Manage EC2 instances'
}
]);
switch (mainChoice) {
case 'Continue from last session':
if (sessionData) {
await manageEC2Instances(sessionData.instances, sessionData.pem);
} else {
console.log('No valid session data found. Starting a new session.');
await manageEC2Instances();
}
break;
case 'Manage EC2 instances':
await manageEC2Instances();
break;
case 'Manage saved tags':
await manageTags();
break;
case 'Check Ram':
await checkRAMandMemory();
break;
case 'Exit':
console.log('Goodbye!');
process.exit(0);
}
await mainMenu(); // Loop back to main menu
}
async function askForInstance() {
loadCachedTags();
const { action } = await inquirer.prompt([
{
type: 'list',
name: 'action',
message: 'Do you want to use a saved tag or enter new values? (Eg. test1) ',
choices: [...Object.keys(cachedTags), 'Enter new values'],
default: 'Enter new values'
}
]);
if (action !== 'Enter new values') {
return cachedTags[action];
}
const address = await inquirer.prompt({
type: 'input',
name: 'address',
message: 'Enter the EC2 address (Eg. ec2-33-44-55-66.ap-southeast-1.compute.amazonaws.com):'
});
const username = await inquirer.prompt({
type: 'input',
name: 'username',
message: 'Enter the SSH username for this instance (Eg. ubuntu):',
default: 'ubuntu'
});
const { tag } = await inquirer.prompt({
type: 'input',
name: 'tag',
message: 'Save these inputs under which tag?'
});
const instance = {
address: address.address,
username: username.username,
};
cachedTags[tag] = instance;
saveCachedTags();
return instance;
}
async function manageEC2Instances(savedInstances = null, savedPem = null) {
let instances;
let pem;
let rootDirectory;
switch(os.platform()) {
case 'win32':
rootDirectory = 'C:/';
break;
case 'darwin': // macOS
case 'linux':
rootDirectory = process.env.HOME;
break;
default:
rootDirectory = './'; // Default to current directory for other platforms
}
isBusy = true;
if (savedInstances && savedPem) {
console.log('Continuing from last session...');
instances = savedInstances;
pem = savedPem;
// Use instances and pem to directly connect to EC2
} else {
instances = [];
const { numOfInstances } = await inquirer.prompt([
{
type: 'input',
name: 'numOfInstances',
message: 'How many EC2 instances do you want to connect to?',
validate: value => !isNaN(value) ? true : 'Please enter a valid number.'
}
]);
const { pemMethod } = await inquirer.prompt([
{
type: 'list',
name: 'pemMethod',
message: 'How would you like to provide the PEM file?',
choices: ['Type the path manually', 'Select from directory'],
default: 'Type the path manually'
}
]);
if (pemMethod === 'Type the path manually') {
const pemPrompt = await inquirer.prompt([
{
type: 'input',
name: 'pem',
message: 'Enter the PEM file name (with path if not in the current directory):'
}
]);
pem = pemPrompt.pem;
} else {
const { pemPath } = await inquirer.prompt([
{
type: 'file-tree-selection',
name: 'pemPath',
message: 'Select your PEM file',
onlyShowDir: false,
root: rootDirectory
}
]);
pem = pemPath;
}
for (let i = 0; i < numOfInstances; i++) {
const instance = await askForInstance();
instances.push(instance);
}
// Save the session data after collecting all necessary details
saveSession({ instances, pem }, passphrase);
}
const { osChoice } = await inquirer.prompt({
type: 'list',
name: 'osChoice',
message: 'Choose your Operating System:',
choices: ['macOS', 'Linux', 'Windows'],
default: os.platform() === 'darwin' ? 'macOS' : (os.platform() === 'win32' ? 'Windows' : 'Linux')
});
for (let { address, username } of instances) {
let cmd, args;
const sshCommand = `ssh -v -i "${pem}" ${username}@${address.trim()}`;
if (osChoice === 'macOS') {
cmd = 'osascript';
let scriptPart = 'tell application "Terminal" to do script "ssh -v -i ' + pem + ' ' + username + '@' + address.trim() + '"';
args = ['-e', scriptPart];
} else if (osChoice === 'Linux') {
cmd = 'gnome-terminal';
args = ['--', `${sshCommand}`];
} else if (osChoice === 'Windows') {
cmd = 'cmd.exe';
args = [
'/c',
`start cmd.exe /k ssh -v -i "${pem}" ${username}@${address.trim()} && pause`
];
}
let shellOption;
if (osChoice === 'macOS') {
shellOption = false;
} else if (osChoice === 'Windows') {
shellOption = true;
}
console.log('executing', cmd, args);
spawn(cmd, args, {
shell: shellOption,
detached: true,
stdio: 'inherit'
}).unref();
}
isBusy = false;
monitor.emit('finishedManaging');
};
///////////////////////////////////// Logging ////////////////////////////////////////////////
// Event listener for 'connectionAttempt'
monitor.on('connectionAttempt', (address, username) => {
const logEntry = `Attempting connection to ${address} as ${username}`;
console.log(logEntry);
logToFile('Connection Attempt', logEntry); // Append the log entry to a file
});
monitor.on('reconnected', (address) => {
const logEntry = `Successfully reconnected to ${address}.`;
console.log(`Successfully reconnected to ${address}.`);
logToFile('Connection Attempt', logEntry);
});
monitor.on('reconnectFailed', (address) => {
console.error(`Failed to reconnect to ${address} after multiple attempts.`);
logToFile('Connection Attempt', logEntry);
});