How do I use a variable outside of a while loop - python

When I run the script, there are no errors but nothing gets printed nor logged, even if a model is actually uploaded.
import os
import requests
import sys
from colorama import Fore
os.system('cls')
while True:
info = requests.get("https://search.roblox.com/catalog/json?CatalogContect=2&Category=6&SortType=3&ResultsPerPage=1").json()
if info[0]['Name'] == "DreamGrim":
pass
elif info[0]['Name'] == ".gg/Fgj3VRGapz":
pass
else:
print(f"[{Fore.LIGHTGREEN_EX}+{Fore.RESET}] Logged model: " + str(info[0]['Name']) + " | " "https://www.roblox.com/library/" + str(info[0]['AssetId']) + "/" + str(info[0]['Name']))
with open('logs.txt', 'a') as f:
f.write(f"\n[+] Logged model: " + str(info[0]['Name']) + " | " "https://www.roblox.com/library/" + str(info[0]['AssetId']) + "/" + str(info[0]['Name']))
How do I make this work without the logs getting looped?
If I put it inside the while True: loop the logs start to loop and something like this happens:
[+] Logged model: Hot Chocolate | https://www.roblox.com/library/7881318998/Hot Chocolate
[+] Logged model: Hot Chocolate | https://www.roblox.com/library/7881318998/Hot Chocolate
[+] Logged model: Hot Chocolate | https://www.roblox.com/library/7881318998/Hot Chocolate
[+] Logged model: Hot Chocolate | https://www.roblox.com/library/7881318998/Hot Chocolate
[+] Logged model: Hot Chocolate | https://www.roblox.com/library/7881318998/Hot Chocolate

You have to terminate the while loop before the script can progress to the next step. If you try and run the following code you will get repeated 1s and no 2s:
while True:
print(1)
print(2)
A better way of structuring the code would be to get the info first and then iterate through it:
info = requests.get("https://search.roblox.com/catalog/json?CatalogContect=2&Category=6&SortType=3&ResultsPerPage=1").json()
for result in info:
if result['Name'] == "DreamGrim":
pass
...

You want to use the while True statement for something that should loop until you reach a point. Here, you are only creating and changing your variable's value over and over again.
You never break off of the loop so you never get to the rest of the code.
Maybe you wanted to use the with statement ?

Related

Command not executed on if statement being true

So I'm writing a simple program in Python that checks active window ID and in this program I have an if statement inside a while True loop that checks if the active window ID matches the expected window ID.
Here's the code:
import os, subprocess
def get_window_id():
output = subprocess.check_output("xprop -root | grep \"window id\"", shell=True)
get_window_id.result = {}
for row in output.split(b"\n"):
if b": " in row:
key, value = row.split(b": ")
get_window_id.result[key.strip(b"window id # ")] = value.strip()
while True:
get_window_id()
print(get_window_id.result[b"_NET_ACTIVE_WINDOW(WINDOW)"].strip(b"b'window id # "))
if get_window_id.result[b"_NET_ACTIVE_WINDOW(WINDOW)"].strip(b"b'window id # ") != "b'0x3000003'":
os.system("kill -STOP $(pgrep mpv)")
else:
os.system("kill -CONT $(pgrep mpv)")
When the active window ID doesn't match the expected one, the block of code that corresponds to that condition executes, but when the active window ID matches the expected one, the block of code that corresponds to that condition doesn't execute. I obviously want that block of code to execute.
As you can see, I'm not the best at Python and asking for help but I hope that this is enough for somebody to help. If not I can always provide more information :)
And sorry if the title and/or body of the question are not clear. It's currently 2AM and I've been trying to do this all day.
Thanks in advance.
YES! I did it! Just needed some sleep and a little bit more searching, but basically what I needed to do is get rid of those bs before the strings and to do that I needed to add encoding=utf8 to the subprocess.check_output line and delete the bs and it worked!
Code after the change:
import os, subprocess
def get_window_id():
output = subprocess.check_output("xprop -root | grep \"window id\"", shell=True, encoding="utf8")
get_window_id.result = {}
for row in output.split("\n"):
if ": " in row:
key, value = row.split(": ")
get_window_id.result[key.strip("window id # ")] = value.strip()
while True:
get_window_id()
print(get_window_id.result["_NET_ACTIVE_WINDOW(WINDOW)"].strip("'window id # "))
if get_window_id.result["_NET_ACTIVE_WINDOW(WINDOW)"].strip("'window id # ") != "0x3000003":
os.system("kill -STOP $(pgrep mpv)")
else:
os.system("kill -CONT $(pgrep mpv)")

How do I authenticate a bitcoinlib created wallet against a mnemonic phrase?

I have created a wallet using bitcoinlib. The wallet is named 'my-awesome-wallet55.' When I try to open my existing wallet with a newly generated mnemonic phrase, the behavior I expect is an exception or security error, however the wallet opens anyway. I can manually check the private keys to create my own security check, but shouldn't trying to open an existing wallet with the wrong key fail? Seems like a pretty big security issue otherwise.
from bitcoinlib.wallets import Wallet, wallet_create_or_open
from bitcoinlib.keys import HDKey
from bitcoinlib.mnemonic import Mnemonic
# Creating a new Mnemonic phrase to try and open an existing wallet with
passphrase=Mnemonic().generate(strength=256, add_checksum=True)
# Use new phrase to create key
key = HDKey.from_passphrase(passphrase, witness_type='segwit', network='testnet')
# In my opinion this should fail because I provided the wrong key, but it returns the wallet
w = Wallet('my-awesome-wallet55', main_key_object=key)
# Statement showing that our private keys are different
print("key.private_hex: " + key.private_hex + "\nw.main_key.key_private.hex(): " +
w.main_key.key_private.hex())
if key.private_hex == w.main_key.key_private.hex():
# We don't make it here because our private keys don't match
print("Wallet 'my-awesome-wallet55' authenticated")
w.utxos_update()
print("Balance: " + str(w.balance()))
print("Wallet address: " + w.get_key().address)
w.info()
else:
# Instead we make it here and still have access to the wallet
print("Wallet Authentication failed")
w.utxos_update()
print("Balance: " + str(w.balance()))
print("Wallet address: " + w.get_key().address)
w.info()
Is there a standard way for authenticating a wallet using bitcoinlib? Based on what I have here, it seems someone only needs to know the name of a wallet to gain complete access over it.
UPDATE:
After getting Frank's question, I updated the code to try and send a transaction:
from bitcoinlib.wallets import Wallet, wallet_create_or_open
from bitcoinlib.keys import HDKey
from bitcoinlib.mnemonic import Mnemonic
passphrase=Mnemonic().generate(strength=256, add_checksum=True)
#passphrase='lumber romance negative child immense grab icon wasp silver essay enjoy jewel mom demise fit moral device hand capable toilet spirit age enforce deny'
print(passphrase)
key = HDKey.from_passphrase(passphrase, witness_type='segwit', network='testnet')
#wallet_create_or_open('my-awesome-wallet55', keys=passphrase, witness_type='segwit', network='testnet')
w = Wallet('my-awesome-wallet55', main_key_object=key)
print("key.private_hex: " + key.private_hex + "\nw.main_key.key_private.hex(): " + w.main_key.key_private.hex())
if key.private_hex == w.main_key.key_private.hex():
print("Wallet 'my-awesome-wallet55' authenticated")
w.utxos_update()
print("Balance: " + str(w.balance()))
t = w.send_to('tb1qprqnf4dqwuphxs9xqpzkjdgled6eeptn389nec', 4000, fee=1000)
t.info()
else:
print("Wallet Authentication failed")
w.utxos_update()
print("Balance: " + str(w.balance()))
t = w.send_to('tb1qprqnf4dqwuphxs9xqpzkjdgled6eeptn389nec', 4000, fee=1000)
t.info()
Here are the results:
Sonnys-MBP:TelegramBTCWallet sonnyparlin $ python test.py
unfold royal atom rule electric ice quote spin fiber quality lady just garment nature secret six garden comic carpet mom endless lamp family arctic
key.private_hex: 23ac38dc5293ee53918c8dfe18abc28975c8fa6963c876302aa4473ddca2f14a
w.main_key.key_private.hex(): 8c11283bf21e9344930ab9519742d6f59cd220528e0be17886d27a21c9c127c7
Wallet Authentication failed
Balance: 95000.0
Transaction 5e729021da81a5e6fc3b3d88b5bf136d09c78b0ac9a08be2cf1c90107e7ae27c
Date: None
Network: testnet
Version: 1
Witness type: segwit
Status: unconfirmed
Verified: True
Inputs
- tb1q7dx79l3maq2cqynpjzxqxsk3v6jhhaggzl07c3 0.00095000 tBTC badb9dbe2b4741310137de774e058aaf6cbba28e2f36c11640b241284f780f86 1
segwit sig_pubkey; sigs: 1 (1-of-1) valid
Outputs
- tb1qprqnf4dqwuphxs9xqpzkjdgled6eeptn389nec 0.00004000 tBTC p2wpkh U
- tb1q9wg0vnqx63ng39s80gwqqffe2z7c5vvh0f4h3g 0.00090000 tBTC p2wpkh U
Size: 139
Vsize: 139
Fee: 1000
Confirmations: 0
Block: None
Pushed to network: True
Wallet: my-awesome-wallet55
I published this to the bitcoinlib developers as a bug, which they confirmed, you can follow it here:
https://github.com/1200wd/bitcoinlib/issues/206#issuecomment-991265402

PYTHON - Itertools.combinations results in memory error

I am creating a brute force script (for my studies) on python which connects to my login.php form and tries a combinaison of every characters of the alphabet to find the password.
The thing is that, after something like 110 000 combinaison, I am getting a memory error.
I already looked up on the net to find solutions which seems to be :
--> gc.collect() & del var
I tried to add the gc.collect() on the blank field of my function bruteforce so everytime i % 100 == 0, I clear the memory space but It dosen't work.
I can't find the way to add it in my script to free memory.
I think the problem is that I can't clear the memory space when my function is running. Maybe I should play with many threads like :
start 1
stop 1
clear space
start 2
stop 2
clear space
etc...
Do you guys have any suggestions ?
Here is my code :
import itertools, mechanize, threading, gc, os, psutil
charset='abcdefghijklmnopqrstuvwxyz'
br=mechanize.Browser()
combi=itertools.combinations(charset, 2)
br.open('http://192.168.10.105/login.php')
def check_memory():
process = psutil.Process(os.getpid())
mem_info = process.memory_info()
return mem_info.rss
def bruteforce():
i = 0
for x in combi:
br.select_form(nr=0)
br.form ['username'] = 'myusername'
tried = br.form ['password'] = ''.join(x)
i = i+1
print "Checking : ", tried, " Number of try : ", i
response=br.submit()
if response.geturl()=="http://192.168.10.105/index.php":
print("The password is : ", ''.join(x))
break
if i % 100 == 0:
mem_before = check_memory():
print "Memory before : ", mem_before
print "Free memory "
mem_after = check_memory()
print "Memory after : ", mem_after
x = threading.Thread(target = bruteforce)
x.start()
Thank you !
Thanks to #chepner, I found that the issue was with mechanize, not with itertools.
A good way to fix it is by clearing the history : "Out of Memory" error with mechanize

Trying to use Try/Except without an actual loop. Code is stuck on the except portion

Writing a python script that sets up pickup games. srv.connect() will time out if the IP/RCON are put in wrong and/or the server is down altogether. I do not want the discord bot to crash just because a server is down so I am trying to use a try/except to keep the bot going. A person can start a pickup by typing !pickup size 4 servername ... and if srv.connect() can not get a handshake with the server, itll time out and send a message in discord saying it can not find the server. Then they could do !pickup size 4 servername2 and itll work. Problem right now is that after doing !pickup size 4 servername it seems stuck on saying the rcon/ip is down even though servername2 should be running just fine. Any help?
if(message.content.startswith('!pickup size')):
if(pickupActive == 0):
x = message.content.split()
if(len(x) >= 4):
pServer = x[3]
if(pServer in servers):
srv = Console(host=servers[pServer][0], port= servers[pServer][1], password=servers[pServer][2])
try:
srv.connect()
servercfg = srv.execute("servercfgfile")
#print(servers[pServer][3])
if (servers[pServer][3] in servercfg): #and (pickupActive == 0)): #change "server.cfg" to whatever your server configurtion filename is for pickup play. keep the quotations
totalPlayers = [" "] * int(x[2])
initialPlayerCount = len(totalPlayers)
pickupLeader = message.author.name
totalPlayers.insert(playerCount, pickupLeader)
totalPlayers.remove(" ")
PopulateTable()
await message.channel.send("```Pickup Game Starting! " + pickupLeader + " is the leader for the Pickup Game! Come join in! type '!pickup add' to join```")
await message.channel.send("```" + msg + "```")
pickupActive = 1
else:
await message.channel.send("`" + servers[pServer][4] + "`")
except:
await message.channel.send("Can not connect to the server for rcon..")
srv.disconnect()
else:
await message.channel.send("`Please specify the size of the pickup and a valid server name..`")
else:
await message.channel.send("`Proper formatting not used, please say !pickup size # server (Example: !pickup size 3 nwo)`")
else:
await message.channel.send("`Already a pickup game in progress, please add up to the current pickup game..`")

Crawling web pages with Python

I have a seed file of 250 URLs of IMDB's top 250 movies.
I need to crawl each one of them and get some info from it.
I've created a function that gets a URL of a movie and returns the info I need. It works great. My problem is when I'm trying to run this function on all of the 250 URLs.
After a certian amount (not constant!) of URLs that were crawled successfully, the program stops its run. The python.exe process takes 0% CPU and the memory consumption doesn't change. After some debugging, I figured that the problem is with the parsing, it just stops working and I have no idea why (stuck on a find command).
I'm using urllib2 to get the HTML content of the URL, than parse it as a string and then continue to the next URL (I'm going only once on each of these strings, linear time for all the checks and extractions).
Any idea what can cause this kind of behavior?
EDIT:
I'm attaching one of the problematic functions' code (got 1 more, but I'm guessing it's the same problem)
def getActors(html,actorsDictionary):
counter = 0
actorsLeft = 3
actorFlag = 0
imdbURL = "http://www.imdb.com"
for line in html:
# we have 3 actors, stop
if (actorsLeft == 0):
break
# current line contains actor information
if (actorFlag == 1):
endTag = str(line).find('/" >')
endTagA = str(line).find('</a>')
if (actorsLeft == 3):
actorList = str(line)[endTag+7:endTagA]
else:
actorList += ", " + str(line)[endTag+7:endTagA]
actorURL = imdbURL + str(line)[str(line).find('href=')+6:endTag]
actorFlag = 0
actorsLeft -= 1
actorsDictionary[actorURL] = str(line)[endTag+7:endTagA]
# check if next line contains actor information
if (str(line).find('<td class="name">') > -1 ):
actorFlag = 1
# convert commas and clean \n
actorList = actorList.replace(",",", ")
actorList = actorList.replace("\n","")
return actorList
I'm calling the function this way:
for url in seedFile:
moviePage = urllib.request.urlopen(url)
print(getTitleAndYear(moviePage),",",movieURL,",",getPlot(moviePage),getActors(moviePage,actorsDictionary))
This works great without the getActors function
There is no exception raised here (I removed the try and catch for now)
and it's getting stuck in the for loop after some iterations
EDIT 2: if I run only the getActors function, it works well and finishes all the URLs in the seed file (250)

Categories