-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdockerauto.py
More file actions
844 lines (774 loc) · 39.6 KB
/
dockerauto.py
File metadata and controls
844 lines (774 loc) · 39.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
#!/usr/bin/env python3
#
# DockerAuto version 2.1 (20_02_2026)
# Written by Andy Tyler (@ticarpi)
# Please use responsibly...
# Software URL: https://github.com/ticarpi/dockerauto
# Web: https://www.ticarpi.com
# Twitter: @ticarpi
dockerautovers = "2.1"
import os
import socket
import re
from urllib.request import urlretrieve
import json
import base64
import argparse
from datetime import datetime
import shutil
from zipfile import ZipFile
basepath = os.path.expanduser('~/.dockerauto/')
configfile = basepath+'dockerlist.json'
tokenfile = basepath+'tokens.json'
tmpdir = basepath+'tmp_da/'
assigned_ports = []
def run_update(dockerlist_json, updateitem):
if dockerlist_json['dockeritems'][updateitem][3][0] != 'DockerHub':
run_build(dockerlist_json, updateitem)
else:
try:
print("\n[+] Running docker update command for "+updateitem)
run_cmd('docker pull '+dockerlist_json['dockeritems'][updateitem][3][1])
#os.system(cmd)
except Exception as e:
print(f'[!] Error: {e}')
print('[-] The specified tool ('+updateitem+') could not be updated')
def run_build(dockerlist_json, dockeritem):
try:
print('[+] Prepping temp build directory')
shutil.rmtree(tmpdir)
except Exception as e:
print(f'[!] Error: {e}')
print('[+] Creating temp build directory')
if dockerlist_json['dockeritems'][dockeritem][3][0] == 'GitHub':
split = dockerlist_json['dockeritems'][dockeritem][3][2].split("/")
gitdir = split[-1]
builddir = tmpdir+gitdir
pwd = os.getcwd()
os.mkdir(tmpdir)
os.chdir(tmpdir)
os.system('git clone '+dockerlist_json['dockeritems'][dockeritem][3][2])
os.chdir(pwd)
elif dockerlist_json['dockeritems'][dockeritem][3][0] == 'ZipUrl':
try:
builddir = tmpdir+dockerlist_json['dockeritems'][dockeritem][3][3]
except Exception as e:
print(f'[!] Error: {e}')
builddir = tmpdir
os.mkdir(tmpdir)
pwd = os.getcwd()
print('[+] Downloading '+dockerlist_json['dockeritems'][dockeritem][3][2])
downloadfile(dockerlist_json['dockeritems'][dockeritem][3][2], tmpdir+'temp.zip')
with ZipFile(tmpdir+'temp.zip', 'r') as zObject:
print('[+] Extracting '+tmpdir+'temp.zip to '+tmpdir)
zObject.extractall(path=tmpdir)
else:
builddir = tmpdir
os.mkdir(builddir)
pwd = os.getcwd()
for file in dockerlist_json['dockeritems'][dockeritem][4].keys():
filename = builddir.rstrip("/")+'/'+file
print(' [*] Building: '+filename)
b642file(dockerlist_json['dockeritems'][dockeritem][4][file], filename)
os.chdir(builddir)
run_cmd('docker build -t '+dockeritem+' .')
os.chdir(pwd)
shutil.rmtree(builddir)
print('[+] Cleaning up temp build directory')
return True
def check_port(port):
"""Check if a port is available"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
sock.bind(('', port))
sock.close()
return True
except PermissionError:
# Port requires elevated privileges
return 'permission'
except OSError:
# Port is in use
return False
def get_alternative_port(original_port, assigned_ports, sudo_granted=False):
result = check_port(original_port)
if result is True and original_port not in assigned_ports:
assigned_ports.append(original_port)
return original_port
elif result == 'permission':
if sudo_granted:
# Already have sudo, no need to prompt again
assigned_ports.append(original_port)
return original_port
else:
print(f'[!] Port {original_port} requires elevated privileges')
use_sudo = input(f'[?] Attempt with sudo? (y/N): ')
if use_sudo.lower() == 'y':
assigned_ports.append(original_port)
return original_port
else:
print(f'[!] Port {original_port} is already in use')
while True:
new_port = input(f'[?] Enter alternative port for {original_port} (press Enter for auto): ')
if new_port == '':
for port in range(10000, 65535):
if check_port(port) is True and port not in assigned_ports:
print(f'[+] Using auto-selected port: {port}')
assigned_ports.append(port)
return port
else:
try:
new_port = int(new_port)
if new_port < 1 or new_port > 65535:
print('[!] Port must be between 1-65535')
continue
result = check_port(new_port)
if result is True and new_port not in assigned_ports:
assigned_ports.append(new_port)
return new_port
elif result == 'permission' and sudo_granted:
assigned_ports.append(new_port)
return new_port
elif new_port in assigned_ports:
print(f'[!] Port {new_port} already assigned in this command')
else:
print(f'[!] Port {new_port} is in use, try another')
except ValueError:
print('[!] Please enter a valid port number')
def setuptokens():
with open(configfile, "r") as dockerlist:
dockerlist_json = json.load(dockerlist)
checktokenfile()
with open(tokenfile, 'r') as f:
tokens = json.load(f)
items_with_tokens = []
items_needing_tokens = []
for dockeritem in dockerlist_json['dockeritems'].keys():
cmd = dockerlist_json['dockeritems'][dockeritem][1]
if '[TOKEN_HERE]' in cmd:
existing_token = tokens['tokenitems'].get(dockeritem, '')
if existing_token:
items_with_tokens.append(dockeritem)
else:
items_needing_tokens.append(dockeritem)
if not items_needing_tokens and not items_with_tokens:
print('[+] No items use [TOKEN_HERE] in their commands')
return
if items_needing_tokens:
print(f'[+] Found {len(items_needing_tokens)} items requiring tokens:')
for item in items_needing_tokens:
print(f' [*] {item}')
for item in items_needing_tokens:
addtoken(item)
if items_with_tokens:
print(f'\n[+] Found {len(items_with_tokens)} items with existing tokens:')
for item in items_with_tokens:
current_token = tokens['tokenitems'][item]
# Show partial token for security (first 8 chars + ***)
display_token = current_token[:8] + '***' if len(current_token) > 8 else current_token
print(f' [*] {item}: {display_token}')
replace = input(f'[?] Replace token for {item}? (y/N): ')
if replace.lower() == 'y':
addtoken(item)
print('\n[+] Token setup complete!')
def checktokenfile():
if not os.path.exists(tokenfile):
os.makedirs(os.path.dirname(tokenfile), exist_ok=True)
with open(tokenfile, 'w') as f:
json.dump({"tokenitems": {}}, f, indent=2)
def gettoken(dockeritem):
checktokenfile()
with open(tokenfile, 'r') as f:
tokens = json.load(f)
token = tokens['tokenitems'].get(dockeritem, None)
if not token:
print(f'[!] No token found for {dockeritem}')
addtoken(dockeritem)
with open(tokenfile, 'r') as f:
tokens = json.load(f)
token = tokens['tokenitems'].get(dockeritem)
return token
def addtoken(dockeritem):
with open(tokenfile, 'r') as f:
tokens = json.load(f)
token = input(f'[*] Enter token for {dockeritem}: ')
tokens['tokenitems'][dockeritem] = token
with open(tokenfile, 'w') as f:
json.dump(tokens, f, indent=2)
print(f'[+] Token saved for {dockeritem}')
def b642file(fileb64, filename):
with open(filename, 'w') as newfile:
newfile.write(base64.b64decode(fileb64.encode('ascii')).decode('ascii'))
def mode_update(dockeritem):
with open(configfile, "r") as dockerlist:
dockerlist_json = json.load(dockerlist)
if dockeritem == 'ALL' or dockeritem == 'all':
print("[+] Updating all of the following:")
for key in dockerlist_json['dockeritems'].keys():
print(" [*] "+key)
update = input('\n[!] Are you sure you want to update all Docker images? (y/N)')
if update=='y' or update=='Y':
for key in dockerlist_json['dockeritems'].keys():
run_update(dockerlist_json, key)
dockerlist_json['dockeritems'][key][5] = timestamp = int(datetime.timestamp(datetime.now()))
with open(configfile, "w") as dockerdump:
dockerdump.write(json.dumps(dockerlist_json))
else:
print('Quitting...')
exit(1)
else:
print('[+] Updating '+dockeritem)
run_update(dockerlist_json, dockeritem)
dockerlist_json['dockeritems'][dockeritem][5] = timestamp = int(datetime.timestamp(datetime.now()))
with open(configfile, "w") as dockerdump:
dockerdump.write(json.dumps(dockerlist_json))
def run_remove(dockerlist_json, removeitem):
print("\n[+] Removing config entry for "+removeitem)
del dockerlist_json['dockeritems'][removeitem]
with open(configfile, "w") as dockerdump:
dockerdump.write(json.dumps(dockerlist_json))
print('\n[+] '+removeitem+' has been removed from the config')
def mode_remove(dockeritem):
with open(configfile, "r") as dockerlist:
dockerlist_json = json.load(dockerlist)
if dockeritem in dockerlist_json['dockeritems'].keys():
print('[+] Removing '+dockeritem+' from the config:')
remove = input('\n[!] Are you sure you want to remove this item? (y/N)')
if remove=='y' or remove=='Y':
run_remove(dockerlist_json, dockeritem)
else:
print('Quitting...')
exit(1)
else:
print("The specified tool ("+dockeritem+") is not in the config file. Try one of the following:")
for key in dockerlist_json['dockeritems'].keys():
print(" [*] "+key)
def mode_run(dockeritem, args, alt_port=None):
with open(configfile, "r") as dockerlist:
dockerlist_json = json.load(dockerlist)
cmd = dockerlist_json['dockeritems'][dockeritem][1]
name_match = re.search(r'--name\s+(\S+)', cmd)
if name_match:
container_name = name_match.group(1)
check_cmd = f'docker ps -q -f name={container_name}'
if powershellcmd:
check_cmd = powershellcmd + ' -c \'' + check_cmd + '\''
result = os.popen(check_cmd).read().strip()
if result:
print(f'[!] Container {container_name} is already running')
stop = input('[?] Stop it first? (y/N): ')
if stop.lower() == 'y':
mode_stop(dockeritem)
else:
print('[-] Cannot start - container already running')
return
try:
imagelist = checkimage()
if dockeritem in imagelist or dockerlist_json['dockeritems'][dockeritem][3][0] == 'DockerHub':
print("[+] Running docker command for "+dockeritem)
cmd = dockerlist_json['dockeritems'][dockeritem][1]
if ' --rm ' in cmd:
if '[TOKEN_HERE]' in cmd:
token = gettoken(dockeritem)
if token:
cmd = cmd.replace('[TOKEN_HERE]', token)
else:
print('[!] No token available, cannot run command')
return
run_cmd(cmd+' '+args, imagename=dockeritem, alt_port=alt_port)
else:
cmd = 'docker ps -a --format json'
if powershellcmd:
cmd = powershellcmd+' -c \''+cmd+'\''
loaded = os.popen(cmd).readlines()
loadlist = []
for container in loaded:
img = json.loads(container)
loadlist.append(img['Names'])
if dockeritem in loadlist:
print('[*] Detected an existing named DockerAuto container - restarting...')
run_cmd('docker start '+dockeritem+' -i')
else:
print('[-] The image has not yet been created. Run `dockerauto update '+dockeritem+'` to create the docker image')
except Exception as e:
print(f"[DEBUG] Error occurred: {type(e).__name__}: {e}")
print("The specified tool ("+dockeritem+") could not be run. Try one of the following:")
for key in dockerlist_json['dockeritems'].keys():
print(" [*] "+key)
def unload_image(dockeritem, dockerlist_json):
try:
run_cmd('docker image rm '+dockerlist_json['dockeritems'][dockeritem][3][1])
except Exception as e:
print(f'[!] Error: {e}')
print("[!] ERROR processing the specified tool ("+dockeritem+").")
def ensure_sudo():
"""Get sudo access once, keep it alive for subsequent calls"""
import subprocess
print('[!] Privileged ports detected - sudo required')
# -v validates/refreshes sudo timestamp
result = subprocess.run(['sudo', '-v'], capture_output=False)
if result.returncode == 0:
print('[+] sudo access granted')
return True
else:
print('[-] sudo access failed')
return False
def run_cmd(cmd, imagename=None, alt_port=None):
assigned_ports = []
port_pattern = r'-p\s+(\d+):'
matches = re.findall(port_pattern, cmd)
needs_sudo = False
sudo_granted = False
# Check all ports first before prompting for sudo
privileged_ports = [int(p) for p in matches if int(p) < 1024]
if privileged_ports:
sudo_granted = ensure_sudo() # Ask once for all privileged ports
if alt_port and matches:
original_port = int(matches[0])
cmd = cmd.replace(f'-p {original_port}:', f'-p {alt_port}:', 1)
print(f'[+] Using manually specified port {alt_port}')
assigned_ports.append(alt_port)
if alt_port < 1024:
needs_sudo = True
else:
for external_port in matches:
port_num = int(external_port)
new_port = get_alternative_port(port_num, assigned_ports, sudo_granted)
if new_port != port_num:
cmd = cmd.replace(f'-p {external_port}:', f'-p {new_port}:')
print(f'[+] Updated command to use port {new_port}')
if new_port < 1024:
needs_sudo = True
assigned_ports.append(new_port)
# Auto-inject --name if missing
if '--name' not in cmd and imagename:
# Find position after 'docker run' and insert --name
docker_run_match = re.search(r'docker\s+run\s+', cmd)
if docker_run_match:
insert_pos = docker_run_match.end()
cmd = cmd[:insert_pos] + f'--name {imagename} ' + cmd[insert_pos:]
print(f'[+] Auto-added container name: {imagename}')
if '[TOKEN_HERE]' in cmd:
if imagename is None:
print('[!] Error: Token placeholder found but no imagename provided')
return
token = gettoken(imagename)
if token:
cmd = cmd.replace('[TOKEN_HERE]', token)
else:
print('[!] No token available, cannot run command')
return
if powershellcmd:
cmd = powershellcmd + ' -c \'' + cmd + '\''
elif needs_sudo:
if not sudo_granted:
sudo_granted = ensure_sudo()
if sudo_granted:
cmd = 'sudo ' + cmd
else:
print('[-] Cannot bind to privileged port without sudo')
return
#print('[*] Running: '+cmd+'\n')
os.system(cmd)
# def run_cmd(cmd):
# port_pattern = r'-p\s+(\d+):'
# matches = re.findall(port_pattern, cmd)
# for external_port in matches:
# port_num = int(external_port)
# new_port = get_alternative_port(port_num, assigned_ports)
# if new_port != port_num:
# cmd = cmd.replace(f'-p {external_port}:', f'-p {new_port}:')
# print(f'[+] Updated command to use port {new_port}')
# if '[TOKEN_HERE]' in cmd:
# token = gettoken(imagename)
# if token:
# cmd = cmd.replace('[TOKEN_HERE]', token)
# else:
# print('[!] No token available, cannot run command')
# return
# if powershellcmd:
# cmd = powershellcmd+' -c \''+cmd+'\''
# os.system(cmd)
def mode_shell(dockeritem):
with open(configfile, "r") as dockerlist:
dockerlist_json = json.load(dockerlist)
if dockeritem in dockerlist_json['dockeritems']:
print('[+] Creating a /bin/sh shell on the DockerAuto image ('+dockerlist_json['dockeritems'][dockeritem][3][1]+')\n [*] Type exit to close the shell\n [*] If the image has /bin/bash you can run that to upgrade your shell\n')
run_cmd('docker run -it --rm --name shell_'+dockeritem+' --entrypoint=/bin/sh '+dockerlist_json['dockeritems'][dockeritem][3][1])
def mode_unload(dockeritem):
with open(configfile, "r") as dockerlist:
dockerlist_json = json.load(dockerlist)
if dockeritem == 'ALL' or dockeritem == 'all':
print("[+] Unloading all of the following Docker images:")
for key in dockerlist_json['dockeritems'].keys():
print(" [*] "+key+' ('+dockerlist_json['dockeritems'][key][3][1]+')')
update = input('\n[!] Are you sure you want to unload all Docker images? (y/N)')
if update=='y' or update=='Y':
for key in dockerlist_json['dockeritems'].keys():
unload_image(key, dockerlist_json)
else:
print('Quitting...')
exit(1)
if dockeritem in dockerlist_json['dockeritems']:
unload_image(dockeritem, dockerlist_json)
elif dockeritem != 'ALL' and dockeritem != 'all':
print("The specified tool ("+dockeritem+") is not in the config file. Try one of the following:")
for key in dockerlist_json['dockeritems'].keys():
print(" [*] "+key)
def file2b64(inputfile, filename):
b64obj = {}
with open(inputfile, 'r') as thisfile:
b64obj[filename] = base64.b64encode(thisfile.read().encode('ascii')).decode('ascii')
return b64obj
def mode_add(dockeritem, dockerfile, file, configfile, dockercomposefile):
dockeritem.replace(' ', '_')
with open(configfile, "r") as dockerlist:
dockerlist_json = json.load(dockerlist)
if dockeritem in dockerlist_json['dockeritems']:
print('[-] An entry already exists for '+dockeritem)
exit(1)
print('\n[+] Creating entry for new DockerAuto item: '+dockeritem)
newitem = ["","","",[],"","",""]
newitem[5] = ''
newitem[0] = input('\n[*] Please enter a short description of the image\n')
newitem[4] = {}
if dockerfile or dockercomposefile:
if file:
for filename in file:
split = filename.split("/")
filename_split = split[-1]
print('[+] Adding: '+filename+' contents to build info')
newitem[4].update(file2b64(filename, filename_split))
if dockerfile:
newitem[4].update(file2b64(dockerfile, 'Dockerfile'))
print('[+] Adding: '+dockerfile+' as the Dockerfile for building the '+dockeritem+' base image')
else:
newitem[4].update(file2b64(dockercomposefile, 'docker-compose.yaml'))
print('[+] Adding: '+dockercomposefile+' as the docker-compose.yaml file for building the '+dockeritem+' multi container image')
option = input('[*] Select which category best fits your new DockerAuto item:\n [1] Tool (for running a single application)\n [2] Service (For serving or receiving files, or hosting data etc.)\n [3] Environment (For exploring filesystems and running a variety of tooling from a base image)\n')
if option == '1':
newitem[6] = "tool"
elif option == '2':
newitem[6] = "service"
elif option == '3':
newitem[6] = "environment"
else:
print('[-] Not a valid option. Quitting...')
exit(1)
subcat = input('[*] Enter optional subcategory (e.g., web, infra, db) or press Enter to skip:\n')
if subcat.strip():
newitem[6] = newitem[6] + '>' + subcat.strip()
option = input('[*] Select which method you want to use to generate your Docker content:\n [1] Clone a GitHub repo\n [2] Download a zip\n [3] No codebase to import\n')
if option == '1':
repourl = 'https://www.github.com/'+input('\n[*] Please enter the "user/name" of the GitHub repo for cloning (e.g. ticarpi/jwt_tool)\n')
newitem[3] = ['GitHub', dockeritem, repourl]
elif option == '2':
zipurl = input('\n [*] Please enter the URL of the zipfile you wish to download\n')
zipdir = input('\n [*] Please enter a directory name that the files are within in the zip file (or leave blank if no zip subdirectory)\n')
newitem[3] = ['ZipUrl', dockeritem, zipurl, zipdir]
elif option == '3':
if dockerfile:
newitem[3] = ['Dockerfile', dockeritem]
else:
newitem[3] = ['Docker-Compose', dockeritem]
else:
print('[-] Not a valid option. Quitting...')
exit(1)
else:
option = input('[*] Select which category best fits your new DockerAuto item:\n [1] Tool (for running a single application)\n [2] Service (For serving or receiving files, or hosting data etc.)\n [3] Environment (For exploring filesystems and running a variety of tooling from a base image)\n')
if option == '1':
newitem[6] = "tool"
elif option == '2':
newitem[6] = "service"
elif option == '3':
newitem[6] = "environment"
else:
print('[-] Not a valid option. Quitting...')
exit(1)
subcat = input('[*] Enter optional subcategory (e.g., web, infra, db) or press Enter to skip:\n')
if subcat.strip():
newitem[6] = newitem[6] + '>' + subcat.strip()
option = input('[*] Select which method you want to use to generate your Docker content:\n [1] Clone a GitHub repo\n [2] Download a zip\n [3] Pull from DockerHub\n')
if option == '1':
repourl = 'https://www.github.com/'+input('\n[*] Please enter the "user/name" of the GitHub repo for cloning (e.g. ticarpi/jwt_tool)\n')
newitem[3] = ['GitHub', dockeritem, repourl]
elif option == '2':
zipurl = input('\n [*] Please enter the URL of the zipfile you wish to download\n')
zipdir = input('\n [*] Please enter a directory name that the files are within in the zip file (or leave blank if no zip subdirectory)\n')
newitem[3] = ['ZipUrl', dockeritem, zipurl, zipdir]
elif option == '3':
newitem[3] = ['DockerHub', input('\n[*] Please enter the DockerHub repo (e.g. ticarpi/jwt_tool)\n')]
else:
print('[-] Not a valid option. Quitting...')
exit(1)
newitem[1] = input('\n[*] Please enter the base command used to run this container.\ne.g. docker run -it --network \"host\" --rm -v \"${PWD}:/tmp\" -v \"${HOME}/.jwt_tool:/root/.jwt_tool\" ticarpi/jwt_tool\n Include the following:\n [*] volume mapping "-v"\n [*] port mapping "-p"\n [*] private tokens/secrets (will be prompted later) "[TOKEN_HERE]"\n [*] environment variables "-e"\n [*] Remove instruction "--rm"\n [*] only use "double quotes", not \'single quotes\'\n [*] and make sure the image referenced is: '+newitem[3][1]+'\n')
newitem[2] = input('\n[*] Please enter any useful notes for running the container, separating each note with a semicolon. e.g. "-h; PWD mapped to /tmp"\n')
dockerlist_json['dockeritems'][dockeritem] = newitem
with open(configfile, "w") as dockerdump:
dockerdump.write(json.dumps(dockerlist_json))
print('\n[+] new item ('+dockeritem+') has been added to the config')
def mode_info(dockeritem):
with open(configfile, "r") as dockerlist:
dockerlist_json = json.load(dockerlist)
if dockeritem in dockerlist_json['dockeritems']:
if dockerlist_json['dockeritems'][dockeritem][5] == '':
updatetime = 'NEVER'
else:
updatetime = str(datetime.fromtimestamp(dockerlist_json['dockeritems'][dockeritem][5]))
if dockerlist_json['dockeritems'][dockeritem][4] == {}:
genfiles = ['None']
else:
genfiles = dockerlist_json['dockeritems'][dockeritem][4].keys()
print("[+] Info for: "+dockeritem+" (Last updated: "+updatetime+")")
print(" [*] Description: "+dockerlist_json['dockeritems'][dockeritem][0])
print(" [*] Usage Notes:\n [*] "+dockerlist_json['dockeritems'][dockeritem][2].replace(';','\n [*]'))
print(" [*] Command: "+dockerlist_json['dockeritems'][dockeritem][1])
print(" [*] Image Source: "+str(dockerlist_json['dockeritems'][dockeritem][3]))
print(" [*] Dockerfile Generation Script Files:")
for file in genfiles:
print(" [*] "+file)
print(" [*] Category: "+dockerlist_json['dockeritems'][dockeritem][6].capitalize())
else:
print("The specified tool ("+dockeritem+") is not in the config file. Try one of the following:")
for key in dockerlist_json['dockeritems'].keys():
print(" [*] "+key)
def mode_list():
with open(configfile, "r") as dockerlist:
dockerlist_json = json.load(dockerlist)
imagelist = checkimage()
print('[+] Images in config:')
# Build hierarchical structure
categories = {}
for key in dockerlist_json['dockeritems'].keys():
cat_full = dockerlist_json['dockeritems'][key][6]
# Parse category>subcategory
if '>' in cat_full:
cat, subcat = cat_full.split('>', 1)
else:
cat, subcat = cat_full, None
if cat not in categories:
categories[cat] = {}
if subcat not in categories[cat]:
categories[cat][subcat] = []
categories[cat][subcat].append(key)
# Display hierarchically
for cat in ['tool', 'service', 'environment']:
if cat not in categories:
continue
print(' [*] '+cat.capitalize()+'s')
for subcat in sorted(categories[cat].keys()):
if subcat:
print(' [*] '+subcat.capitalize())
indent = ' '
else:
indent = ' '
for key in sorted(categories[cat][subcat]):
installed = ' - run \'update\' to build image'
imgname = dockerlist_json['dockeritems'][key][3][1]
if imgname in imagelist:
installed = ' - IMAGE INSTALLED ('+imgname+')'
print(indent+"[*] "+key+installed)
def saveconfig(sourcefile, destfile):
print('\n[+] Saving config\nfrom: '+sourcefile+'\nto: '+destfile+'\n')
try:
shutil.copy2(sourcefile, destfile)
except Exception as e:
print(f'[!] Error: {e}')
print('Copy failed, check permissions on source and destination files:\nSource:'+sourcefile+'\nDestination: '+destfile)
def downloadfile(URL, filename):
urlretrieve(URL, filename)
def checkimage():
cmd = 'docker images --format "{{json .}}"'
if powershellcmd:
cmd = powershellcmd+' -c \''+cmd+'\''
images = os.popen(cmd).readlines()
imagelist = []
for image in images:
try:
img = json.loads(image)
imagelist.append(img['Repository'])
except json.JSONDecodeError:
continue # Skip invalid lines
return imagelist
def mode_export():
saveconfig(configfile, os.getcwd()+'/EXPORT.dockerlist.json')
def mode_install(config):
if os.path.exists(basepath):
overwrite = input('[!] Installing a new DockerAuto config will remove previous configs and some cached docker data.\nDo you want to continue? (y/N)')
if overwrite=='y' or overwrite=='Y':
jsonfile=os.getcwd()+'/'+config
saveconfig(jsonfile, configfile)
else:
print('Quitting...')
exit(1)
if shutil.which('dockerauto') is None:
os.system('sudo ln -s '+os.getcwd()+'/dockerauto.py /usr/bin/dockerauto')
os.chmod(os.getcwd()+'/dockerauto.py', 0o775)
print('[+] DockerAuto now installed via simlink to /usr/bin/dockerauto, you can now run with:\n$ dockerauto [args]')
try:
print('[+] Prepping base directory at: '+basepath)
shutil.rmtree(basepath)
except Exception as e:
print(f'[!] Error: {e}')
print('[+] Building base directory at: '+basepath)
os.mkdir(basepath)
if config.startswith('http://') or config.startswith('https://'):
downloadfile(config, 'temp.json')
config = 'temp.json'
if not os.path.exists(config):
print('[!] Cannot find '+config+' check the filepath')
exit(1)
#jsonfile=os.getcwd()+'/'+config
saveconfig(config, configfile)
def mode_stop(dockeritem=None):
"""Stop a running dockerauto container, or show all running if no argument"""
with open(configfile, "r") as dockerlist:
dockerlist_json = json.load(dockerlist)
# If no dockeritem specified, check all containers
if dockeritem is None:
running_containers = []
for item in dockerlist_json['dockeritems'].keys():
cmd = dockerlist_json['dockeritems'][item][1]
name_match = re.search(r'--name\s+(\S+)', cmd)
if name_match:
container_name = name_match.group(1)
else:
container_name = item
# Check if container is running
check_cmd = f'docker ps -q -f name={container_name}'
if powershellcmd:
check_cmd = powershellcmd + ' -c \'' + check_cmd + '\''
result = os.popen(check_cmd).read().strip()
if result:
running_containers.append((item, container_name))
if not running_containers:
print('[+] No DockerAuto containers currently running')
return
print('[+] Running DockerAuto containers:')
for item, container_name in running_containers:
print(f' [*] {item} (container: {container_name})')
stop_all = input('\n[?] Stop all running containers? (y/N): ')
if stop_all.lower() == 'y':
for item, container_name in running_containers:
print(f'[+] Stopping {item}...')
stop_cmd = f'docker stop {container_name}'
run_cmd(stop_cmd)
print('[+] All DockerAuto containers stopped')
return
# Stop specific container
if dockeritem not in dockerlist_json['dockeritems']:
print(f"[-] {dockeritem} not found in config")
return
# Extract container name from docker command
cmd = dockerlist_json['dockeritems'][dockeritem][1]
name_match = re.search(r'--name\s+(\S+)', cmd)
if name_match:
container_name = name_match.group(1)
else:
container_name = dockeritem
# Check if container is running
check_cmd = f'docker ps -q -f name={container_name}'
if powershellcmd:
check_cmd = powershellcmd + ' -c \'' + check_cmd + '\''
result = os.popen(check_cmd).read().strip()
if result:
print(f'[+] Stopping {dockeritem} (container: {container_name})...')
stop_cmd = f'docker stop {container_name}'
run_cmd(stop_cmd)
print(f'[+] {dockeritem} stopped and removed')
else:
print(f'[-] {dockeritem} is not currently running')
def checkwsl():
powershellcmd = ''
for path in ['/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe', '/mnt/c/Windows/SysWOW64/WindowsPowerShell/v1.0/powershell.exe', 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe', 'C:\\Windows\\SysWOW64\\WindowsPowerShell\\v1.0\\powershell.exe']:
if os.path.exists(path):
powershellcmd = path
break
if powershellcmd:
print(' [*] PowerShell path: '+powershellcmd+'\n')
else:
print("[-] PowerShell couldn't be found, trying with WSL2 Docker instead.\n")
return powershellcmd
def checkdeps():
errors=0
if shutil.which('docker') is None and not powershellcmd:
print('[-] Docker NOT installed.\nThis is a requirement for a tool that runs Docker containers.\n\nOn Kali and other Linux distros that use the APT package manager you can install this and configure it by running the following command:\nsudo apt update && sudo apt install docker.io -y && sudo usermod -aG docker $USER\n')
errors+=1
if shutil.which('git') is None:
print('[-] Git NOT installed.\nThis is a requirement in order to update and pull Git repos to build new Docker containers.\n\nOn Kali and other Linux distros that use the APT package manager you can install this by running the following command:\nsudo apt update && sudo apt install git -y\n')
errors+=1
if errors>0:
exit(1)
logo="\n██████ ██████ ██████ ██ ██ ███████ ██████ █████ ██ ██ ████████ ██████ \n"
logo+="██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ \n"
logo+="██ ██ ██ ██ ██ █████ █████ ██████ ███████ ██ ██ ██ ██ ██ \n"
logo+="██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ \n"
logo+="██████ ██████ ██████ ██ ██ ███████ ██ ██ ██ ██ ██████ ██ ██████ \n"
logo+="\t@ticarpi\t\t\t\t\t\tversion "+dockerautovers+"\n"
if __name__ == '__main__':
print(logo)
powershellcmd = checkwsl()
checkdeps()
parser = argparse.ArgumentParser(epilog="OK, bye", formatter_class=argparse.RawTextHelpFormatter)
subparsers = parser.add_subparsers(dest='mode',required=True)
parser_install = subparsers.add_parser('install', help="Install a new config file (and set up symlink to run DockerAuto from any directory)")
parser_run = subparsers.add_parser('run', help="Run Docker commands for DockerAuto items")
parser_list = subparsers.add_parser('list', help="Show all DockerAuto items in the config (and install status)")
parser_info = subparsers.add_parser('info', help="Look up info about each DockerAuto item in the config")
parser_shell = subparsers.add_parser('shell', help="Drop into the specified DockerAuto image in a shell")
parser_add = subparsers.add_parser('add', help="Add new DockerAuto items to the config manually")
parser_remove = subparsers.add_parser('remove', help="Remove DockerAuto items from the config manually")
parser_update = subparsers.add_parser('update', help="Pull any new Docker image updates for DockerAuto items in the config - or for everything (update ALL)")
parser_unload = subparsers.add_parser('unload', help="Delete stored Docker images for DockerAuto items in the config - or for everything (unload ALL)")
parser_export = subparsers.add_parser('export', help="Export the config file")
parser_setuptokens = subparsers.add_parser('setuptokens', help="Set up tokens for all items requiring them in config (included as \"[TOKEN_HERE]\")")
parser_stop = subparsers.add_parser('stop', help="Stop a running DockerAuto container")
parser_stop.add_argument('dockeritem', type=str, nargs='?', action="store", help="Stop the selected DockerAuto container (or all if not specified)")
parser_add.add_argument('dockeritem', type=str, action="store", help="A new DockerAuto item", default='dockerauto')
parser_shell.add_argument('dockeritem', type=str, action="store", help="The DockerAuto image to connect to", default='dockerauto')
parser_add.add_argument('-d', '--dockerfile', action="store", help="Dockerfile for the new DockerAuto item")
parser_add.add_argument('-dc', '--dockercomposefile', action="store", help="docker-compose YAML file for running a collection of services")
parser_add.add_argument('-f', '--file', action="append", help="Additional files, such as configs/certs, for the new DockerAuto item")
parser_run.add_argument('dockeritem', type=str, action="store", help="Run the selected DockerAuto items", default='dockerauto')
parser_update.add_argument('dockeritem', type=str, action="store", help="Update the selected DockerAuto items (or 'update ALL' to update all Docker images)", default='ALL')
parser_unload.add_argument('dockeritem', type=str, action="store", help="Unload the selected DockerAuto item to the config", default='ALL')
parser_remove.add_argument('dockeritem', type=str, action="store", help="Remove the selected DockerAuto item from the config", default='ALL')
#parser_run.add_argument('arglist', help="Arguments to use in the docker command (surround in 'single quotes' e.g. '-u https://example.com -X GET')", nargs='*')
parser_run.add_argument('arglist', help="Arguments to use in the docker command", nargs=argparse.REMAINDER)
parser_info.add_argument('dockeritem', type=str, action="store", help="Info about selected DockerAuto items", default='dockerauto')
parser_install.add_argument("-c", "--config", action="store", help="URL or local filepath to grab your custom DockerAuto config from", required=False, default='example.dockerlist.json')
args = parser.parse_args()
if not os.path.exists(configfile) and args.mode != 'install':
print('Install config before you can use any other DockerAuto functionality:\n$ python3 dockerauto.py install -j [Path/URL to dockerlist.json]')
exit(1)
if args.mode == 'install':
mode_install(args.config)
elif args.mode == 'info':
mode_info(args.dockeritem)
elif args.mode == 'update':
mode_update(args.dockeritem)
elif args.mode == 'unload':
mode_unload(args.dockeritem)
elif args.mode == 'shell':
mode_shell(args.dockeritem)
elif args.mode == 'remove':
mode_remove(args.dockeritem)
elif args.mode == 'list':
mode_list()
elif args.mode == 'stop':
mode_stop(args.dockeritem)
elif args.mode == 'export':
mode_export()
elif args.mode == 'setuptokens':
setuptokens()
elif args.mode == 'run':
if args.arglist:
arglist = ' '.join(f'"{arg}"' if ' ' in arg else arg for arg in args.arglist)
else:
arglist = ''
mode_run(args.dockeritem, arglist)
elif args.mode == 'add':
if args.dockerfile and args.dockercomposefile:
print('[-] Cannot specify BOTH Dockerfile and docker-compose YAML.\n [*] If your Docker-Compose instance uses Dockerfiles, add these as files (\'-f\')')
exit(1)
mode_add(args.dockeritem, args.dockerfile, args.file, configfile, args.dockercomposefile)