Added existing scripts

This commit is contained in:
2022-09-13 12:38:57 -05:00
parent 251dbfb0eb
commit 845bc9d7a3
38 changed files with 1340 additions and 0 deletions

25
python/Arcus admin.py Normal file
View File

@ -0,0 +1,25 @@
import string
from random import choice
userlist = ['Firstname Lastname <example@example.com>',]
identifier = 'tstidt'
arcus_endpoint = '.arcusapp.globalscape.com'
print('***\n')
for user in userlist:
ul = user.lower()
characters = string.ascii_letters + '!#$+-?~' + string.digits
password = "".join(choice(characters) for x in range(16))
first, last, email = ul.split()
print('RDGW:')
print(first.title())
print(last.title())
print(first[0] + last + '_' + identifier )
strip_email = email.strip('<')
strip_email = strip_email.strip('>')
print(password + '\n')
print('Deployatron:')
print(identifier + arcus_endpoint)
print(strip_email)
print(first[0] + last + '_' + identifier)
print(password + '\n')
print('***\n')

24
python/appengen.py Normal file
View File

@ -0,0 +1,24 @@
from datetime import date
time = date.today()
ln = input('What do you want the logger name to be?: ')
an = input('What do you want the appender name to be?: ')
ran = input('What is the real appender name in the EFT logging.cfg? Case sensitive!: ')
ll = input('What level do you want the logging to be?: ')
pre_str = 'log4cplus.appender.'
l1 = f'\n#{ln} logger {time}\n'
l2 = f'{pre_str}{an.lower()}=log4cplus::RollingFileAppender'
l3 = f'{pre_str}{an.lower()}.File=${{AppDataPath}}\\EFT-{ln}.log'
l4 = f'{pre_str}{an.lower()}.MaxFileSize=20MB'
l5 = f'{pre_str}{an.lower()}.MaxBackupIndex=5'
l6 = f'{pre_str}{an.lower()}.layout=log4cplus::TTCCLayout'
l7 = f'{pre_str}{an.lower()}.layout.DateFormat=%m-%d-%y %H:%M:%S,%q'
l8 = f'log4cplus.additivity.{ran}=false'
l9 = f'log4cplus.logger.{ran}={ll.upper()}, {an.lower()}\n'
llist = [ l1, l2, l3, l4, l5, l6, l7, l8, l9]
for obj in llist:
print(f'{obj}\r')

34
python/appengen2.py Normal file
View File

@ -0,0 +1,34 @@
from datetime import date
time = date.today()
ln = input('What do you want the logger name to be?: ')
an = input('What do you want the appender name to be?: ')
ran = input('What is are the real appender names in the EFT logging.cfg?\nDelimit by "," like this:\n sftp,smtp,workspaces Case sensitive!: ')
ran_list = []
if ',' in ran:
ran_list = ran.split(',')
ll = input('What level do you want the logging to be?: ')
pre_str = 'log4cplus.appender.'
l1 = f'\n#{ln} logger {time}\n'
l2 = f'{pre_str}{an.lower()}=log4cplus::RollingFileAppender'
l3 = f'{pre_str}{an.lower()}.File=${{AppDataPath}}\\EFT-{ln}.log'
l4 = f'{pre_str}{an.lower()}.MaxFileSize=20MB'
l5 = f'{pre_str}{an.lower()}.MaxBackupIndex=5'
l6 = f'{pre_str}{an.lower()}.layout=log4cplus::TTCCLayout'
l7 = f'{pre_str}{an.lower()}.layout.DateFormat=%m-%d-%y %H:%M:%S,%q'
l8 = ''
l9 = ''
if ran_list:
while ran_list:
ap = ran_list.pop()
l8 += f'log4cplus.additivity.{ap}=false\n'
l9 += f'log4cplus.logger.{ap}={ll.upper()}, {an.lower()}\n'
else:
l8 += f'log4cplus.additivity.{ran}=false\n'
l9 += f'log4cplus.logger.{ran}={ll.upper()}, {an.lower()}\n'
llist = [ l1, l2, l3, l4, l5, l6, l7, l8, l9]
for obj in llist:
print(f'{obj}\r')

38
python/countfolders.py Normal file
View File

@ -0,0 +1,38 @@
import sqlite3
import logging
import logging.handlers
# make sure the slashes are forward
# create logger
filename = "C:/Users/jbranan/Desktop/temp/a/log.txt"
logger = logging.getLogger('sqllite')
logger.setLevel(logging.DEBUG)
# create console handler and set level to debug
ch = logging.handlers.RotatingFileHandler(filename, mode='a', maxBytes=20971520, backupCount=5, encoding=None, delay=False)
ch.setLevel(logging.INFO)
# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# add formatter to ch
ch.setFormatter(formatter)
# add ch to logger
logger.addHandler(ch)
db = "C:/Users/jbranan/Desktop/temp/a/SiteConfig.e05dd013-0099-47c5-a727-dc0285e74204.db"
query = r"""
SELECT count(PathLowered)
FROM FSEntry
WHERE PathLowered LIKE '%az%';
"""
conn = sqlite3.connect(db)
c = conn.cursor()
c.execute(query)
data = c.fetchone()[0]
logger.info(f'{data} %az%')
conn.close()

View File

@ -0,0 +1,9 @@
import win32com.client as win32
from pathlib import Path
server = win32.gencache.EnsureDispatch('SFTPCOMInterface.CIServer')
server.ConnectEx('192.168.4.14', 1100, 0, 'a', 'QjIlmT4H')
a = server.ICIClientSettings.GetUsedSpace
print(a)

5
python/eftcom.py Normal file
View File

@ -0,0 +1,5 @@
import win32com.client as win32
from pathlib import Path
server = win32.gencache.EnsureDispatch('SFTPCOMInterface.CIServer')
server.ConnectEx('localhost', 1100, 0, 'scripting', 'password')

10
python/file_replicator.py Normal file
View File

@ -0,0 +1,10 @@
from shutil import copyfile
templatefile = "C:/tmp/work/test_12722-16345_1gb.txt"
output_folder = "C:/tmp/work/output/"
fs, fl = templatefile.split('.')
if '/' in fs:
fs = fs.split('/')[-1]
for i in range(16):
destfilename = f'{output_folder}{i}{fs}.{fl}'
copyfile(templatefile, destfilename)

37
python/filecreator.py Normal file
View File

@ -0,0 +1,37 @@
import os
import string
from datetime import datetime
now = datetime.now() # current date and time
tm = now.strftime("X%mX%dX%y-X%HX%MX%S").replace('X0','X').replace('X','')
file = 'test'
ext = '.txt'
# Must be forward slashes
outputdirectory = 'C:/tmp/work/'
fsize = '1gb'
go = True
class Del:
def __init__(self, keep=string.digits + '.'):
self.comp = dict((ord(c),c) for c in keep)
def __getitem__(self, k):
return self.comp.get(k)
DD = Del()
fname = f'{file}_{tm}_{fsize}{ext}'
if 'k' in fsize.lower():
unit = float(1024)
fsizecal = unit * float(fsize.translate(DD))
elif 'm' in fsize.lower():
unit = float(1048576)
fsizecal = unit * float(fsize.translate(DD))
elif 'g' in fsize.lower():
unit = float(1073741824)
fsizecal = unit * float(fsize.translate(DD))
else:
print("For Kilobytes please use kb or k\nFor Megabytes please use mb or m\nFor Gigabytes please use gb or g")
go = False
if go:
os.system(f'fsutil.exe file createnew {outputdirectory}{fname} {int(fsizecal)}')

View File

@ -0,0 +1,11 @@
import sqlite3
# make sure the slashes are forward
db = "C:/Users/jbranan/Desktop/SiteConfig.94e925b5-6120-4d85-8660-60a74a495361.db.old-broken"
query = """PRAGMA foreign_keys = 0; CREATE TABLE sqlitestudio_temp_table AS SELECT * FROM Participation; DROP TABLE Participation; CREATE TABLE Participation( id BLOB NOT NULL, ParticipationInfo TEXT NOT NULL, InvitationInfo TEXT NOT NULL, Files TEXT NOT NULL, Workspace BLOB, Client BLOB, Secret TEXT NOT NULL, Invitation BLOB, PRIMARY KEY ( id), CONSTRAINT Client_fk FOREIGN KEY ( Client ) REFERENCES Client (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED, CONSTRAINT Workspace_fk FOREIGN KEY ( Workspace ) REFERENCES Workspace (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED, CONSTRAINT Invitation_fk FOREIGN KEY ( Invitation ) REFERENCES Invitation (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED ); INSERT INTO Participation ( id, ParticipationInfo, InvitationInfo, Files, Workspace, Client, Secret, Invitation ) SELECT id, ParticipationInfo, InvitationInfo, Files, Workspace, Client, Secret, Invitation FROM sqlitestudio_temp_table; DROP TABLE sqlitestudio_temp_table; CREATE INDEX Participation_Client_i ON Participation ( "Client" ); CREATE INDEX Participation_Secret_i ON Participation ( "Secret" ); PRAGMA foreign_keys = 1;"""
conn = sqlite3.connect(db)
c = conn.cursor()
c.executescript(query)
conn.commit()
conn.close()

32
python/gen_json.py Normal file
View File

@ -0,0 +1,32 @@
# You can change these, make suure file_path always has forward slashes
# and make sure to double up backslashes in the output folder
file_path = 'C:/Users/klowery/Desktop/reports/'
#output_folder = '\\\\file.core.windows.net\\gsbshared\\AdminSite\\ARMDB-Output'
output_folder = 'C:\\Users\\klowery\\Desktop\\reports'
user = 'a'
ipaddress = '8.8.8.8'
#Dont change these
file_list = ['ActivityAdhocDetailed','EventRulesActivityDetailed','TransactionsTable',
'AuthenticationsTable','ExecutiveSummary','TroubleshootingEventRuleFailures',
'AdminActions','FailedLogins','WorkspacesActivity',
'AdminActivitySummary','ProtocolCommandsTable','TrafficIpWiseConnections',
'AllFiles','TrafficConnectionsSummary','ActivityByUserDetailed','TroubleshootingIpAddressActivityDetailed']
additional_parameter = ''
additional_value = ''
additional_string = f',"{additional_parameter}":"{additional_value}"'
for file_name in file_list:
fobj = file_path + file_name + '.json'
with open(fobj, 'w') as f:
if file_name == 'ActivityByUserDetailed':
additional_parameter = 'User'
additional_value = user
file_contents = f'{{"Days":"1","Report":"{file_name}","UseInterimFile":true,"OutputFolder":"{output_folder}"{additional_string}}}'
elif file_name == 'TroubleshootingIpAddressActivityDetailed':
file_contents = f'{{"Days":"1","Report":"{file_name}","UseInterimFile":true,"OutputFolder":"{output_folder}"{additional_string}}}'
additional_parameter = 'ipAddress'
additional_value = ipaddress
else:
file_contents = f'{{"Days":"1","Report":"{file_name}","UseInterimFile":true,"OutputFolder":"{output_folder}"}}'
f.write(file_contents)

39
python/hotfix.py Normal file
View File

@ -0,0 +1,39 @@
# No Touchy
file_list = []
build_list = True
# Change to what ever you would like the extention of the name to be in the instructions.
rn_ext = '.old'
while build_list:
file_name = input('Name of file? If done, type d: ')
if file_name == 'd':
build_list = False
else:
file_list.append(file_name)
header_line = 'Hotfix Instructions:'
print(header_line)
line_counter = 1
service_off = f'{line_counter}.WARNING: Shut off the service on all nodes!'
print(service_off)
line_counter += 1
for fn in file_list:
if fn == file_list[0]:
main_line_rn = f'{line_counter}.Rename {fn} to {fn}{rn_ext} on all nodes. You can determine the location of this file by looking at the registry here:\n\t(HKEY_LOCAL_MACHINE\\SOFTWARE\WOW6432Node\\GlobalSCAPE Inc.\\EFT Server Enterprise) \n\tThe default location for this file is in the "C:\\Program Files (x86)\\Globalscape\\EFT Server Enterprise\\ directory".'
print(main_line_rn)
else:
alt_line_rn = f'{line_counter}.Rename {fn} to {fn}{rn_ext} in that same folder on all nodes.'
print(alt_line_rn)
line_counter += 1
for fnc in file_list:
alt_line_c = f'{line_counter}.Copy the {fnc} file into the respective directories on all nodes.'
print(alt_line_c)
line_counter += 1
validate_hotfix = f'{line_counter}.Verify the hotfix has been deployed by right clicking on the files in the destination and going to the details tab. Confirm the "Product version" property has a hotfix number.'
print(validate_hotfix)
line_counter += 1
service_on = f'{line_counter}.Start the service.'
print(service_on)

21
python/injectadmin.py Normal file
View File

@ -0,0 +1,21 @@
import sqlite3
# make sure the slashes are forward
db = "//192.168.2.21/Vault/testing stuff/ServerConfig.db"
query = """
INSERT OR REPLACE INTO "main"."Admin" ("id", "Name", "NameLowered", "Type", "LastActiveTime", "PasswordHash", "PasswordIsTemporary", "PasswordChangedTime", "PasswordHistory", "UnlockTime", "InvalidLoginAttempts", "Permissions") VALUES (X'b76a1d7bc3ad5ac4863606ce71ba3af3', 'Local computer\\Administrators', 'local computer\\administrators', '2', '1607536951', '', '1', '1607536951', '[]', '0', '[]', '{
"ACLs": [],
"Level": "Server",
"ManageCom": true,
"ManagePersonalData": true,
"ManageReporting": true,
"RestAccess": true,
"RestAdminRole": "server_full_access",
"SettingsTemplates": []
}');"""
conn = sqlite3.connect(db)
c = conn.cursor()
c.execute(query)
conn.commit()
conn.close()

View File

@ -0,0 +1,17 @@
# Requirements
# Copy all of the files from the W:\Installers folder to any local folder on the laptop
# Build a manifest
# Determine the difference between the current W:\Installers and the destination manifest
# RSYNC?
# importing required packages
import os
from datetime import datetime
tm = now.strftime("X%mX%dX%y-X%HX%MX%S").replace('X0','X').replace('X','')
# defining source and destination
# paths
src = 'W:/installers'
trg = 'C:/Users/jbranan/Downloads/installers'
logfile = f'C:/Users/jbranan/Desktop/RC_log_{tm}.log'
os.system(f'Robocopy {src} {trg} /V /E /r:1 /w:15 /log+:{logfile} /XO /NP')

View File

@ -0,0 +1,35 @@
import time
import platform
full_list = True
results_value = 10
version = platform.architecture()
print(version[0])
start_time = time.time()
d = {}
print('Building username appearance totals...')
# 71.50.132.89 - -, [28/Jan/2021:00:44:22 +0530] "user root" 331 0,
with open('C:/Users/jbranan/Desktop/temp/h/Global_support/Logs/nc210121.log', encoding='utf8') as file_object:
for line in file_object.readlines():
if not '#' in line and '] "user ' in line:
username = line.split('] "user ')[1].split('" ')[0]
if not username in d and not username.startswith('-'):
d[username] = 1
elif not username.startswith('-'):
d[username] += 1
elif '/' in username:
continue
d = sorted(d.items(), key=lambda x: x[1], reverse=True)
if full_list:
for username in d:
print(f'User: {username[0]} - Appearances: {username[1]}')
else:
for username in d[:results_value]:
print(f'User: {username[0]} - Appearances: {username[1]}')
print("--- %s seconds ---" % (time.time() - start_time))

75
python/parseSiteRoot.py Normal file
View File

@ -0,0 +1,75 @@
#!/usr/bin/python3
import sys
import re
import string
from collections import defaultdict
currDir = ""
lines = []
folders = defaultdict(int)
foldersOldFiles = defaultdict(int)
parsedCurrentDir = []
while True:
in_line = sys.stdin.readline()
if not in_line:
break
in_line = in_line[:-1]
#m = re.search("Directory: (.*)$", in_line)
m = re.search("gsbdata.InetPub.(.*)$", in_line)
if m:
currDir = m.group(1)
currDir = currDir.lstrip().rstrip()
# folder names split across lines
while True:
in_line = sys.stdin.readline()
in_line = in_line[:-1]
in_line = in_line.lstrip().rstrip()
if(in_line == ''):
break
else:
currDir = currDir + in_line
#folders[currDir] = 0
parsedCurrDir = re.split(r'\\', currDir)
#print(currDir)
continue
#continue
if in_line.startswith("-a----"):
arr = re.split("\s+", in_line)
filelen = int(arr[4]) #string.atoi(arr[4])
for i in range(0, len(parsedCurrDir)):
f = r'\\'.join(parsedCurrDir[0:i])
folders[f] = folders[f] + filelen
if arr[1].endswith("2019") or arr[1].endswith("2018"):
for i in range(0, len(parsedCurrDir)):
f = r'\\'.join(parsedCurrDir[0:i])
foldersOldFiles[f] = foldersOldFiles[f] + filelen
for kv in folders.items():
#print(kv)
formattedOldFilesLen = "{:15d}".format(foldersOldFiles[kv[0]])
formattedLen = "{:15d}".format(kv[1])
if 0 != kv[1]:
percent = 100.0 * float(foldersOldFiles[kv[0]])/float(kv[1])
else:
percent = float(0.0)
line = "%s %s %s%% %s" % (formattedOldFilesLen, formattedLen, "{:6.2f}".format(percent), kv[0])
lines.append(line)
lines.sort()
lines.reverse()
for line in lines:
print(line)

6
python/password.py Normal file
View File

@ -0,0 +1,6 @@
import string
from random import *
characters = string.ascii_letters + '!#$+-?~' + string.digits
password = "".join(choice(characters) for x in range(16))
print(password)

10
python/updateawepath.py Normal file
View File

@ -0,0 +1,10 @@
import sqlite3
db = "C:/Users/jonbr/OneDrive/pyprojects/work.py/update values in sqllite/SiteConfig.33ffaac4-ee37-4fb3-95a2-928ae6333757.db"
awe_path = '\\\\file.core.windows.net\\gsbslogs\\AWE\\'
conn = sqlite3.connect(db)
c = conn.cursor()
c.execute(f"UPDATE AdvancedWorkflow set settings = json_set(AdvancedWorkflow.Settings, '$.LogDir', '{awe_path}')")
conn.commit()
conn.close()