Measure and show process memory every'\
209 | ' N seconds\n'
210 |
211 | return help_msg
212 |
213 |
214 | # (major,minor,release)
215 | def kernel_ver():
216 | kv = proc.open('sys/kernel/osrelease').readline().split(".")[:3]
217 | last = len(kv)
218 | if last == 2:
219 | kv.append('0')
220 | last -= 1
221 | while last > 0:
222 | for char in "-_":
223 | kv[last] = kv[last].split(char)[0]
224 | try:
225 | int(kv[last])
226 | except:
227 | kv[last] = 0
228 | last -= 1
229 | return (int(kv[0]), int(kv[1]), int(kv[2]))
230 |
231 |
232 | #return Private,Shared
233 | #Note shared is always a subset of rss (trs is not always)
234 | def getMemStats(pid):
235 | global have_pss
236 | global have_swap_pss
237 | mem_id = pid #unique
238 | Private_lines = []
239 | Shared_lines = []
240 | Pss_lines = []
241 | Rss = (int(proc.open(pid, 'statm').readline().split()[1])
242 | * PAGESIZE)
243 | Swap_lines = []
244 | Swap_pss_lines = []
245 |
246 | Swap = 0
247 | Swap_pss = 0
248 |
249 | if os.path.exists(proc.path(pid, 'smaps')): # stat
250 | lines = proc.open(pid, 'smaps').readlines() # open
251 | # Note we checksum smaps as maps is usually but
252 | # not always different for separate processes.
253 | mem_id = hash(''.join(lines))
254 | for line in lines:
255 | if line.startswith("Shared"):
256 | Shared_lines.append(line)
257 | elif line.startswith("Private"):
258 | Private_lines.append(line)
259 | elif line.startswith("Pss"):
260 | have_pss = 1
261 | Pss_lines.append(line)
262 | elif line.startswith("Swap:"):
263 | Swap_lines.append(line)
264 | elif line.startswith("SwapPss:"):
265 | have_swap_pss = 1
266 | Swap_pss_lines.append(line)
267 | Shared = sum([int(line.split()[1]) for line in Shared_lines])
268 | Private = sum([int(line.split()[1]) for line in Private_lines])
269 | #Note Shared + Private = Rss above
270 | #The Rss in smaps includes video card mem etc.
271 | if have_pss:
272 | pss_adjust = 0.5 # add 0.5KiB as this avg error due to truncation
273 | Pss = sum([float(line.split()[1])+pss_adjust for line in Pss_lines])
274 | Shared = Pss - Private
275 | # Note that Swap = Private swap + Shared swap.
276 | Swap = sum([int(line.split()[1]) for line in Swap_lines])
277 | if have_swap_pss:
278 | # The kernel supports SwapPss, that shows proportional swap share.
279 | # Note that Swap - SwapPss is not Private Swap.
280 | Swap_pss = sum([int(line.split()[1]) for line in Swap_pss_lines])
281 | elif (2,6,1) <= kernel_ver() <= (2,6,9):
282 | Shared = 0 #lots of overestimation, but what can we do?
283 | Private = Rss
284 | else:
285 | Shared = int(proc.open(pid, 'statm').readline().split()[2])
286 | Shared *= PAGESIZE
287 | Private = Rss - Shared
288 | return (Private, Shared, mem_id, Swap, Swap_pss)
289 |
290 |
291 | def getCmdName(pid, split_args, discriminate_by_pid):
292 | cmdline = proc.open(pid, 'cmdline').read().split("\0")
293 | if cmdline[-1] == '' and len(cmdline) > 1:
294 | cmdline = cmdline[:-1]
295 |
296 | path = proc.path(pid, 'exe')
297 | try:
298 | path = os.readlink(path)
299 | # Some symlink targets were seen to contain NULs on RHEL 5 at least
300 | # https://github.com/pixelb/scripts/pull/10, so take string up to NUL
301 | path = path.split('\0')[0]
302 | except OSError:
303 | val = sys.exc_info()[1]
304 | if (val.errno == errno.ENOENT or # either kernel thread or process gone
305 | val.errno == errno.EPERM):
306 | raise LookupError
307 | raise
308 |
309 | if split_args:
310 | return " ".join(cmdline)
311 | if path.endswith(" (deleted)"):
312 | path = path[:-10]
313 | if os.path.exists(path):
314 | path += " [updated]"
315 | else:
316 | #The path could be have prelink stuff so try cmdline
317 | #which might have the full path present. This helped for:
318 | #/usr/libexec/notification-area-applet.#prelink#.fX7LCT (deleted)
319 | if os.path.exists(cmdline[0]):
320 | path = cmdline[0] + " [updated]"
321 | else:
322 | path += " [deleted]"
323 | exe = os.path.basename(path)
324 | cmd = proc.open(pid, 'status').readline()[6:-1]
325 | if exe.startswith(cmd):
326 | cmd = exe #show non truncated version
327 | #Note because we show the non truncated name
328 | #one can have separated programs as follows:
329 | #584.0 KiB + 1.0 MiB = 1.6 MiB mozilla-thunder (exe -> bash)
330 | # 56.0 MiB + 22.2 MiB = 78.2 MiB mozilla-thunderbird-bin
331 | if sys.version_info >= (3,):
332 | cmd = cmd.encode(errors='replace').decode()
333 | if discriminate_by_pid:
334 | cmd = '%s [%d]' % (cmd, pid)
335 | return cmd
336 |
337 |
338 | #The following matches "du -h" output
339 | #see also human.py
340 | def human(num, power="Ki", units=None):
341 | if units is None:
342 | powers = ["Ki", "Mi", "Gi", "Ti"]
343 | while num >= 1000: #4 digits
344 | num /= 1024.0
345 | power = powers[powers.index(power)+1]
346 | return "%.1f %sB" % (num, power)
347 | else:
348 | return "%.f" % ((num * 1024) / units)
349 |
350 |
351 | def cmd_with_count(cmd, count):
352 | if count > 1:
353 | return "%s (%u)" % (cmd, count)
354 | else:
355 | return cmd
356 |
357 | #Warn of possible inaccuracies
358 | #2 = accurate & can total
359 | #1 = accurate only considering each process in isolation
360 | #0 = some shared mem not reported
361 | #-1= all shared mem not reported
362 | def shared_val_accuracy():
363 | """http://wiki.apache.org/spamassassin/TopSharedMemoryBug"""
364 | kv = kernel_ver()
365 | pid = os.getpid()
366 | if kv[:2] == (2,4):
367 | if proc.open('meminfo').read().find("Inact_") == -1:
368 | return 1
369 | return 0
370 | elif kv[:2] == (2,6):
371 | if os.path.exists(proc.path(pid, 'smaps')):
372 | if proc.open(pid, 'smaps').read().find("Pss:")!=-1:
373 | return 2
374 | else:
375 | return 1
376 | if (2,6,1) <= kv <= (2,6,9):
377 | return -1
378 | return 0
379 | elif kv[0] > 2 and os.path.exists(proc.path(pid, 'smaps')):
380 | return 2
381 | else:
382 | return 1
383 |
384 | def show_shared_val_accuracy( possible_inacc, only_total=False ):
385 | level = ("Warning","Error")[only_total]
386 | if possible_inacc == -1:
387 | sys.stderr.write(
388 | "%s: Shared memory is not reported by this system.\n" % level
389 | )
390 | sys.stderr.write(
391 | "Values reported will be too large, and totals are not reported\n"
392 | )
393 | elif possible_inacc == 0:
394 | sys.stderr.write(
395 | "%s: Shared memory is not reported accurately by this system.\n" % level
396 | )
397 | sys.stderr.write(
398 | "Values reported could be too large, and totals are not reported\n"
399 | )
400 | elif possible_inacc == 1:
401 | sys.stderr.write(
402 | "%s: Shared memory is slightly over-estimated by this system\n"
403 | "for each program, so totals are not reported.\n" % level
404 | )
405 | sys.stderr.close()
406 | if only_total and possible_inacc != 2:
407 | sys.exit(1)
408 |
409 |
410 | def get_memory_usage(pids_to_show, split_args, discriminate_by_pid,
411 | include_self=False, only_self=False):
412 | cmds = {}
413 | shareds = {}
414 | mem_ids = {}
415 | count = {}
416 | swaps = {}
417 | shared_swaps = {}
418 | for pid in os.listdir(proc.path('')):
419 | if not pid.isdigit():
420 | continue
421 | pid = int(pid)
422 |
423 | # Some filters
424 | if only_self and pid != our_pid:
425 | continue
426 | if pid == our_pid and not include_self:
427 | continue
428 | if pids_to_show is not None and pid not in pids_to_show:
429 | continue
430 |
431 | try:
432 | cmd = getCmdName(pid, split_args, discriminate_by_pid)
433 | except LookupError:
434 | #operation not permitted
435 | #kernel threads don't have exe links or
436 | #process gone
437 | continue
438 |
439 | try:
440 | private, shared, mem_id, swap, swap_pss = getMemStats(pid)
441 | except RuntimeError:
442 | continue #process gone
443 | if shareds.get(cmd):
444 | if have_pss: #add shared portion of PSS together
445 | shareds[cmd] += shared
446 | elif shareds[cmd] < shared: #just take largest shared val
447 | shareds[cmd] = shared
448 | else:
449 | shareds[cmd] = shared
450 | cmds[cmd] = cmds.setdefault(cmd, 0) + private
451 | if cmd in count:
452 | count[cmd] += 1
453 | else:
454 | count[cmd] = 1
455 | mem_ids.setdefault(cmd, {}).update({mem_id: None})
456 |
457 | # Swap (overcounting for now...)
458 | swaps[cmd] = swaps.setdefault(cmd, 0) + swap
459 | if have_swap_pss:
460 | shared_swaps[cmd] = shared_swaps.setdefault(cmd, 0) + swap_pss
461 | else:
462 | shared_swaps[cmd] = 0
463 |
464 | # Total swaped mem for each program
465 | total_swap = 0
466 |
467 | # Total swaped shared mem for each program
468 | total_shared_swap = 0
469 |
470 | # Add shared mem for each program
471 | total = 0
472 |
473 | for cmd in cmds:
474 | cmd_count = count[cmd]
475 | if len(mem_ids[cmd]) == 1 and cmd_count > 1:
476 | # Assume this program is using CLONE_VM without CLONE_THREAD
477 | # so only account for one of the processes
478 | cmds[cmd] /= cmd_count
479 | if have_pss:
480 | shareds[cmd] /= cmd_count
481 | cmds[cmd] = cmds[cmd] + shareds[cmd]
482 | total += cmds[cmd] # valid if PSS available
483 | total_swap += swaps[cmd]
484 | if have_swap_pss:
485 | total_shared_swap += shared_swaps[cmd]
486 |
487 | sorted_cmds = sorted(cmds.items(), key=lambda x:x[1])
488 | sorted_cmds = [x for x in sorted_cmds if x[1]]
489 |
490 | return sorted_cmds, shareds, count, total, swaps, shared_swaps, \
491 | total_swap, total_shared_swap
492 |
493 |
494 | def print_header(show_swap, discriminate_by_pid):
495 | output_string = " Private + Shared = RAM used"
496 | if show_swap:
497 | if have_swap_pss:
498 | output_string += " " * 5 + "Shared Swap"
499 | output_string += " Swap used"
500 | output_string += "\tProgram"
501 | if discriminate_by_pid:
502 | output_string += "[pid]"
503 | output_string += "\n\n"
504 | sys.stdout.write(output_string)
505 |
506 |
507 | def print_memory_usage(sorted_cmds, shareds, count, total, swaps, total_swap,
508 | shared_swaps, total_shared_swap, show_swap):
509 | for cmd in sorted_cmds:
510 |
511 | output_string = "%9s + %9s = %9s"
512 | output_data = (human(cmd[1]-shareds[cmd[0]]),
513 | human(shareds[cmd[0]]), human(cmd[1]))
514 | if show_swap:
515 | if have_swap_pss:
516 | output_string += "\t%9s"
517 | output_data += (human(shared_swaps[cmd[0]]),)
518 | output_string += " %9s"
519 | output_data += (human(swaps[cmd[0]]),)
520 | output_string += "\t%s\n"
521 | output_data += (cmd_with_count(cmd[0], count[cmd[0]]),)
522 |
523 | sys.stdout.write(output_string % output_data)
524 |
525 | if have_pss:
526 | if show_swap:
527 | if have_swap_pss:
528 | sys.stdout.write("%s\n%s%9s%s%9s%s%9s\n%s\n" %
529 | ("-" * 61, " " * 24, human(total), " " * 7,
530 | human(total_shared_swap), " " * 3,
531 | human(total_swap), "=" * 61))
532 | else:
533 | sys.stdout.write("%s\n%s%9s%s%9s\n%s\n" %
534 | ("-" * 45, " " * 24, human(total), " " * 3,
535 | human(total_swap), "=" * 45))
536 | else:
537 | sys.stdout.write("%s\n%s%9s\n%s\n" %
538 | ("-" * 33, " " * 24, human(total), "=" * 33))
539 |
540 |
541 | def verify_environment():
542 | if os.geteuid() != 0:
543 | sys.stderr.write("Sorry, root permission required.\n")
544 | sys.stderr.close()
545 | sys.exit(1)
546 |
547 | try:
548 | kernel_ver()
549 | except (IOError, OSError):
550 | val = sys.exc_info()[1]
551 | if val.errno == errno.ENOENT:
552 | sys.stderr.write(
553 | "Couldn't access " + proc.path('') + "\n"
554 | "Only GNU/Linux and FreeBSD (with linprocfs) are supported\n")
555 | sys.exit(2)
556 | else:
557 | raise
558 |
559 | def main():
560 | split_args, pids_to_show, watch, only_total, discriminate_by_pid, \
561 | show_swap = parse_options()
562 |
563 | verify_environment()
564 |
565 | if not only_total:
566 | print_header(show_swap, discriminate_by_pid)
567 |
568 | if watch is not None:
569 | try:
570 | sorted_cmds = True
571 | while sorted_cmds:
572 | sorted_cmds, shareds, count, total, swaps, shared_swaps, \
573 | total_swap, total_shared_swap = \
574 | get_memory_usage(pids_to_show, split_args,
575 | discriminate_by_pid)
576 | if only_total and have_pss:
577 | sys.stdout.write(human(total, units=1)+'\n')
578 | elif not only_total:
579 | print_memory_usage(sorted_cmds, shareds, count, total,
580 | swaps, total_swap, shared_swaps,
581 | total_shared_swap, show_swap)
582 |
583 | sys.stdout.flush()
584 | time.sleep(watch)
585 | else:
586 | sys.stdout.write('Process does not exist anymore.\n')
587 | except KeyboardInterrupt:
588 | pass
589 | else:
590 | # This is the default behavior
591 | sorted_cmds, shareds, count, total, swaps, shared_swaps, total_swap, \
592 | total_shared_swap = get_memory_usage(pids_to_show, split_args,
593 | discriminate_by_pid)
594 | if only_total and have_pss:
595 | sys.stdout.write(human(total, units=1)+'\n')
596 | elif not only_total:
597 | print_memory_usage(sorted_cmds, shareds, count, total, swaps,
598 | total_swap, shared_swaps, total_shared_swap,
599 | show_swap)
600 |
601 | # We must close explicitly, so that any EPIPE exception
602 | # is handled by our excepthook, rather than the default
603 | # one which is reenabled after this script finishes.
604 | sys.stdout.close()
605 |
606 | vm_accuracy = shared_val_accuracy()
607 | show_shared_val_accuracy( vm_accuracy, only_total )
608 |
609 | if __name__ == '__main__': main()
610 |
--------------------------------------------------------------------------------
/Files/Menu/reboot_sys.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # Script by : _Dreyannz_
3 | clear
4 | echo -e "\e[0m "
5 | echo -e "\e[94m[][][]======================================[][][]"
6 | echo -e "\e[0m "
7 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
8 | echo -e "\e[0m "
9 | echo -e "\e[93m [1] Reboot Now"
10 | echo -e "\e[93m [2] Reboot Time"
11 | echo -e "\e[93m [x] Exit"
12 | echo -e "\e[0m "
13 | read -p " Select From Options [1-3 or x] : " Reboot
14 | echo -e "\e[0m "
15 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
16 | sleep 3
17 | clear
18 | case $Reboot in
19 | 1)
20 | clear
21 | reboot
22 | exit
23 | ;;
24 | 2)
25 | clear
26 | reboot_sys_auto
27 | exit
28 | ;;
29 | x)
30 | clear
31 | exit
32 | ;;
33 | esac
--------------------------------------------------------------------------------
/Files/Menu/reboot_sys_auto.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # Script by : _Dreyannz_
3 | clear
4 | echo -e "\e[0m "
5 | echo -e "\e[94m[][][]======================================[][][]"
6 | echo -e "\e[0m "
7 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
8 | echo -e "\e[0m "
9 | echo -e "\e[93m [1] Reboot Every 1 Hour"
10 | echo -e "\e[93m [2] Reboot Every 2 Hours"
11 | echo -e "\e[93m [3] Reboot Every 12 Hours"
12 | echo -e "\e[93m [4] Reboot Once A Day"
13 | echo -e "\e[93m [5] Reboot Once A Week"
14 | echo -e "\e[93m [6] Reboot Once A Month"
15 | echo -e "\e[93m [7] Remove Reboot"
16 | echo -e "\e[93m [x] Exit"
17 | echo -e "\e[0m "
18 | read -p " Select From Options [1-7 or x] : " Reboot_Sys
19 | echo -e "\e[0m "
20 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
21 | sleep 3
22 | clear
23 | case $Reboot_Sys in
24 | 1)
25 | clear
26 | echo "10 * * * * root /usr/local/bin/reboot_sys" > /etc/cron.d/reboot_sys
27 | echo -e "\e[0m "
28 | echo -e "\e[94m[][][]======================================[][][]"
29 | echo -e "\e[0m "
30 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
31 | echo -e "\e[0m "
32 | echo -e "\e[93m Auto-Reboot Set Every Hour "
33 | echo -e "\e[0m "
34 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
35 | exit
36 | ;;
37 | 2)
38 | clear
39 | echo "10 */6 * * * root /usr/local/bin/reboot_sys" > /etc/cron.d/reboot_sys
40 | echo -e "\e[0m "
41 | echo -e "\e[94m[][][]======================================[][][]"
42 | echo -e "\e[0m "
43 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
44 | echo -e "\e[0m "
45 | echo -e "\e[93m Auto-Reboot Set Every 2 Hours "
46 | echo -e "\e[0m "
47 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
48 | exit
49 | ;;
50 | 3)
51 | clear
52 | echo "10 */12 * * * root /usr/local/bin/reboot_sys" > /etc/cron.d/reboot_sys
53 | echo -e "\e[0m "
54 | echo -e "\e[94m[][][]======================================[][][]"
55 | echo -e "\e[0m "
56 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
57 | echo -e "\e[0m "
58 | echo -e "\e[93m Auto-Reboot Set Every 12 Hours "
59 | echo -e "\e[0m "
60 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
61 | exit
62 | ;;
63 | 4)
64 | clear
65 | echo "10 0 * * * root /usr/local/bin/reboot_sys" > /etc/cron.d/reboot_sys
66 | echo -e "\e[0m "
67 | echo -e "\e[94m[][][]======================================[][][]"
68 | echo -e "\e[0m "
69 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
70 | echo -e "\e[0m "
71 | echo -e "\e[93m Auto-Reboot Set Once A Day "
72 | echo -e "\e[0m "
73 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
74 | exit
75 | ;;
76 | 5)
77 | clear
78 | echo "10 0 */7 * * root /usr/local/bin/reboot_sys" > /etc/cron.d/reboot_sys
79 | echo -e "\e[0m "
80 | echo -e "\e[94m[][][]======================================[][][]"
81 | echo -e "\e[0m "
82 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
83 | echo -e "\e[0m "
84 | echo -e "\e[93m Auto-Reboot Set Once A Week "
85 | echo -e "\e[0m "
86 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
87 | exit
88 | ;;
89 | 6)
90 | clear
91 | echo "10 0 1 * * root /usr/local/bin/reboot_sys" > /etc/cron.d/reboot_sys
92 | echo -e "\e[0m "
93 | echo -e "\e[94m[][][]======================================[][][]"
94 | echo -e "\e[0m "
95 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
96 | echo -e "\e[0m "
97 | echo -e "\e[93m Auto-Reboot Set Once A Month "
98 | echo -e "\e[0m "
99 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
100 | exit
101 | ;;
102 | 7)
103 | clear
104 | rm -f /etc/cron.d/reboot_sys
105 | echo -e "\e[0m "
106 | echo -e "\e[94m[][][]======================================[][][]"
107 | echo -e "\e[0m "
108 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
109 | echo -e "\e[0m "
110 | echo -e "\e[93m Auto-Reboot Removed "
111 | echo -e "\e[0m "
112 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
113 | exit
114 | ;;
115 | x)
116 | clear
117 | exit
118 | ;;
119 | esac
--------------------------------------------------------------------------------
/Files/Menu/restart_services.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # Script by : _Dreyannz_
3 | clear
4 | echo -e "\e[0m "
5 | echo -e "\e[94m[][][]======================================[][][]"
6 | echo -e "\e[0m "
7 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
8 | echo -e "\e[0m "
9 | echo -e "\e[93m [1] Restart All Services"
10 | echo -e "\e[93m [2] Restart OpenSSH"
11 | echo -e "\e[93m [3] Restart Dropbear"
12 | echo -e "\e[93m [4] Restart Stunnel4"
13 | echo -e "\e[93m [5] Restart OpenVPN"
14 | echo -e "\e[93m [6] Restart Squid"
15 | echo -e "\e[93m [7] Restart Nginx"
16 | echo -e "\e[93m [x] Exit"
17 | echo -e "\e[0m "
18 | read -p " Select From Options [1-7 or x] : " Restart
19 | echo -e "\e[0m "
20 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
21 | sleep 3
22 | clear
23 | case $Restart in
24 | 1)
25 | clear
26 | service ssh restart
27 | service dropbear restart
28 | service stunnel4 restart
29 | service openvpn restart
30 | service squid3 restart
31 | service nginx restart
32 | echo -e "\e[0m "
33 | echo -e "\e[94m[][][]======================================[][][]"
34 | echo -e "\e[0m "
35 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
36 | echo -e "\e[0m "
37 | echo -e "\e[93m Service/s Restarted "
38 | echo -e "\e[0m "
39 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
40 | exit
41 | ;;
42 | 2)
43 | clear
44 | service ssh restart
45 | echo -e "\e[0m "
46 | echo -e "\e[94m[][][]======================================[][][]"
47 | echo -e "\e[0m "
48 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
49 | echo -e "\e[0m "
50 | echo -e "\e[93m SSH Service Restarted "
51 | echo -e "\e[0m "
52 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
53 | exit
54 | ;;
55 | 3)
56 | clear
57 | service dropbear restart
58 | echo -e "\e[0m "
59 | echo -e "\e[94m[][][]======================================[][][]"
60 | echo -e "\e[0m "
61 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
62 | echo -e "\e[0m "
63 | echo -e "\e[93m Dropbear Service Restarted "
64 | echo -e "\e[0m "
65 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
66 | exit
67 | ;;
68 | 4)
69 | clear
70 | service stunnel4 restart
71 | echo -e "\e[0m "
72 | echo -e "\e[94m[][][]======================================[][][]"
73 | echo -e "\e[0m "
74 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
75 | echo -e "\e[0m "
76 | echo -e "\e[93m Stunnel4 Service Restarted "
77 | echo -e "\e[0m "
78 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
79 | exit
80 | ;;
81 | 5)
82 | clear
83 | service openvpn restart
84 | echo -e "\e[0m "
85 | echo -e "\e[94m[][][]======================================[][][]"
86 | echo -e "\e[0m "
87 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
88 | echo -e "\e[0m "
89 | echo -e "\e[93m OpenVPN Service Restarted "
90 | echo -e "\e[0m "
91 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
92 | exit
93 | ;;
94 | 6)
95 | clear
96 | service squid3 restart
97 | echo -e "\e[0m "
98 | echo -e "\e[94m[][][]======================================[][][]"
99 | echo -e "\e[0m "
100 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
101 | echo -e "\e[0m "
102 | echo -e "\e[93m Squid3 Service Restarted "
103 | echo -e "\e[0m "
104 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
105 | exit
106 | ;;
107 | 7)
108 | clear
109 | service nginx restart
110 | echo -e "\e[0m "
111 | echo -e "\e[94m[][][]======================================[][][]"
112 | echo -e "\e[0m "
113 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
114 | echo -e "\e[0m "
115 | echo -e "\e[93m Nginx Service Restarted "
116 | echo -e "\e[0m "
117 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
118 | exit
119 | ;;
120 | x)
121 | clear
122 | exit
123 | ;;
124 | esac
--------------------------------------------------------------------------------
/Files/Menu/server_menu.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # Script by : _Dreyannz_
3 | clear
4 | echo -e "\e[0m "
5 | echo -e "\e[94m[][][]======================================[][][]"
6 | echo -e "\e[0m "
7 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
8 | echo -e "\e[0m "
9 | echo -e "\e[93m [1] Change Server Password"
10 | echo -e "\e[93m [2] RAM Usage"
11 | echo -e "\e[93m [3] Diagnostics"
12 | echo -e "\e[93m [4] Benchmark"
13 | echo -e "\e[93m [5] SpeedTest"
14 | echo -e "\e[93m [x] Exit"
15 | echo -e "\e[0m "
16 | read -p " Select From Options [1-7 or x] : " Server
17 | echo -e "\e[0m "
18 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
19 | case $Server in
20 | 1)
21 | clear
22 | echo -e "\e[0m "
23 | echo -e "\e[94m[][][]======================================[][][]"
24 | echo -e "\e[0m "
25 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
26 | echo -e "\e[0m "
27 | echo -e "\e[93m Checking root Permissions "
28 | echo -e "\e[0m "
29 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
30 | sleep 4
31 | if [[ $USER != "root" ]]; then
32 | clear
33 | echo -e "\e[0m "
34 | echo -e "\e[94m[][][]======================================[][][]"
35 | echo -e "\e[0m "
36 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
37 | echo -e "\e[0m "
38 | echo -e "\e[91m root Permissions Denied "
39 | echo -e "\e[0m "
40 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
41 | exit
42 | fi
43 | clear
44 | echo -e "\e[0m "
45 | echo -e "\e[94m[][][]======================================[][][]"
46 | echo -e "\e[0m "
47 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
48 | echo -e "\e[0m "
49 | read -p " New Password : " Pass
50 | echo -e "\e[0m "
51 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
52 | sleep 4
53 | New_Pass=root:$Pass;
54 | echo $New_Pass > passwd
55 | chpasswd < passwd
56 | rm passwd
57 | echo -e "\e[0m "
58 | echo -e "\e[94m[][][]======================================[][][]"
59 | echo -e "\e[0m "
60 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
61 | echo -e "\e[0m "
62 | echo -e "\e[94m Password Has Been Changed "
63 | echo -e "\e[0m "
64 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
65 | exit
66 | ;;
67 | 2)
68 | clear
69 | ram
70 | exit
71 | ;;
72 | 3)
73 | clear
74 | diagnose
75 | exit
76 | ;;
77 | 4)
78 | clear
79 | bench-network
80 | exit
81 | ;;
82 | 5)
83 | clear
84 | speedtest --share
85 | exit
86 | ;;
87 | x)
88 | clear
89 | exit
90 | ;;
91 | esac
--------------------------------------------------------------------------------
/Files/Menu/set_multilogin_autokill.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # Script by : _Dreyannz_
3 | clear
4 | echo -e "\e[0m "
5 | echo -e "\e[94m[][][]======================================[][][]"
6 | echo -e "\e[0m "
7 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
8 | echo -e "\e[0m "
9 | echo -e "\e[93m [1] AutoKill After 5 Minutes"
10 | echo -e "\e[93m [2] AutoKill After 15 Minutes"
11 | echo -e "\e[93m [3] AutoKill After 30 Minutes"
12 | echo -e "\e[93m [4] Turn Off AutoKill/MultiLogin"
13 | echo -e "\e[93m [x] Exit"
14 | echo -e "\e[0m "
15 | read -p " Select From Options [1-5 or x] : " AutoKill
16 | echo -e "\e[0m "
17 | case $AutoKill in
18 | 1)
19 | read -p " Allowed MultiLogin : " -e -i 1 MultiLogin
20 | echo -e "\e[0m "
21 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
22 | sleep 4
23 | clear
24 | echo "*/5 * * * * root /usr/bin/set_multilogin_autokill_lib $MultiLogin" > /etc/cron.d/set_multilogin_autokill_lib
25 | echo -e "\e[0m "
26 | echo -e "\e[94m[][][]======================================[][][]"
27 | echo -e "\e[0m "
28 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
29 | echo -e "\e[0m "
30 | echo -e "\e[93m Allowed MultiLogin : "$MultiLogin
31 | echo -e "\e[93m AutoKill Every : 5 Minutes"
32 | echo -e "\e[0m "
33 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
34 | exit
35 | ;;
36 | 2)
37 | read -p " Allowed MultiLogin : " -e -i 1 MultiLogin
38 | echo -e "\e[0m "
39 | echo -e "\e[94m[][][]======================================[][][]\e[0m"s
40 | sleep 4
41 | clear
42 | echo "*/15 * * * * root /usr/bin/set_multilogin_autokill_lib $MultiLogin" > /etc/cron.d/set_multilogin_autokill_lib
43 | echo -e "\e[0m "
44 | echo -e "\e[94m[][][]======================================[][][]"
45 | echo -e "\e[0m "
46 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
47 | echo -e "\e[0m "
48 | echo -e "\e[93m Allowed MultiLogin : "$MultiLogin
49 | echo -e "\e[93m AutoKill Every : 15 Minutes"
50 | echo -e "\e[0m "
51 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
52 | exit
53 | ;;
54 | 3)
55 | read -p " Allowed MultiLogin : " -e -i 1 MultiLogin
56 | echo -e "\e[0m "
57 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
58 | sleep 4
59 | clear
60 | echo "*/30 * * * * root /usr/bin/set_multilogin_autokill_lib $MultiLogin" > /etc/cron.d/set_multilogin_autokill_lib
61 | echo -e "\e[0m "
62 | echo -e "\e[94m[][][]======================================[][][]"
63 | echo -e "\e[0m "
64 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
65 | echo -e "\e[0m "
66 | echo -e "\e[93m Allowed MultiLogin : "$MultiLogin
67 | echo -e "\e[93m AutoKill Every : 30 Minutes"
68 | echo -e "\e[0m "
69 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
70 | exit
71 | ;;
72 | 4)
73 | clear
74 | rm -f /etc/cron.d/set_multilogin_autokill_lib
75 | echo -e "\e[0m "
76 | echo -e "\e[94m[][][]======================================[][][]"
77 | echo -e "\e[0m "
78 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
79 | echo -e "\e[0m "
80 | echo -e "\e[93m AutoKill MultiLogin Turned "
81 | echo -e "\e[0m "
82 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
83 | exit
84 | ;;
85 | x)
86 | clear
87 | exit
88 | ;;
89 | esac
--------------------------------------------------------------------------------
/Files/Menu/set_multilogin_autokill_lib.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # Script by : _Dreyannz_
3 | #!/bin/bash
4 | clear
5 | fi
6 | MAX=1
7 | if [ -e "/var/log/auth.log" ]; then
8 | OS=1;
9 | LOG="/var/log/auth.log";
10 | fi
11 | if [ -e "/var/log/secure" ]; then
12 | OS=2;
13 | LOG="/var/log/secure";
14 | fi
15 |
16 | if [ $OS -eq 1 ]; then
17 | service ssh restart > /dev/null 2>&1;
18 | fi
19 | if [ $OS -eq 2 ]; then
20 | service sshd restart > /dev/null 2>&1;
21 | fi
22 | service dropbear restart > /dev/null 2>&1;
23 |
24 | if [[ ${1+x} ]]; then
25 | MAX=$1;
26 | fi
27 |
28 | cat /etc/passwd | grep "/home/" | cut -d":" -f1 > /root/user.txt
29 | username1=( `cat "/root/user.txt" `);
30 | i="0";
31 | for user in "${username1[@]}"
32 | do
33 | username[$i]=`echo $user | sed 's/'\''//g'`;
34 | jumlah[$i]=0;
35 | i=$i+1;
36 | done
37 | cat $LOG | grep -i dropbear | grep -i "Password auth succeeded" > /tmp/log-db.txt
38 | proc=( `ps aux | grep -i dropbear | awk '{print $2}'`);
39 | for PID in "${proc[@]}"
40 | do
41 | cat /tmp/log-db.txt | grep "dropbear\[$PID\]" > /tmp/log-db-pid.txt
42 | NUM=`cat /tmp/log-db-pid.txt | wc -l`;
43 | USER=`cat /tmp/log-db-pid.txt | awk '{print $10}' | sed 's/'\''//g'`;
44 | IP=`cat /tmp/log-db-pid.txt | awk '{print $12}'`;
45 | if [ $NUM -eq 1 ]; then
46 | i=0;
47 | for user1 in "${username[@]}"
48 | do
49 | if [ "$USER" == "$user1" ]; then
50 | jumlah[$i]=`expr ${jumlah[$i]} + 1`;
51 | pid[$i]="${pid[$i]} $PID"
52 | fi
53 | i=$i+1;
54 | done
55 | fi
56 | done
57 | cat $LOG | grep -i sshd | grep -i "Accepted password for" > /tmp/log-db.txt
58 | data=( `ps aux | grep "\[priv\]" | sort -k 72 | awk '{print $2}'`);
59 | for PID in "${data[@]}"
60 | do
61 | cat /tmp/log-db.txt | grep "sshd\[$PID\]" > /tmp/log-db-pid.txt;
62 | NUM=`cat /tmp/log-db-pid.txt | wc -l`;
63 | USER=`cat /tmp/log-db-pid.txt | awk '{print $9}'`;
64 | IP=`cat /tmp/log-db-pid.txt | awk '{print $11}'`;
65 | if [ $NUM -eq 1 ]; then
66 | i=0;
67 | for user1 in "${username[@]}"
68 | do
69 | if [ "$USER" == "$user1" ]; then
70 | jumlah[$i]=`expr ${jumlah[$i]} + 1`;
71 | pid[$i]="${pid[$i]} $PID"
72 | fi
73 | i=$i+1;
74 | done
75 | fi
76 | done
77 | j="0";
78 | for i in ${!username[*]}
79 | do
80 | if [ ${jumlah[$i]} -gt $MAX ]; then
81 | date=`date +"%Y-%m-%d %X"`;
82 | echo "$date - ${username[$i]} - ${jumlah[$i]}";
83 | echo "$date - ${username[$i]} - ${jumlah[$i]}" >> /root/log-limit.txt;
84 | kill ${pid[$i]};
85 | pid[$i]="";
86 | j=`expr $j + 1`;
87 | fi
88 | done
89 | if [ $j -gt 0 ]; then
90 | if [ $OS -eq 1 ]; then
91 | service ssh restart > /dev/null 2>&1;
92 | fi
93 | if [ $OS -eq 2 ]; then
94 | service sshd restart > /dev/null 2>&1;
95 | fi
96 | service dropbear restart > /dev/null 2>&1;
97 | j=0;
98 | fi
--------------------------------------------------------------------------------
/Files/Menu/show_ports.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # Script by : _Dreyannz_
3 | opensshport="$(netstat -ntlp | grep -i ssh | grep -i 0.0.0.0 | awk '{print $4}' | cut -d: -f2)"
4 | dropbearport="$(netstat -nlpt | grep -i dropbear | grep -i 0.0.0.0 | awk '{print $4}' | cut -d: -f2)"
5 | stunnel4port="$(netstat -nlpt | grep -i stunnel | grep -i 0.0.0.0 | awk '{print $4}' | cut -d: -f2)"
6 | openvpnport="$(netstat -nlpt | grep -i openvpn | grep -i 0.0.0.0 | awk '{print $4}' | cut -d: -f2)"
7 | squidport="$(cat /etc/squid3/squid.conf | grep -i http_port | awk '{print $2}')"
8 | clear
9 | echo -e "\e[0m "
10 | echo -e "\e[94m[][][]======================================[][][]"
11 | echo -e "\e[0m "
12 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
13 | echo -e "\e[0m "
14 | echo -e " Port OpenSSH : "$opensshport
15 | echo -e " Port Dropbear : "$dropbearport
16 | echo -e " Port SSL : "$stunnel4port
17 | echo -e " Port Squid : "$squidport
18 | echo -e " Port OpenVPN : "$openvpnport
19 | echo -e "\e[0m "
20 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
--------------------------------------------------------------------------------
/Files/Menu/speedtest:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | # Copyright 2012-2016 Matt Martz
4 | # All Rights Reserved.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
7 | # not use this file except in compliance with the License. You may obtain
8 | # a copy of the License at
9 | #
10 | # http://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | # License for the specific language governing permissions and limitations
16 | # under the License.
17 |
18 | import os
19 | import re
20 | import csv
21 | import sys
22 | import math
23 | import errno
24 | import signal
25 | import socket
26 | import timeit
27 | import datetime
28 | import platform
29 | import threading
30 | import xml.parsers.expat
31 |
32 | try:
33 | import gzip
34 | GZIP_BASE = gzip.GzipFile
35 | except ImportError:
36 | gzip = None
37 | GZIP_BASE = object
38 |
39 | __version__ = '1.0.4'
40 |
41 |
42 | class FakeShutdownEvent(object):
43 | """Class to fake a threading.Event.isSet so that users of this module
44 | are not required to register their own threading.Event()
45 | """
46 |
47 | @staticmethod
48 | def isSet():
49 | "Dummy method to always return false"""
50 | return False
51 |
52 |
53 | # Some global variables we use
54 | USER_AGENT = None
55 | SOURCE = None
56 | SHUTDOWN_EVENT = FakeShutdownEvent()
57 | SCHEME = 'http'
58 | DEBUG = False
59 |
60 | # Used for bound_interface
61 | SOCKET_SOCKET = socket.socket
62 |
63 | # Begin import game to handle Python 2 and Python 3
64 | try:
65 | import json
66 | except ImportError:
67 | try:
68 | import simplejson as json
69 | except ImportError:
70 | json = None
71 |
72 | try:
73 | import xml.etree.cElementTree as ET
74 | except ImportError:
75 | try:
76 | import xml.etree.ElementTree as ET
77 | except ImportError:
78 | from xml.dom import minidom as DOM
79 | ET = None
80 |
81 | try:
82 | from urllib2 import urlopen, Request, HTTPError, URLError
83 | except ImportError:
84 | from urllib.request import urlopen, Request, HTTPError, URLError
85 |
86 | try:
87 | from httplib import HTTPConnection
88 | except ImportError:
89 | from http.client import HTTPConnection
90 |
91 | try:
92 | from httplib import HTTPSConnection
93 | except ImportError:
94 | try:
95 | from http.client import HTTPSConnection
96 | except ImportError:
97 | HTTPSConnection = None
98 |
99 | try:
100 | from Queue import Queue
101 | except ImportError:
102 | from queue import Queue
103 |
104 | try:
105 | from urlparse import urlparse
106 | except ImportError:
107 | from urllib.parse import urlparse
108 |
109 | try:
110 | from urlparse import parse_qs
111 | except ImportError:
112 | try:
113 | from urllib.parse import parse_qs
114 | except ImportError:
115 | from cgi import parse_qs
116 |
117 | try:
118 | from hashlib import md5
119 | except ImportError:
120 | from md5 import md5
121 |
122 | try:
123 | from argparse import ArgumentParser as ArgParser
124 | from argparse import SUPPRESS as ARG_SUPPRESS
125 | PARSER_TYPE_INT = int
126 | PARSER_TYPE_STR = str
127 | except ImportError:
128 | from optparse import OptionParser as ArgParser
129 | from optparse import SUPPRESS_HELP as ARG_SUPPRESS
130 | PARSER_TYPE_INT = 'int'
131 | PARSER_TYPE_STR = 'string'
132 |
133 | try:
134 | from io import StringIO, BytesIO, TextIOWrapper, FileIO
135 | except ImportError:
136 | try:
137 | from cStringIO import StringIO
138 | BytesIO = None
139 | except ImportError:
140 | from StringIO import StringIO
141 | BytesIO = None
142 |
143 | try:
144 | import __builtin__
145 | except ImportError:
146 | import builtins
147 |
148 | class _Py3Utf8Stdout(TextIOWrapper):
149 | def __init__(self, **kwargs):
150 | buf = FileIO(sys.stdout.fileno(), 'w')
151 | super(_Py3Utf8Stdout, self).__init__(
152 | buf,
153 | encoding='utf8',
154 | errors='strict'
155 | )
156 |
157 | def write(self, s):
158 | super(_Py3Utf8Stdout, self).write(s)
159 | self.flush()
160 |
161 | _py3_print = getattr(builtins, 'print')
162 | _py3_utf8_stdout = _Py3Utf8Stdout()
163 |
164 | def print_(*args, **kwargs):
165 | kwargs['file'] = _py3_utf8_stdout
166 | _py3_print(*args, **kwargs)
167 | else:
168 | del __builtin__
169 |
170 | def print_(*args, **kwargs):
171 | """The new-style print function for Python 2.4 and 2.5.
172 |
173 | Taken from https://pypi.python.org/pypi/six/
174 |
175 | Modified to set encoding to UTF-8 always
176 | """
177 | fp = kwargs.pop("file", sys.stdout)
178 | if fp is None:
179 | return
180 |
181 | def write(data):
182 | if not isinstance(data, basestring):
183 | data = str(data)
184 | # If the file has an encoding, encode unicode with it.
185 | encoding = 'utf8' # Always trust UTF-8 for output
186 | if (isinstance(fp, file) and
187 | isinstance(data, unicode) and
188 | encoding is not None):
189 | errors = getattr(fp, "errors", None)
190 | if errors is None:
191 | errors = "strict"
192 | data = data.encode(encoding, errors)
193 | fp.write(data)
194 | want_unicode = False
195 | sep = kwargs.pop("sep", None)
196 | if sep is not None:
197 | if isinstance(sep, unicode):
198 | want_unicode = True
199 | elif not isinstance(sep, str):
200 | raise TypeError("sep must be None or a string")
201 | end = kwargs.pop("end", None)
202 | if end is not None:
203 | if isinstance(end, unicode):
204 | want_unicode = True
205 | elif not isinstance(end, str):
206 | raise TypeError("end must be None or a string")
207 | if kwargs:
208 | raise TypeError("invalid keyword arguments to print()")
209 | if not want_unicode:
210 | for arg in args:
211 | if isinstance(arg, unicode):
212 | want_unicode = True
213 | break
214 | if want_unicode:
215 | newline = unicode("\n")
216 | space = unicode(" ")
217 | else:
218 | newline = "\n"
219 | space = " "
220 | if sep is None:
221 | sep = space
222 | if end is None:
223 | end = newline
224 | for i, arg in enumerate(args):
225 | if i:
226 | write(sep)
227 | write(arg)
228 | write(end)
229 |
230 |
231 | # Exception "constants" to support Python 2 through Python 3
232 | try:
233 | import ssl
234 | try:
235 | CERT_ERROR = (ssl.CertificateError,)
236 | except AttributeError:
237 | CERT_ERROR = tuple()
238 |
239 | HTTP_ERRORS = ((HTTPError, URLError, socket.error, ssl.SSLError) +
240 | CERT_ERROR)
241 | except ImportError:
242 | HTTP_ERRORS = (HTTPError, URLError, socket.error)
243 |
244 |
245 | class SpeedtestException(Exception):
246 | """Base exception for this module"""
247 |
248 |
249 | class SpeedtestCLIError(SpeedtestException):
250 | """Generic exception for raising errors during CLI operation"""
251 |
252 |
253 | class SpeedtestHTTPError(SpeedtestException):
254 | """Base HTTP exception for this module"""
255 |
256 |
257 | class SpeedtestConfigError(SpeedtestException):
258 | """Configuration provided is invalid"""
259 |
260 |
261 | class ConfigRetrievalError(SpeedtestHTTPError):
262 | """Could not retrieve config.php"""
263 |
264 |
265 | class ServersRetrievalError(SpeedtestHTTPError):
266 | """Could not retrieve speedtest-servers.php"""
267 |
268 |
269 | class InvalidServerIDType(SpeedtestException):
270 | """Server ID used for filtering was not an integer"""
271 |
272 |
273 | class NoMatchedServers(SpeedtestException):
274 | """No servers matched when filtering"""
275 |
276 |
277 | class SpeedtestMiniConnectFailure(SpeedtestException):
278 | """Could not connect to the provided speedtest mini server"""
279 |
280 |
281 | class InvalidSpeedtestMiniServer(SpeedtestException):
282 | """Server provided as a speedtest mini server does not actually appear
283 | to be a speedtest mini server
284 | """
285 |
286 |
287 | class ShareResultsConnectFailure(SpeedtestException):
288 | """Could not connect to speedtest.net API to POST results"""
289 |
290 |
291 | class ShareResultsSubmitFailure(SpeedtestException):
292 | """Unable to successfully POST results to speedtest.net API after
293 | connection
294 | """
295 |
296 |
297 | class SpeedtestUploadTimeout(SpeedtestException):
298 | """testlength configuration reached during upload
299 | Used to ensure the upload halts when no additional data should be sent
300 | """
301 |
302 |
303 | class SpeedtestBestServerFailure(SpeedtestException):
304 | """Unable to determine best server"""
305 |
306 |
307 | class GzipDecodedResponse(GZIP_BASE):
308 | """A file-like object to decode a response encoded with the gzip
309 | method, as described in RFC 1952.
310 |
311 | Largely copied from ``xmlrpclib``/``xmlrpc.client`` and modified
312 | to work for py2.4-py3
313 | """
314 | def __init__(self, response):
315 | # response doesn't support tell() and read(), required by
316 | # GzipFile
317 | if not gzip:
318 | raise SpeedtestHTTPError('HTTP response body is gzip encoded, '
319 | 'but gzip support is not available')
320 | IO = BytesIO or StringIO
321 | self.io = IO()
322 | while 1:
323 | chunk = response.read(1024)
324 | if len(chunk) == 0:
325 | break
326 | self.io.write(chunk)
327 | self.io.seek(0)
328 | gzip.GzipFile.__init__(self, mode='rb', fileobj=self.io)
329 |
330 | def close(self):
331 | try:
332 | gzip.GzipFile.close(self)
333 | finally:
334 | self.io.close()
335 |
336 |
337 | def get_exception():
338 | """Helper function to work with py2.4-py3 for getting the current
339 | exception in a try/except block
340 | """
341 | return sys.exc_info()[1]
342 |
343 |
344 | def bound_socket(*args, **kwargs):
345 | """Bind socket to a specified source IP address"""
346 |
347 | sock = SOCKET_SOCKET(*args, **kwargs)
348 | sock.bind((SOURCE, 0))
349 | return sock
350 |
351 |
352 | def distance(origin, destination):
353 | """Determine distance between 2 sets of [lat,lon] in km"""
354 |
355 | lat1, lon1 = origin
356 | lat2, lon2 = destination
357 | radius = 6371 # km
358 |
359 | dlat = math.radians(lat2 - lat1)
360 | dlon = math.radians(lon2 - lon1)
361 | a = (math.sin(dlat / 2) * math.sin(dlat / 2) +
362 | math.cos(math.radians(lat1)) *
363 | math.cos(math.radians(lat2)) * math.sin(dlon / 2) *
364 | math.sin(dlon / 2))
365 | c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
366 | d = radius * c
367 |
368 | return d
369 |
370 |
371 | def build_user_agent():
372 | """Build a Mozilla/5.0 compatible User-Agent string"""
373 |
374 | global USER_AGENT
375 | if USER_AGENT:
376 | return USER_AGENT
377 |
378 | ua_tuple = (
379 | 'Mozilla/5.0',
380 | '(%s; U; %s; en-us)' % (platform.system(), platform.architecture()[0]),
381 | 'Python/%s' % platform.python_version(),
382 | '(KHTML, like Gecko)',
383 | 'speedtest-cli/%s' % __version__
384 | )
385 | USER_AGENT = ' '.join(ua_tuple)
386 | printer(USER_AGENT, debug=True)
387 | return USER_AGENT
388 |
389 |
390 | def build_request(url, data=None, headers=None, bump=''):
391 | """Build a urllib2 request object
392 |
393 | This function automatically adds a User-Agent header to all requests
394 |
395 | """
396 |
397 | if not USER_AGENT:
398 | build_user_agent()
399 |
400 | if not headers:
401 | headers = {}
402 |
403 | if url[0] == ':':
404 | schemed_url = '%s%s' % (SCHEME, url)
405 | else:
406 | schemed_url = url
407 |
408 | if '?' in url:
409 | delim = '&'
410 | else:
411 | delim = '?'
412 |
413 | # WHO YOU GONNA CALL? CACHE BUSTERS!
414 | final_url = '%s%sx=%s.%s' % (schemed_url, delim,
415 | int(timeit.time.time() * 1000),
416 | bump)
417 |
418 | headers.update({
419 | 'User-Agent': USER_AGENT,
420 | 'Cache-Control': 'no-cache',
421 | })
422 |
423 | printer('%s %s' % (('GET', 'POST')[bool(data)], final_url),
424 | debug=True)
425 |
426 | return Request(final_url, data=data, headers=headers)
427 |
428 |
429 | def catch_request(request):
430 | """Helper function to catch common exceptions encountered when
431 | establishing a connection with a HTTP/HTTPS request
432 |
433 | """
434 |
435 | try:
436 | uh = urlopen(request)
437 | return uh, False
438 | except HTTP_ERRORS:
439 | e = get_exception()
440 | return None, e
441 |
442 |
443 | def get_response_stream(response):
444 | """Helper function to return either a Gzip reader if
445 | ``Content-Encoding`` is ``gzip`` otherwise the response itself
446 |
447 | """
448 |
449 | try:
450 | getheader = response.headers.getheader
451 | except AttributeError:
452 | getheader = response.getheader
453 |
454 | if getheader('content-encoding') == 'gzip':
455 | return GzipDecodedResponse(response)
456 |
457 | return response
458 |
459 |
460 | def get_attributes_by_tag_name(dom, tag_name):
461 | """Retrieve an attribute from an XML document and return it in a
462 | consistent format
463 |
464 | Only used with xml.dom.minidom, which is likely only to be used
465 | with python versions older than 2.5
466 | """
467 | elem = dom.getElementsByTagName(tag_name)[0]
468 | return dict(list(elem.attributes.items()))
469 |
470 |
471 | def print_dots(current, total, start=False, end=False):
472 | """Built in callback function used by Thread classes for printing
473 | status
474 | """
475 |
476 | if SHUTDOWN_EVENT.isSet():
477 | return
478 |
479 | sys.stdout.write('.')
480 | if current + 1 == total and end is True:
481 | sys.stdout.write('\n')
482 | sys.stdout.flush()
483 |
484 |
485 | def do_nothing(*args, **kwargs):
486 | pass
487 |
488 |
489 | class HTTPDownloader(threading.Thread):
490 | """Thread class for retrieving a URL"""
491 |
492 | def __init__(self, i, request, start, timeout):
493 | threading.Thread.__init__(self)
494 | self.request = request
495 | self.result = [0]
496 | self.starttime = start
497 | self.timeout = timeout
498 | self.i = i
499 |
500 | def run(self):
501 | try:
502 | if (timeit.default_timer() - self.starttime) <= self.timeout:
503 | f = urlopen(self.request)
504 | while (not SHUTDOWN_EVENT.isSet() and
505 | (timeit.default_timer() - self.starttime) <=
506 | self.timeout):
507 | self.result.append(len(f.read(10240)))
508 | if self.result[-1] == 0:
509 | break
510 | f.close()
511 | except IOError:
512 | pass
513 |
514 |
515 | class HTTPUploaderData(object):
516 | """File like object to improve cutting off the upload once the timeout
517 | has been reached
518 | """
519 |
520 | def __init__(self, length, start, timeout):
521 | self.length = length
522 | self.start = start
523 | self.timeout = timeout
524 |
525 | self._data = None
526 |
527 | self.total = [0]
528 |
529 | def _create_data(self):
530 | chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
531 | multiplier = int(round(int(self.length) / 36.0))
532 | IO = BytesIO or StringIO
533 | self._data = IO(
534 | ('content1=%s' %
535 | (chars * multiplier)[0:int(self.length) - 9]
536 | ).encode()
537 | )
538 |
539 | @property
540 | def data(self):
541 | if not self._data:
542 | self._create_data()
543 | return self._data
544 |
545 | def read(self, n=10240):
546 | if ((timeit.default_timer() - self.start) <= self.timeout and
547 | not SHUTDOWN_EVENT.isSet()):
548 | chunk = self.data.read(n)
549 | self.total.append(len(chunk))
550 | return chunk
551 | else:
552 | raise SpeedtestUploadTimeout
553 |
554 | def __len__(self):
555 | return self.length
556 |
557 |
558 | class HTTPUploader(threading.Thread):
559 | """Thread class for putting a URL"""
560 |
561 | def __init__(self, i, request, start, size, timeout):
562 | threading.Thread.__init__(self)
563 | self.request = request
564 | self.request.data.start = self.starttime = start
565 | self.size = size
566 | self.result = None
567 | self.timeout = timeout
568 | self.i = i
569 |
570 | def run(self):
571 | request = self.request
572 | try:
573 | if ((timeit.default_timer() - self.starttime) <= self.timeout and
574 | not SHUTDOWN_EVENT.isSet()):
575 | try:
576 | f = urlopen(request)
577 | except TypeError:
578 | # PY24 expects a string or buffer
579 | # This also causes issues with Ctrl-C, but we will concede
580 | # for the moment that Ctrl-C on PY24 isn't immediate
581 | request = build_request(self.request.get_full_url(),
582 | data=request.data.read(self.size))
583 | f = urlopen(request)
584 | f.read(11)
585 | f.close()
586 | self.result = sum(self.request.data.total)
587 | else:
588 | self.result = 0
589 | except (IOError, SpeedtestUploadTimeout):
590 | self.result = sum(self.request.data.total)
591 |
592 |
593 | class SpeedtestResults(object):
594 | """Class for holding the results of a speedtest, including:
595 |
596 | Download speed
597 | Upload speed
598 | Ping/Latency to test server
599 | Data about server that the test was run against
600 |
601 | Additionally this class can return a result data as a dictionary or CSV,
602 | as well as submit a POST of the result data to the speedtest.net API
603 | to get a share results image link.
604 | """
605 |
606 | def __init__(self, download=0, upload=0, ping=0, server=None):
607 | self.download = download
608 | self.upload = upload
609 | self.ping = ping
610 | if server is None:
611 | self.server = {}
612 | else:
613 | self.server = server
614 | self._share = None
615 | self.timestamp = datetime.datetime.utcnow().isoformat()
616 | self.bytes_received = 0
617 | self.bytes_sent = 0
618 |
619 | def __repr__(self):
620 | return repr(self.dict())
621 |
622 | def share(self):
623 | """POST data to the speedtest.net API to obtain a share results
624 | link
625 | """
626 |
627 | if self._share:
628 | return self._share
629 |
630 | download = int(round(self.download / 1000.0, 0))
631 | ping = int(round(self.ping, 0))
632 | upload = int(round(self.upload / 1000.0, 0))
633 |
634 | # Build the request to send results back to speedtest.net
635 | # We use a list instead of a dict because the API expects parameters
636 | # in a certain order
637 | api_data = [
638 | 'recommendedserverid=%s' % self.server['id'],
639 | 'ping=%s' % ping,
640 | 'screenresolution=',
641 | 'promo=',
642 | 'download=%s' % download,
643 | 'screendpi=',
644 | 'upload=%s' % upload,
645 | 'testmethod=http',
646 | 'hash=%s' % md5(('%s-%s-%s-%s' %
647 | (ping, upload, download, '297aae72'))
648 | .encode()).hexdigest(),
649 | 'touchscreen=none',
650 | 'startmode=pingselect',
651 | 'accuracy=1',
652 | 'bytesreceived=%s' % self.bytes_received,
653 | 'bytessent=%s' % self.bytes_sent,
654 | 'serverid=%s' % self.server['id'],
655 | ]
656 |
657 | headers = {'Referer': 'http://c.speedtest.net/flash/speedtest.swf'}
658 | request = build_request('://www.speedtest.net/api/api.php',
659 | data='&'.join(api_data).encode(),
660 | headers=headers)
661 | f, e = catch_request(request)
662 | if e:
663 | raise ShareResultsConnectFailure(e)
664 |
665 | response = f.read()
666 | code = f.code
667 | f.close()
668 |
669 | if int(code) != 200:
670 | raise ShareResultsSubmitFailure('Could not submit results to '
671 | 'speedtest.net')
672 |
673 | qsargs = parse_qs(response.decode())
674 | resultid = qsargs.get('resultid')
675 | if not resultid or len(resultid) != 1:
676 | raise ShareResultsSubmitFailure('Could not submit results to '
677 | 'speedtest.net')
678 |
679 | self._share = 'http://www.speedtest.net/result/%s.png' % resultid[0]
680 |
681 | return self._share
682 |
683 | def dict(self):
684 | """Return dictionary of result data"""
685 |
686 | return {
687 | 'download': self.download,
688 | 'upload': self.upload,
689 | 'ping': self.ping,
690 | 'server': self.server,
691 | 'timestamp': self.timestamp,
692 | 'bytes_sent': self.bytes_sent,
693 | 'bytes_received': self.bytes_received,
694 | 'share': self._share,
695 | }
696 |
697 | def csv(self, delimiter=','):
698 | """Return data in CSV format"""
699 |
700 | data = self.dict()
701 | out = StringIO()
702 | writer = csv.writer(out, delimiter=delimiter, lineterminator='')
703 | writer.writerow([data['server']['id'], data['server']['sponsor'],
704 | data['server']['name'], data['timestamp'],
705 | data['server']['d'], data['ping'], data['download'],
706 | data['upload']])
707 | return out.getvalue()
708 |
709 | def json(self, pretty=False):
710 | """Return data in JSON format"""
711 |
712 | kwargs = {}
713 | if pretty:
714 | kwargs.update({
715 | 'indent': 4,
716 | 'sort_keys': True
717 | })
718 | return json.dumps(self.dict(), **kwargs)
719 |
720 |
721 | class Speedtest(object):
722 | """Class for performing standard speedtest.net testing operations"""
723 |
724 | def __init__(self, config=None):
725 | self.config = {}
726 | self.get_config()
727 | if config is not None:
728 | self.config.update(config)
729 |
730 | self.servers = {}
731 | self.closest = []
732 | self.best = {}
733 |
734 | self.results = SpeedtestResults()
735 |
736 | def get_config(self):
737 | """Download the speedtest.net configuration and return only the data
738 | we are interested in
739 | """
740 |
741 | headers = {}
742 | if gzip:
743 | headers['Accept-Encoding'] = 'gzip'
744 | request = build_request('://www.speedtest.net/speedtest-config.php',
745 | headers=headers)
746 | uh, e = catch_request(request)
747 | if e:
748 | raise ConfigRetrievalError(e)
749 | configxml = []
750 |
751 | stream = get_response_stream(uh)
752 |
753 | while 1:
754 | configxml.append(stream.read(1024))
755 | if len(configxml[-1]) == 0:
756 | break
757 | stream.close()
758 | uh.close()
759 |
760 | if int(uh.code) != 200:
761 | return None
762 |
763 | printer(''.encode().join(configxml), debug=True)
764 |
765 | try:
766 | root = ET.fromstring(''.encode().join(configxml))
767 | server_config = root.find('server-config').attrib
768 | download = root.find('download').attrib
769 | upload = root.find('upload').attrib
770 | # times = root.find('times').attrib
771 | client = root.find('client').attrib
772 |
773 | except AttributeError:
774 | root = DOM.parseString(''.join(configxml))
775 | server_config = get_attributes_by_tag_name(root, 'server-config')
776 | download = get_attributes_by_tag_name(root, 'download')
777 | upload = get_attributes_by_tag_name(root, 'upload')
778 | # times = get_attributes_by_tag_name(root, 'times')
779 | client = get_attributes_by_tag_name(root, 'client')
780 |
781 | ignore_servers = list(
782 | map(int, server_config['ignoreids'].split(','))
783 | )
784 |
785 | ratio = int(upload['ratio'])
786 | upload_max = int(upload['maxchunkcount'])
787 | up_sizes = [32768, 65536, 131072, 262144, 524288, 1048576, 7340032]
788 | sizes = {
789 | 'upload': up_sizes[ratio - 1:],
790 | 'download': [350, 500, 750, 1000, 1500, 2000, 2500,
791 | 3000, 3500, 4000]
792 | }
793 |
794 | counts = {
795 | 'upload': int(upload_max * 2 / len(sizes['upload'])),
796 | 'download': int(download['threadsperurl'])
797 | }
798 |
799 | threads = {
800 | 'upload': int(upload['threads']),
801 | 'download': int(server_config['threadcount']) * 2
802 | }
803 |
804 | length = {
805 | 'upload': int(upload['testlength']),
806 | 'download': int(download['testlength'])
807 | }
808 |
809 | self.config.update({
810 | 'client': client,
811 | 'ignore_servers': ignore_servers,
812 | 'sizes': sizes,
813 | 'counts': counts,
814 | 'threads': threads,
815 | 'length': length,
816 | 'upload_max': upload_max
817 | })
818 |
819 | self.lat_lon = (float(client['lat']), float(client['lon']))
820 |
821 | return self.config
822 |
823 | def get_servers(self, servers=None):
824 | """Retrieve a the list of speedtest.net servers, optionally filtered
825 | to servers matching those specified in the ``servers`` argument
826 | """
827 | if servers is None:
828 | servers = []
829 |
830 | self.servers.clear()
831 |
832 | for i, s in enumerate(servers):
833 | try:
834 | servers[i] = int(s)
835 | except ValueError:
836 | raise InvalidServerIDType('%s is an invalid server type, must '
837 | 'be int' % s)
838 |
839 | urls = [
840 | '://www.speedtest.net/speedtest-servers-static.php',
841 | 'http://c.speedtest.net/speedtest-servers-static.php',
842 | '://www.speedtest.net/speedtest-servers.php',
843 | 'http://c.speedtest.net/speedtest-servers.php',
844 | ]
845 |
846 | headers = {}
847 | if gzip:
848 | headers['Accept-Encoding'] = 'gzip'
849 |
850 | errors = []
851 | for url in urls:
852 | try:
853 | request = build_request('%s?threads=%s' %
854 | (url,
855 | self.config['threads']['download']),
856 | headers=headers)
857 | uh, e = catch_request(request)
858 | if e:
859 | errors.append('%s' % e)
860 | raise ServersRetrievalError
861 |
862 | stream = get_response_stream(uh)
863 |
864 | serversxml = []
865 | while 1:
866 | serversxml.append(stream.read(1024))
867 | if len(serversxml[-1]) == 0:
868 | break
869 |
870 | stream.close()
871 | uh.close()
872 |
873 | if int(uh.code) != 200:
874 | raise ServersRetrievalError
875 |
876 | printer(''.encode().join(serversxml), debug=True)
877 |
878 | try:
879 | try:
880 | root = ET.fromstring(''.encode().join(serversxml))
881 | elements = root.getiterator('server')
882 | except AttributeError:
883 | root = DOM.parseString(''.join(serversxml))
884 | elements = root.getElementsByTagName('server')
885 | except (SyntaxError, xml.parsers.expat.ExpatError):
886 | raise ServersRetrievalError
887 |
888 | for server in elements:
889 | try:
890 | attrib = server.attrib
891 | except AttributeError:
892 | attrib = dict(list(server.attributes.items()))
893 |
894 | if servers and int(attrib.get('id')) not in servers:
895 | continue
896 |
897 | if int(attrib.get('id')) in self.config['ignore_servers']:
898 | continue
899 |
900 | try:
901 | d = distance(self.lat_lon,
902 | (float(attrib.get('lat')),
903 | float(attrib.get('lon'))))
904 | except:
905 | continue
906 |
907 | attrib['d'] = d
908 |
909 | try:
910 | self.servers[d].append(attrib)
911 | except KeyError:
912 | self.servers[d] = [attrib]
913 |
914 | printer(''.encode().join(serversxml), debug=True)
915 |
916 | break
917 |
918 | except ServersRetrievalError:
919 | continue
920 |
921 | if servers and not self.servers:
922 | raise NoMatchedServers
923 |
924 | return self.servers
925 |
926 | def set_mini_server(self, server):
927 | """Instead of querying for a list of servers, set a link to a
928 | speedtest mini server
929 | """
930 |
931 | urlparts = urlparse(server)
932 |
933 | name, ext = os.path.splitext(urlparts[2])
934 | if ext:
935 | url = os.path.dirname(server)
936 | else:
937 | url = server
938 |
939 | request = build_request(url)
940 | uh, e = catch_request(request)
941 | if e:
942 | raise SpeedtestMiniConnectFailure('Failed to connect to %s' %
943 | server)
944 | else:
945 | text = uh.read()
946 | uh.close()
947 |
948 | extension = re.findall('upload_?[Ee]xtension: "([^"]+)"',
949 | text.decode())
950 | if not extension:
951 | for ext in ['php', 'asp', 'aspx', 'jsp']:
952 | try:
953 | f = urlopen('%s/speedtest/upload.%s' % (url, ext))
954 | except:
955 | pass
956 | else:
957 | data = f.read().strip().decode()
958 | if (f.code == 200 and
959 | len(data.splitlines()) == 1 and
960 | re.match('size=[0-9]', data)):
961 | extension = [ext]
962 | break
963 | if not urlparts or not extension:
964 | raise InvalidSpeedtestMiniServer('Invalid Speedtest Mini Server: '
965 | '%s' % server)
966 |
967 | self.servers = [{
968 | 'sponsor': 'Speedtest Mini',
969 | 'name': urlparts[1],
970 | 'd': 0,
971 | 'url': '%s/speedtest/upload.%s' % (url.rstrip('/'), extension[0]),
972 | 'latency': 0,
973 | 'id': 0
974 | }]
975 |
976 | return self.servers
977 |
978 | def get_closest_servers(self, limit=5):
979 | """Limit servers to the closest speedtest.net servers based on
980 | geographic distance
981 | """
982 |
983 | if not self.servers:
984 | self.get_servers()
985 |
986 | for d in sorted(self.servers.keys()):
987 | for s in self.servers[d]:
988 | self.closest.append(s)
989 | if len(self.closest) == limit:
990 | break
991 | else:
992 | continue
993 | break
994 |
995 | printer(self.closest, debug=True)
996 | return self.closest
997 |
998 | def get_best_server(self, servers=None):
999 | """Perform a speedtest.net "ping" to determine which speedtest.net
1000 | server has the lowest latency
1001 | """
1002 |
1003 | if not servers:
1004 | if not self.closest:
1005 | servers = self.get_closest_servers()
1006 | servers = self.closest
1007 |
1008 | results = {}
1009 | for server in servers:
1010 | cum = []
1011 | url = os.path.dirname(server['url'])
1012 | urlparts = urlparse('%s/latency.txt' % url)
1013 | printer('%s %s/latency.txt' % ('GET', url), debug=True)
1014 | for _ in range(0, 3):
1015 | try:
1016 | if urlparts[0] == 'https':
1017 | h = HTTPSConnection(urlparts[1])
1018 | else:
1019 | h = HTTPConnection(urlparts[1])
1020 | headers = {'User-Agent': USER_AGENT}
1021 | start = timeit.default_timer()
1022 | h.request("GET", urlparts[2], headers=headers)
1023 | r = h.getresponse()
1024 | total = (timeit.default_timer() - start)
1025 | except HTTP_ERRORS:
1026 | e = get_exception()
1027 | printer('%r' % e, debug=True)
1028 | cum.append(3600)
1029 | continue
1030 |
1031 | text = r.read(9)
1032 | if int(r.status) == 200 and text == 'test=test'.encode():
1033 | cum.append(total)
1034 | else:
1035 | cum.append(3600)
1036 | h.close()
1037 |
1038 | avg = round((sum(cum) / 6) * 1000.0, 3)
1039 | results[avg] = server
1040 |
1041 | try:
1042 | fastest = sorted(results.keys())[0]
1043 | except IndexError:
1044 | raise SpeedtestBestServerFailure('Unable to connect to servers to '
1045 | 'test latency.')
1046 | best = results[fastest]
1047 | best['latency'] = fastest
1048 |
1049 | self.results.ping = fastest
1050 | self.results.server = best
1051 |
1052 | self.best.update(best)
1053 | printer(best, debug=True)
1054 | return best
1055 |
1056 | def download(self, callback=do_nothing):
1057 | """Test download speed against speedtest.net"""
1058 |
1059 | urls = []
1060 | for size in self.config['sizes']['download']:
1061 | for _ in range(0, self.config['counts']['download']):
1062 | urls.append('%s/random%sx%s.jpg' %
1063 | (os.path.dirname(self.best['url']), size, size))
1064 |
1065 | request_count = len(urls)
1066 | requests = []
1067 | for i, url in enumerate(urls):
1068 | requests.append(build_request(url, bump=i))
1069 |
1070 | def producer(q, requests, request_count):
1071 | for i, request in enumerate(requests):
1072 | thread = HTTPDownloader(i, request, start,
1073 | self.config['length']['download'])
1074 | thread.start()
1075 | q.put(thread, True)
1076 | callback(i, request_count, start=True)
1077 |
1078 | finished = []
1079 |
1080 | def consumer(q, request_count):
1081 | while len(finished) < request_count:
1082 | thread = q.get(True)
1083 | while thread.isAlive():
1084 | thread.join(timeout=0.1)
1085 | finished.append(sum(thread.result))
1086 | callback(thread.i, request_count, end=True)
1087 |
1088 | q = Queue(self.config['threads']['download'])
1089 | prod_thread = threading.Thread(target=producer,
1090 | args=(q, requests, request_count))
1091 | cons_thread = threading.Thread(target=consumer,
1092 | args=(q, request_count))
1093 | start = timeit.default_timer()
1094 | prod_thread.start()
1095 | cons_thread.start()
1096 | while prod_thread.isAlive():
1097 | prod_thread.join(timeout=0.1)
1098 | while cons_thread.isAlive():
1099 | cons_thread.join(timeout=0.1)
1100 |
1101 | stop = timeit.default_timer()
1102 | self.results.bytes_received = sum(finished)
1103 | self.results.download = (
1104 | (self.results.bytes_received / (stop - start)) * 8.0
1105 | )
1106 | if self.results.download > 100000:
1107 | self.config['threads']['upload'] = 8
1108 | return self.results.download
1109 |
1110 | def upload(self, callback=do_nothing):
1111 | """Test upload speed against speedtest.net"""
1112 |
1113 | sizes = []
1114 |
1115 | for size in self.config['sizes']['upload']:
1116 | for _ in range(0, self.config['counts']['upload']):
1117 | sizes.append(size)
1118 |
1119 | # request_count = len(sizes)
1120 | request_count = self.config['upload_max']
1121 |
1122 | requests = []
1123 | for i, size in enumerate(sizes):
1124 | # We set ``0`` for ``start`` and handle setting the actual
1125 | # ``start`` in ``HTTPUploader`` to get better measurements
1126 | requests.append(
1127 | (
1128 | build_request(
1129 | self.best['url'],
1130 | HTTPUploaderData(size, 0,
1131 | self.config['length']['upload'])
1132 | ),
1133 | size
1134 | )
1135 | )
1136 |
1137 | def producer(q, requests, request_count):
1138 | for i, request in enumerate(requests[:request_count]):
1139 | thread = HTTPUploader(i, request[0], start, request[1],
1140 | self.config['length']['upload'])
1141 | thread.start()
1142 | q.put(thread, True)
1143 | callback(i, request_count, start=True)
1144 |
1145 | finished = []
1146 |
1147 | def consumer(q, request_count):
1148 | while len(finished) < request_count:
1149 | thread = q.get(True)
1150 | while thread.isAlive():
1151 | thread.join(timeout=0.1)
1152 | finished.append(thread.result)
1153 | callback(thread.i, request_count, end=True)
1154 |
1155 | q = Queue(self.config['threads']['upload'])
1156 | prod_thread = threading.Thread(target=producer,
1157 | args=(q, requests, request_count))
1158 | cons_thread = threading.Thread(target=consumer,
1159 | args=(q, request_count))
1160 | start = timeit.default_timer()
1161 | prod_thread.start()
1162 | cons_thread.start()
1163 | while prod_thread.isAlive():
1164 | prod_thread.join(timeout=0.1)
1165 | while cons_thread.isAlive():
1166 | cons_thread.join(timeout=0.1)
1167 |
1168 | stop = timeit.default_timer()
1169 | self.results.bytes_sent = sum(finished)
1170 | self.results.upload = (
1171 | (self.results.bytes_sent / (stop - start)) * 8.0
1172 | )
1173 | return self.results.upload
1174 |
1175 |
1176 | def ctrl_c(signum, frame):
1177 | """Catch Ctrl-C key sequence and set a SHUTDOWN_EVENT for our threaded
1178 | operations
1179 | """
1180 |
1181 | SHUTDOWN_EVENT.set()
1182 | print_('\nCancelling...')
1183 | sys.exit(0)
1184 |
1185 |
1186 | def version():
1187 | """Print the version"""
1188 |
1189 | print_(__version__)
1190 | sys.exit(0)
1191 |
1192 |
1193 | def csv_header():
1194 | """Print the CSV Headers"""
1195 |
1196 | print_('Server ID,Sponsor,Server Name,Timestamp,Distance,Ping,Download,'
1197 | 'Upload')
1198 | sys.exit(0)
1199 |
1200 |
1201 | def parse_args():
1202 | """Function to handle building and parsing of command line arguments"""
1203 | description = (
1204 | 'Command line interface for testing internet bandwidth using '
1205 | 'speedtest.net.\n'
1206 | '------------------------------------------------------------'
1207 | '--------------\n'
1208 | 'https://github.com/sivel/speedtest-cli')
1209 |
1210 | parser = ArgParser(description=description)
1211 | # Give optparse.OptionParser an `add_argument` method for
1212 | # compatibility with argparse.ArgumentParser
1213 | try:
1214 | parser.add_argument = parser.add_option
1215 | except AttributeError:
1216 | pass
1217 | parser.add_argument('--no-download', dest='download', default=True,
1218 | action='store_const', const=False,
1219 | help='Do not perform download test')
1220 | parser.add_argument('--no-upload', dest='upload', default=True,
1221 | action='store_const', const=False,
1222 | help='Do not perform upload test')
1223 | parser.add_argument('--bytes', dest='units', action='store_const',
1224 | const=('byte', 8), default=('bit', 1),
1225 | help='Display values in bytes instead of bits. Does '
1226 | 'not affect the image generated by --share, nor '
1227 | 'output from --json or --csv')
1228 | parser.add_argument('--share', action='store_true',
1229 | help='Generate and provide a URL to the speedtest.net '
1230 | 'share results image, not displayed with --csv')
1231 | parser.add_argument('--simple', action='store_true', default=False,
1232 | help='Suppress verbose output, only show basic '
1233 | 'information')
1234 | parser.add_argument('--csv', action='store_true', default=False,
1235 | help='Suppress verbose output, only show basic '
1236 | 'information in CSV format. Speeds listed in '
1237 | 'bit/s and not affected by --bytes')
1238 | parser.add_argument('--csv-delimiter', default=',', type=PARSER_TYPE_STR,
1239 | help='Single character delimiter to use in CSV '
1240 | 'output. Default ","')
1241 | parser.add_argument('--csv-header', action='store_true', default=False,
1242 | help='Print CSV headers')
1243 | parser.add_argument('--json', action='store_true', default=False,
1244 | help='Suppress verbose output, only show basic '
1245 | 'information in JSON format. Speeds listed in '
1246 | 'bit/s and not affected by --bytes')
1247 | parser.add_argument('--list', action='store_true',
1248 | help='Display a list of speedtest.net servers '
1249 | 'sorted by distance')
1250 | parser.add_argument('--server', help='Specify a server ID to test against',
1251 | type=PARSER_TYPE_INT)
1252 | parser.add_argument('--mini', help='URL of the Speedtest Mini server')
1253 | parser.add_argument('--source', help='Source IP address to bind to')
1254 | parser.add_argument('--timeout', default=10, type=PARSER_TYPE_INT,
1255 | help='HTTP timeout in seconds. Default 10')
1256 | parser.add_argument('--secure', action='store_true',
1257 | help='Use HTTPS instead of HTTP when communicating '
1258 | 'with speedtest.net operated servers')
1259 | parser.add_argument('--version', action='store_true',
1260 | help='Show the version number and exit')
1261 | parser.add_argument('--debug', action='store_true',
1262 | help=ARG_SUPPRESS, default=ARG_SUPPRESS)
1263 |
1264 | options = parser.parse_args()
1265 | if isinstance(options, tuple):
1266 | args = options[0]
1267 | else:
1268 | args = options
1269 | return args
1270 |
1271 |
1272 | def validate_optional_args(args):
1273 | """Check if an argument was provided that depends on a module that may
1274 | not be part of the Python standard library.
1275 |
1276 | If such an argument is supplied, and the module does not exist, exit
1277 | with an error stating which module is missing.
1278 | """
1279 | optional_args = {
1280 | 'json': ('json/simplejson python module', json),
1281 | 'secure': ('SSL support', HTTPSConnection),
1282 | }
1283 |
1284 | for arg, info in optional_args.items():
1285 | if getattr(args, arg, False) and info[1] is None:
1286 | raise SystemExit('%s is not installed. --%s is '
1287 | 'unavailable' % (info[0], arg))
1288 |
1289 |
1290 | def printer(string, quiet=False, debug=False, **kwargs):
1291 | """Helper function to print a string only when not quiet"""
1292 |
1293 | if debug and not DEBUG:
1294 | return
1295 |
1296 | if debug:
1297 | out = '\033[1;30mDEBUG: %s\033[0m' % string
1298 | else:
1299 | out = string
1300 |
1301 | if not quiet:
1302 | print_(out, **kwargs)
1303 |
1304 |
1305 | def shell():
1306 | """Run the full speedtest.net test"""
1307 |
1308 | global SHUTDOWN_EVENT, SOURCE, SCHEME, DEBUG
1309 | SHUTDOWN_EVENT = threading.Event()
1310 |
1311 | signal.signal(signal.SIGINT, ctrl_c)
1312 |
1313 | args = parse_args()
1314 |
1315 | # Print the version and exit
1316 | if args.version:
1317 | version()
1318 |
1319 | if not args.download and not args.upload:
1320 | raise SpeedtestCLIError('Cannot supply both --no-download and '
1321 | '--no-upload')
1322 |
1323 | if args.csv_header:
1324 | csv_header()
1325 |
1326 | if len(args.csv_delimiter) != 1:
1327 | raise SpeedtestCLIError('--csv-delimiter must be a single character')
1328 |
1329 | validate_optional_args(args)
1330 |
1331 | socket.setdefaulttimeout(args.timeout)
1332 |
1333 | # If specified bind to a specific IP address
1334 | if args.source:
1335 | SOURCE = args.source
1336 | socket.socket = bound_socket
1337 |
1338 | if args.secure:
1339 | SCHEME = 'https'
1340 |
1341 | debug = getattr(args, 'debug', False)
1342 | if debug == 'SUPPRESSHELP':
1343 | debug = False
1344 | if debug:
1345 | DEBUG = True
1346 |
1347 | # Pre-cache the user agent string
1348 | build_user_agent()
1349 |
1350 | if args.simple or args.csv or args.json:
1351 | quiet = True
1352 | else:
1353 | quiet = False
1354 |
1355 | if args.csv or args.json:
1356 | machine_format = True
1357 | else:
1358 | machine_format = False
1359 |
1360 | # Don't set a callback if we are running quietly
1361 | if quiet or debug:
1362 | callback = do_nothing
1363 | else:
1364 | callback = print_dots
1365 |
1366 | printer('Retrieving speedtest.net configuration...', quiet)
1367 | try:
1368 | speedtest = Speedtest()
1369 | except (ConfigRetrievalError, HTTP_ERRORS):
1370 | printer('Cannot retrieve speedtest configuration')
1371 | raise SpeedtestCLIError(get_exception())
1372 |
1373 | if args.list:
1374 | try:
1375 | speedtest.get_servers()
1376 | except (ServersRetrievalError, HTTP_ERRORS):
1377 | print_('Cannot retrieve speedtest server list')
1378 | raise SpeedtestCLIError(get_exception())
1379 |
1380 | for _, servers in sorted(speedtest.servers.items()):
1381 | for server in servers:
1382 | line = ('%(id)5s) %(sponsor)s (%(name)s, %(country)s) '
1383 | '[%(d)0.2f km]' % server)
1384 | try:
1385 | print_(line)
1386 | except IOError:
1387 | e = get_exception()
1388 | if e.errno != errno.EPIPE:
1389 | raise
1390 | sys.exit(0)
1391 |
1392 | # Set a filter of servers to retrieve
1393 | servers = []
1394 | if args.server:
1395 | servers.append(args.server)
1396 |
1397 | printer('Testing from %(isp)s (%(ip)s)...' % speedtest.config['client'],
1398 | quiet)
1399 |
1400 | if not args.mini:
1401 | printer('Retrieving speedtest.net server list...', quiet)
1402 | try:
1403 | speedtest.get_servers(servers)
1404 | except NoMatchedServers:
1405 | raise SpeedtestCLIError('No matched servers: %s' % args.server)
1406 | except (ServersRetrievalError, HTTP_ERRORS):
1407 | print_('Cannot retrieve speedtest server list')
1408 | raise SpeedtestCLIError(get_exception())
1409 | except InvalidServerIDType:
1410 | raise SpeedtestCLIError('%s is an invalid server type, must '
1411 | 'be an int' % args.server)
1412 |
1413 | printer('Selecting best server based on ping...', quiet)
1414 | speedtest.get_best_server()
1415 | elif args.mini:
1416 | speedtest.get_best_server(speedtest.set_mini_server(args.mini))
1417 |
1418 | results = speedtest.results
1419 |
1420 | printer('Hosted by %(sponsor)s (%(name)s) [%(d)0.2f km]: '
1421 | '%(latency)s ms' % results.server, quiet)
1422 |
1423 | if args.download:
1424 | printer('Testing download speed', quiet,
1425 | end=('', '\n')[bool(debug)])
1426 | speedtest.download(callback=callback)
1427 | printer('Download: %0.2f M%s/s' %
1428 | ((results.download / 1000.0 / 1000.0) / args.units[1],
1429 | args.units[0]),
1430 | quiet)
1431 | else:
1432 | printer('Skipping download test')
1433 |
1434 | if args.upload:
1435 | printer('Testing upload speed', quiet,
1436 | end=('', '\n')[bool(debug)])
1437 | speedtest.upload(callback=callback)
1438 | printer('Upload: %0.2f M%s/s' %
1439 | ((results.upload / 1000.0 / 1000.0) / args.units[1],
1440 | args.units[0]),
1441 | quiet)
1442 | else:
1443 | printer('Skipping upload test')
1444 |
1445 | if args.simple:
1446 | print_('Ping: %s ms\nDownload: %0.2f M%s/s\nUpload: %0.2f M%s/s' %
1447 | (results.ping,
1448 | (results.download / 1000.0 / 1000.0) / args.units[1],
1449 | args.units[0],
1450 | (results.upload / 1000.0 / 1000.0) / args.units[1],
1451 | args.units[0]))
1452 | elif args.csv:
1453 | print_(results.csv(delimiter=args.csv_delimiter))
1454 | elif args.json:
1455 | if args.share:
1456 | results.share()
1457 | print_(results.json())
1458 |
1459 | if args.share and not machine_format:
1460 | printer('Share results: %s' % results.share())
1461 |
1462 |
1463 | def main():
1464 | try:
1465 | shell()
1466 | except KeyboardInterrupt:
1467 | print_('\nCancelling...')
1468 | except (SpeedtestException, SystemExit):
1469 | e = get_exception()
1470 | if getattr(e, 'code', 1) != 0:
1471 | raise SystemExit('ERROR: %s' % e)
1472 |
1473 |
1474 | if __name__ == '__main__':
1475 | main()
1476 |
1477 | # vim:ts=4:sw=4:expandtab
1478 |
--------------------------------------------------------------------------------
/Files/Menu/user_delete.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # Script by : _Dreyannz_
3 | clear
4 | echo -e "\e[0m "
5 | echo -e "\e[94m[][][]======================================[][][]"
6 | echo -e "\e[0m "
7 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
8 | echo -e "\e[0m "
9 | read -p " Username : " User
10 | echo -e "\e[0m "
11 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
12 | sleep 2
13 | egrep "^$User" /etc/passwd >/dev/null
14 | if [ $? -eq 0 ]; then
15 | userdel -f $User
16 | clear
17 | echo -e "\e[0m "
18 | echo -e "\e[94m[][][]======================================[][][]"
19 | echo -e "\e[0m "
20 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
21 | echo -e "\e[0m "
22 | echo -e "\e[93m User Deleted "
23 | echo -e "\e[0m "
24 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
25 | else
26 | clear
27 | echo -e "\e[0m "
28 | echo -e "\e[94m[][][]======================================[][][]"
29 | echo -e "\e[0m "
30 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
31 | echo -e "\e[0m "
32 | echo -e "\e[93m User Doesnt Exist "
33 | echo -e "\e[0m "
34 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
--------------------------------------------------------------------------------
/Files/Menu/user_details.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # Script by : _Dreyannz_
3 | clear
4 | echo -e "\e[0m "
5 | echo -e "\e[94m[][][]======================================[][][]"
6 | echo -e "\e[0m "
7 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
8 | echo -e "\e[0m "
9 | read -p " Username : " User
10 | echo -e "\e[0m "
11 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
12 | sleep 1
13 | user_details_lib $User
--------------------------------------------------------------------------------
/Files/Menu/user_details_lib.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # Script by : _Dreyannz_
3 | Username=`cat /etc/passwd | grep -Ew ^$1 | cut -d":" -f1`
4 | if [ "$Username" = "" ]
5 | then
6 | clear
7 | echo -e "\e[0m "
8 | echo -e "\e[94m[][][]======================================[][][]"
9 | echo -e "\e[0m "
10 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
11 | echo -e "\e[0m "
12 | echo -e "\e[93m Username Doesnt Exist "
13 | echo -e "\e[0m "
14 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
15 | exit
16 | fi
17 | Userid=`cat /etc/passwd | grep -Ew ^$Username | cut -d":" -f3`
18 | UserPrimaryGroupId=`cat /etc/passwd | grep -Ew ^$Username | cut -d":" -f4`
19 | UserPrimaryGroup=`cat /etc/group | grep :"$UserPrimaryGroupId": | cut -d":" -f1`
20 | UserInfo=`cat /etc/passwd | grep -Ew ^$Username | cut -d":" -f5`
21 | UserHomeDir=`cat /etc/passwd | grep -Ew ^$Username | cut -d":" -f6`
22 | UserShell=`cat /etc/passwd | grep -Ew ^$Username | cut -d":" -f7`
23 | UserGroups=`groups $Username | awk -F": " '{print $2}'`
24 | PasswordExpiryDate=`chage -l $Username | grep "Password expires" | awk -F": " '{print $2}'`
25 | LastPasswordChangeDate=`chage -l $Username | grep "Last password change" | awk -F": " '{print $2}'`
26 | AccountExpiryDate=`chage -l $Username | grep "Account expires" | awk -F": " '{print $2}'`
27 | HomeDirSize=`du -hs $UserHomeDir | awk '{print $1}'`
28 | clear
29 | echo -e "\e[0m "
30 | echo -e "\e[94m[][][]======================================[][][]"
31 | echo -e "\e[0m "
32 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
33 | echo -e "\e[0m "
34 | printf "%-25s : %5s\n" " Username " "$Username"
35 | printf "%-25s : %5s\n" " Password previous change " "$LastPasswordChangeDate"
36 | printf "%-25s : %5s\n" " Account Date Expired " "$AccountExpiryDate"
37 | echo -e "\e[0m "
38 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
--------------------------------------------------------------------------------
/Files/Menu/user_extend.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # Script by : _Dreyannz_
3 | clear
4 | echo -e "\e[0m "
5 | echo -e "\e[94m[][][]======================================[][][]"
6 | echo -e "\e[0m "
7 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
8 | echo -e "\e[0m "
9 | read -p " Username : " User
10 | egrep "^$User" /etc/passwd >/dev/null
11 | if [ $? -eq 0 ]; then
12 | read -p " Day Extend : " Days
13 | Today=`date +%s`
14 | Days_Detailed=$(( $Days * 86400 ))
15 | Expire_On=$(($Today + $Days_Detailed))
16 | Expiration=$(date -u --date="1970-01-01 $Expire_On sec GMT" +%Y/%m/%d)
17 | Expiration_Display=$(date -u --date="1970-01-01 $Expire_On sec GMT" '+%d %b %Y')
18 | passwd -u $User
19 | usermod -e $Expiration $User
20 | egrep "^$User" /etc/passwd >/dev/null
21 | echo -e "$Pass\n$Pass\n"|passwd $User &> /dev/null
22 | clear
23 | echo -e "\e[0m "
24 | echo -e "\e[94m[][][]======================================[][][]"
25 | echo -e "\e[0m "
26 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
27 | echo -e "\e[0m "
28 | echo -e " Username : $User"
29 | echo -e " Days Added : $Days Days"
30 | echo -e " Expires on : $Expiration_Display"
31 | echo -e "\e[0m "
32 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
33 | else
34 | clear
35 | echo -e "\e[0m "
36 | echo -e "\e[94m[][][]======================================[][][]"
37 | echo -e "\e[0m "
38 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
39 | echo -e "\e[0m "
40 | echo -e "\e[93m Username Doesnt Exist "
41 | echo -e "\e[0m "
42 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
43 |
44 | fi
--------------------------------------------------------------------------------
/Files/Menu/user_list.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # Script by : _Dreyannz_
3 | if [ -f /etc/debian_version ]; then
4 | UIDN=1000
5 | elif [ -f /etc/redhat-release ]; then
6 | UIDN=500
7 | else
8 | UIDN=500
9 | fi
10 | clear
11 | echo -e "\e[0m "
12 | echo -e "\e[94m[][][]======================================[][][]"
13 | echo -e "\e[0m "
14 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
15 | echo -e "\e[0m "
16 | echo -e "\e[93m Username Expiration \e[0m"
17 | echo " "
18 | while read Checklist
19 | do
20 | Spacer=" "
21 | Account="$(echo $Checklist | cut -d: -f1)"
22 | ID="$(echo $Checklist | grep -v nobody | cut -d: -f3)"
23 | Exp="$(chage -l $Account | grep "Account expires" | awk -F": " '{print $2}')"
24 | if [[ $ID -ge $UIDN ]]; then
25 | printf "%-26s : %5s\n" " $Account" "$Exp"
26 | fi
27 | done < /etc/passwd
28 | No_Users="$(awk -F: '$3 >= '$UIDN' && $1 != "nobody" {print $1}' /etc/passwd | wc -l)"
29 | echo -e "\e[0m "
30 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
31 | echo -e "\e[0m "
32 | echo -e "\e[93m Number of Users: "$No_Users
33 | echo -e "\e[0m "
34 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
35 |
--------------------------------------------------------------------------------
/Files/Menu/user_lock.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # Script by : _Dreyannz_
3 | clear
4 | echo -e "\e[0m "
5 | echo -e "\e[94m[][][]======================================[][][]"
6 | echo -e "\e[0m "
7 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
8 | echo -e "\e[0m "
9 | read -p " Username : " User
10 | egrep "^$User" /etc/passwd >/dev/null
11 | if [ $? -eq 0 ]; then
12 | sleep 1
13 | if grep -Fxq "$User" /etc/Locked_List.txt
14 | then
15 | clear
16 | echo -e "\e[0m "
17 | echo -e "\e[94m[][][]======================================[][][]"
18 | echo -e "\e[0m "
19 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
20 | echo -e "\e[0m "
21 | echo -e "\e[91m User Has Been Locked Already "
22 | echo -e "\e[0m "
23 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
24 | exit
25 | else
26 | clear
27 | echo -e "\e[0m "
28 | echo -e "\e[94m[][][]======================================[][][]"
29 | echo -e "\e[0m "
30 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
31 | echo -e "\e[0m "
32 | echo -e "\e[91m User Has Been Locked "
33 | echo -e "\e[91m User Has Been Added To Locked_List "
34 | echo -e "\e[0m "
35 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
36 | echo $User >> /etc/Locked_List.txt
37 | passwd -l $User
38 | fi
39 |
40 | else
41 | clear
42 | echo -e "\e[0m "
43 | echo -e "\e[94m[][][]======================================[][][]"
44 | echo -e "\e[0m "
45 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
46 | echo -e "\e[0m "
47 | echo -e "\e[91m Username Doesnt Exist "
48 | echo -e "\e[0m "
49 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
50 | exit
51 | exit 1
52 | fi
--------------------------------------------------------------------------------
/Files/Menu/user_unlock.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # Script by : _Dreyannz_
3 | clear
4 | echo -e "\e[0m "
5 | echo -e "\e[94m[][][]======================================[][][]"
6 | echo -e "\e[0m "
7 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
8 | echo -e "\e[0m "
9 | read -p " Username : " User
10 | egrep "^$User" /etc/passwd >/dev/null
11 | if [ $? -eq 0 ]; then
12 | sleep 1
13 | if grep -Fxq "$User" /etc/Locked_List.txt
14 | then
15 | clear
16 | echo -e "\e[0m "
17 | echo -e "\e[94m[][][]======================================[][][]"
18 | echo -e "\e[0m "
19 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
20 | echo -e "\e[0m "
21 | echo -e "\e[93m User Has Been Unlocked "
22 | echo -e "\e[93m User Has Been Removed from Locked_List "
23 | echo -e "\e[0m "
24 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
25 | passwd -u $User
26 | sed -i 's/$User//g' /etc/Locked_List.txt
27 |
28 | exit
29 | else
30 | clear
31 | echo -e "\e[0m "
32 | echo -e "\e[94m[][][]======================================[][][]"
33 | echo -e "\e[0m "
34 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
35 | echo -e "\e[0m "
36 | echo -e "\e[93m User Is Not Locked "
37 | echo -e "\e[0m "
38 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
39 | exit
40 | fi
41 |
42 | else
43 | clear
44 | echo -e "\e[0m "
45 | echo -e "\e[94m[][][]======================================[][][]"
46 | echo -e "\e[0m "
47 | echo -e "\e[93m AutoScriptVPS by _Dreyannz_ "
48 | echo -e "\e[0m "
49 | echo -e "\e[91m Username Doesnt Exist "
50 | echo -e "\e[0m "
51 | echo -e "\e[94m[][][]======================================[][][]\e[0m"
52 | exit
53 | exit 1
54 | fi
--------------------------------------------------------------------------------
/Files/Nginx/nginx.conf:
--------------------------------------------------------------------------------
1 | user www-data;
2 |
3 | worker_processes 1;
4 | pid /var/run/nginx.pid;
5 |
6 | events {
7 | multi_accept on;
8 | worker_connections 1024;
9 | }
10 |
11 | http {
12 | gzip on;
13 | gzip_vary on;
14 | gzip_comp_level 5;
15 | gzip_types text/plain application/x-javascript text/xml text/css;
16 |
17 | autoindex on;
18 | sendfile on;
19 | tcp_nopush on;
20 | tcp_nodelay on;
21 | keepalive_timeout 65;
22 | types_hash_max_size 2048;
23 | server_tokens off;
24 | include /etc/nginx/mime.types;
25 | default_type application/octet-stream;
26 | access_log /var/log/nginx/access.log;
27 | error_log /var/log/nginx/error.log;
28 | client_max_body_size 32M;
29 | client_header_buffer_size 8m;
30 | large_client_header_buffers 8 8m;
31 |
32 | fastcgi_buffer_size 8m;
33 | fastcgi_buffers 8 8m;
34 |
35 | fastcgi_read_timeout 600;
36 |
37 | set_real_ip_from 204.93.240.0/24;
38 | set_real_ip_from 204.93.177.0/24;
39 | set_real_ip_from 199.27.128.0/21;
40 | set_real_ip_from 173.245.48.0/20;
41 | set_real_ip_from 103.21.244.0/22;
42 | set_real_ip_from 103.22.200.0/22;
43 | set_real_ip_from 103.31.4.0/22;
44 | set_real_ip_from 141.101.64.0/18;
45 | set_real_ip_from 108.162.192.0/18;
46 | set_real_ip_from 190.93.240.0/20;
47 | set_real_ip_from 188.114.96.0/20;
48 | set_real_ip_from 197.234.240.0/22;
49 | set_real_ip_from 198.41.128.0/17;
50 | real_ip_header CF-Connecting-IP;
51 |
52 | include /etc/nginx/conf.d/*.conf;
53 | }
54 |
--------------------------------------------------------------------------------
/Files/Nginx/vps.conf:
--------------------------------------------------------------------------------
1 | server {
2 | listen 80;
3 | server_name 127.0.0.1 localhost;
4 | access_log /var/log/nginx/vps-access.log;
5 | error_log /var/log/nginx/vps-error.log error;
6 | root /home/vps/public_html;
7 |
8 | location / {
9 | index index.html index.htm index.php;
10 | try_files $uri $uri/ /index.php?$args;
11 | }
12 |
13 | location ~ \.php$ {
14 | include /etc/nginx/fastcgi_params;
15 | fastcgi_pass 127.0.0.1:9000;
16 | fastcgi_index index.php;
17 | fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/Files/OpenVPN/before.rules:
--------------------------------------------------------------------------------
1 | # START OPENVPN RULES
2 | # NAT table rules
3 | *nat
4 | :POSTROUTING ACCEPT [0:0]
5 | # Allow traffic from OpenVPN client to eth0
6 | -A POSTROUTING -s 10.8.0.0/8 -o eth0 -j MASQUERADE
7 | COMMIT
8 | # END OPENVPN RULES
9 |
--------------------------------------------------------------------------------
/Files/OpenVPN/client.ovpn:
--------------------------------------------------------------------------------
1 | #AutoScriptVPS by _Dreyannz_
2 |
3 | client
4 | dev tun
5 | proto tcp
6 | remote xxxxxxxxx 1194
7 | persist-key
8 | persist-tun
9 | dev tun
10 | pull
11 | resolv-retry infinite
12 | nobind
13 | user nobody
14 | group nogroup
15 | comp-lzo
16 | ns-cert-type server
17 | verb 3
18 | mute 2
19 | mute-replay-warnings
20 | auth-user-pass
21 | redirect-gateway def1
22 | script-security 2
23 | route 0.0.0.0 0.0.0.0
24 | route-method exe
25 | route-delay 2
26 | cipher AES-128-CBC
27 | http-proxy xxxxxxxxx 8080
28 | http-proxy-retry
29 | dhcp-option DNS 8.8.8.8
30 | dhcp-option DNS 8.8.4.4
31 | http-proxy-option CUSTOM-HEADER Host m.google.com
32 | http-proxy-option CUSTOM-HEADER X-Online-Host m.google.com
33 |
--------------------------------------------------------------------------------
/Files/OpenVPN/server.conf:
--------------------------------------------------------------------------------
1 | port 1194
2 | proto tcp
3 | dev tun
4 | ca ca.crt
5 | cert server.crt
6 | key server.key
7 | dh dh2048.pem
8 | client-cert-not-required
9 | username-as-common-name
10 | plugin /usr/lib/openvpn/openvpn-plugin-auth-pam.so login
11 | server 192.168.100.0 255.255.255.0
12 | ifconfig-pool-persist ipp.txt
13 | push "redirect-gateway def1 bypass-dhcp"
14 | push "dhcp-option DNS 8.8.8.8"
15 | push "dhcp-option DNS 8.8.4.4"
16 | push "route-method exe"
17 | push "route-delay 2"
18 | duplicate-cn
19 | push "route-method exe"
20 | push "route-delay 2"
21 | keepalive 10 120
22 | comp-lzo
23 | user nobody
24 | group nogroup
25 | persist-key
26 | persist-tun
27 | status openvpn-status.log
28 | log openvpn.log
29 | verb 3
30 | cipher AES-128-CBC
31 |
--------------------------------------------------------------------------------
/Files/Others/ddos-deflate-master.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Dreyannz/AutoScriptVPS/8f3c8fa60687c4e2344284b38bfeb7c39efa5638/Files/Others/ddos-deflate-master.zip
--------------------------------------------------------------------------------
/Files/Others/iptables.up.rules:
--------------------------------------------------------------------------------
1 | *nat
2 | :PREROUTING ACCEPT [0:0]
3 | :OUTPUT ACCEPT [0:0]
4 | :POSTROUTING ACCEPT [0:0]
5 | -A POSTROUTING -j SNAT --to-source xxxxxxxxx
6 | -A POSTROUTING -o eth0 -j MASQUERADE
7 | -A POSTROUTING -s 192.168.100.0/24 -o eth0 -j MASQUERADE
8 | -A POSTROUTING -s 10.1.0.0/24 -o eth0 -j MASQUERADE
9 | COMMIT
10 |
11 | *filter
12 | :INPUT ACCEPT [19406:27313311]
13 | :FORWARD ACCEPT [0:0]
14 | :OUTPUT ACCEPT [9393:434129]
15 | :fail2ban-ssh - [0:0]
16 | -A FORWARD -i eth0 -o ppp0 -m state --state RELATED,ESTABLISHED -j ACCEPT
17 | -A FORWARD -i ppp0 -o eth0 -j ACCEPT
18 | -A INPUT -p tcp -m multiport --dports 22 -j fail2ban-ssh
19 | -A INPUT -p ICMP --icmp-type 8 -j ACCEPT
20 | -A INPUT -p tcp -m tcp --dport 53 -j ACCEPT
21 | -A INPUT -p tcp --dport 22 -m state --state NEW -j ACCEPT
22 | -A INPUT -p tcp --dport 80 -m state --state NEW -j ACCEPT
23 | -A INPUT -p tcp --dport 80 -m state --state NEW -j ACCEPT
24 | -A INPUT -p tcp --dport 8888 -m state --state NEW -j ACCEPT
25 | -A INPUT -p udp --dport 8888 -m state --state NEW -j ACCEPT
26 | -A INPUT -p tcp --dport 142 -m state --state NEW -j ACCEPT
27 | -A INPUT -p tcp --dport 143 -m state --state NEW -j ACCEPT
28 | -A INPUT -p tcp --dport 109 -m state --state NEW -j ACCEPT
29 | -A INPUT -p tcp --dport 110 -m state --state NEW -j ACCEPT
30 | -A INPUT -p tcp --dport 443 -m state --state NEW -j ACCEPT
31 | -A INPUT -p tcp --dport 1194 -m state --state NEW -j ACCEPT
32 | -A INPUT -p udp --dport 1194 -m state --state NEW -j ACCEPT
33 | -A INPUT -p tcp --dport 1732 -m state --state NEW -j ACCEPT
34 | -A INPUT -p udp --dport 1732 -m state --state NEW -j ACCEPT
35 | -A INPUT -p tcp --dport 3128 -m state --state NEW -j ACCEPT
36 | -A INPUT -p udp --dport 3128 -m state --state NEW -j ACCEPT
37 | -A INPUT -p tcp --dport 7300 -m state --state NEW -j ACCEPT
38 | -A INPUT -p udp --dport 7300 -m state --state NEW -j ACCEPT
39 | -A INPUT -p tcp --dport 8000 -m state --state NEW -j ACCEPT
40 | -A INPUT -p udp --dport 8000 -m state --state NEW -j ACCEPT
41 | -A INPUT -p tcp --dport 8080 -m state --state NEW -j ACCEPT
42 | -A INPUT -p udp --dport 8080 -m state --state NEW -j ACCEPT
43 | -A INPUT -p tcp --dport 10000 -m state --state NEW -j ACCEPT
44 | -A fail2ban-ssh -j RETURN
45 | COMMIT
46 |
47 | *raw
48 | :PREROUTING ACCEPT [158575:227800758]
49 | :OUTPUT ACCEPT [46145:2312668]
50 | COMMIT
51 |
52 | *mangle
53 | :PREROUTING ACCEPT [158575:227800758]
54 | :INPUT ACCEPT [158575:227800758]
55 | :FORWARD ACCEPT [0:0]
56 | :OUTPUT ACCEPT [46145:2312668]
57 | :POSTROUTING ACCEPT [46145:2312668]
58 | COMMIT
59 |
--------------------------------------------------------------------------------
/Files/Others/issue.net:
--------------------------------------------------------------------------------
1 |
AutoScriptVPS
2 |
by _Dreyannz_
3 |
4 |
5 |
--------------------------------------------------------------------------------
/Files/Screenshots/1.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Dreyannz/AutoScriptVPS/8f3c8fa60687c4e2344284b38bfeb7c39efa5638/Files/Screenshots/1.JPG
--------------------------------------------------------------------------------
/Files/Screenshots/2.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Dreyannz/AutoScriptVPS/8f3c8fa60687c4e2344284b38bfeb7c39efa5638/Files/Screenshots/2.JPG
--------------------------------------------------------------------------------
/Files/Screenshots/3.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Dreyannz/AutoScriptVPS/8f3c8fa60687c4e2344284b38bfeb7c39efa5638/Files/Screenshots/3.JPG
--------------------------------------------------------------------------------
/Files/Screenshots/4.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Dreyannz/AutoScriptVPS/8f3c8fa60687c4e2344284b38bfeb7c39efa5638/Files/Screenshots/4.JPG
--------------------------------------------------------------------------------
/Files/Source/source.list.debian8:
--------------------------------------------------------------------------------
1 | deb http://security.debian.org/ jessie/updates main contrib non-free
2 | deb-src http://security.debian.org/ jessie/updates main contrib non-free
3 | deb http://http.us.debian.org/debian jessie main contrib non-free
4 | deb http://packages.dotdeb.org jessie all
5 | deb-src http://packages.dotdeb.org jessie all
6 |
--------------------------------------------------------------------------------
/Files/Squid/squid3.conf:
--------------------------------------------------------------------------------
1 | acl localhost src 127.0.0.1/32 ::1
2 | acl to_localhost dst 127.0.0.0/8 0.0.0.0/32 ::1
3 | acl SSL_ports port 443
4 | acl Safe_ports port 80
5 | acl Safe_ports port 21
6 | acl Safe_ports port 443
7 | acl Safe_ports port 70
8 | acl Safe_ports port 210
9 | acl Safe_ports port 1025-65535
10 | acl Safe_ports port 280
11 | acl Safe_ports port 488
12 | acl Safe_ports port 591
13 | acl Safe_ports port 777
14 | acl CONNECT method CONNECT
15 | acl SSH dst xxxxxxxxx-xxxxxxxxx/255.255.255.255
16 | http_access allow SSH
17 | http_access allow manager localhost
18 | http_access deny manager
19 | http_access allow localhost
20 | http_access deny all
21 | http_port 3128
22 | http_port 8000
23 | http_port 8080
24 | coredump_dir /var/spool/squid3
25 | refresh_pattern ^ftp: 1440 20% 10080
26 | refresh_pattern ^gopher: 1440 0% 1440
27 | refresh_pattern -i (/cgi-bin/|\?) 0 0% 0
28 | refresh_pattern . 0 20% 4320
29 | visible_hostname Dreyannz
30 |
--------------------------------------------------------------------------------
/Files/Stunnel/stunnel.conf:
--------------------------------------------------------------------------------
1 | pid = /var/run/stunnel.pid
2 | cert = /etc/stunnel/stunnel.pem
3 | [dropbear]
4 | accept = xxxxxxxxx:442
5 | connect = 127.0.0.1:443
6 |
--------------------------------------------------------------------------------
/Files/Stunnel/stunnel.pem:
--------------------------------------------------------------------------------
1 | -----BEGIN CERTIFICATE-----
2 | MIIDJDCCAo2gAwIBAgIJAMyYZPyzciOgMA0GCSqGSIb3DQEBCwUAMIGqMQswCQYD
3 | VQQGEwJNWTEVMBMGA1UECAwMS3VhbGEgTHVtcHVyMQ8wDQYDVQQHDAZHb21iYWsx
4 | GDAWBgNVBAoMD0FpbWFuIEFtaXIgSW5jLjEcMBoGA1UECwwTVHJpayBUZWxrbyBN
5 | YWxheXNpYTETMBEGA1UEAwwKQWltYW4gQW1pcjEmMCQGCSqGSIb3DQEJARYXYWlt
6 | YW5hbWlyMDI0OEBnbWFpbC5jb20wHhcNMTgwMjIzMTEwMTQwWhcNMjMwODE2MTEw
7 | MTQwWjCBqjELMAkGA1UEBhMCTVkxFTATBgNVBAgMDEt1YWxhIEx1bXB1cjEPMA0G
8 | A1UEBwwGR29tYmFrMRgwFgYDVQQKDA9BaW1hbiBBbWlyIEluYy4xHDAaBgNVBAsM
9 | E1RyaWsgVGVsa28gTWFsYXlzaWExEzARBgNVBAMMCkFpbWFuIEFtaXIxJjAkBgkq
10 | hkiG9w0BCQEWF2FpbWFuYW1pcjAyNDhAZ21haWwuY29tMIGfMA0GCSqGSIb3DQEB
11 | AQUAA4GNADCBiQKBgQDJGc5hWEBQ+Aefi55WxpcDay/C0nZ4mnv2Js8gkQbbkFn+
12 | hfn71NtImHZCVIcs+InyB6L/suM8tX0TU0YX8YjX5iZ0S1NYtbpUAFDLLJyND+85
13 | YggsWo63FpvX+s63gLyKgWYweyFvVpECn1aMAE60l592AAS7MCopCqkNLPft6QID
14 | AQABo1AwTjAdBgNVHQ4EFgQUAtaIAiJmqPVZFXeyV3QeJVqzPN8wHwYDVR0jBBgw
15 | FoAUAtaIAiJmqPVZFXeyV3QeJVqzPN8wDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0B
16 | AQsFAAOBgQB2/kNiDUwo86bcl87tULsEDWtv7ppwkU3XxUO0aPUQnaXOp9ifmV0q
17 | WdJx3lgDIKSaKhxUWgkn1QrOFfRax8wtOfdcF7/sQRrfoXxCaMkiqQJ+AJYi/2C6
18 | Iq3P0ZF3sYYybXL30jSdS5qIoBSsgULkiwVithX1fXpm8RHnnEU94g==
19 | -----END CERTIFICATE-----
20 | -----BEGIN RSA PRIVATE KEY-----
21 | MIICXQIBAAKBgQDJGc5hWEBQ+Aefi55WxpcDay/C0nZ4mnv2Js8gkQbbkFn+hfn7
22 | 1NtImHZCVIcs+InyB6L/suM8tX0TU0YX8YjX5iZ0S1NYtbpUAFDLLJyND+85Yggs
23 | Wo63FpvX+s63gLyKgWYweyFvVpECn1aMAE60l592AAS7MCopCqkNLPft6QIDAQAB
24 | AoGAQhYh9WmMEU/BKZQ3X6r5e50g3/RMDIwwCo9sZ/Zg+4yvlm4u3axwt6Wqz1d5
25 | 6LRwmMIbtc3y0UOPK+ek1D+CyWKuBr7Iff8Db1sELZ1I7ElehIkW1wvD3voZDQu3
26 | Hy9N/SCQv5sP31aOyG6EXkqbFz7ndBejibXZHyxNE2I75dUCQQD64HB81E3OMVXI
27 | cWttHsgwr73aE7fK4KU3KFG6fp1qelShSZQRcwomXMxlN5Gv/P0IKBKqdABrxCTP
28 | DsLSEpcPAkEAzTUkkXG7eQJWkL3h1ymwWjpukUsSHyzOlWjodd8fKEzhIT1PC7Ni
29 | Am1yD2pE8AiqC6X+v9jdXT/QIRGrp4lrhwJBAJkjyeaZHgmAmhGqEl5gzOjTTjvB
30 | j46bBJ8f0Ivb4DFwDRsLNARWydpTCT275wWbk8WX2JUODHe8Go/+PbRIPscCQQDH
31 | KH2OHxh40Bkdrvvhq9c5Kp6mqnozAXSZs1BxHZQKs9qHPQ5bZ8SGYJwjc9rmLzKB
32 | zZ/Zp+rnlogzoAe9uPQ/AkAYD6RkgF2DIJ7YXsnTC97z377AZqbh0PbcMSMzyYA/
33 | 3zd7B+vHChG80JN0brZb8ikFBhcqCsG+HkwBjEFn5XRR
34 | -----END RSA PRIVATE KEY-----
35 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | AutoScriptVPS
3 |
4 | AutoScriptVPS is made by _Dreyannz_ to minimize the time consumed and user involvement in setting up your VPS
5 | Supported Linux Distribution
6 |
7 |
8 |
9 |
10 | Services
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 | Commands
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 | Installation
27 |
28 |
29 | wget -O AutoScriptVPS https://git.io/fA44X
30 |
31 |
32 | chmod +x AutoScriptVPS
33 |
34 |
35 | ./AutoScriptVPS
36 |
37 |
38 | Screenshots
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
--------------------------------------------------------------------------------
/TestFolder/Test.txt:
--------------------------------------------------------------------------------
1 | test
2 |
--------------------------------------------------------------------------------