Whats the different about try: and def? - python

I'm trying to Open a file as text, choosing the file via str(raw_input, but it doesn't work with def main():.
My second script, with normal (No threading), is using try:. The threading one not opening the email.
Here is a link to the scripts in ghostbin:
Normal Script Without Threading and Multithread Script ,
The Normal Script Without Threading
try:
filelist = str(raw_input("[+] Enter Mailist File: "))
loglive = open('live.txt','a')
logdie = open('die.txt','a')
logun = open('uncheck.txt','a')
except Exception as Err:
print("ERROR : File List Not Found!")
sys.exit()
list = open(filelist, "r")
while True:
email = list.readline().replace("\n","")
if not email:
break
Multithread Script
def main():
start_time = time.time()
tanya = str(raw_input("[+] Enter Mailist File: "))
mailist = open(tanya, 'r')
while True:
email = mailist.readline().replace("\n","")
if not email:
break
s = requests.session()

You need to call the main function for it to be executed. At the end of your file, add:
if __name__ == '__main__':
main()
The reason for this can be found here: What does if __name__ == "__main__": do?

Related

program freezes after it has enumerated all subdomains

I am trying to create a threaded subdomain enumerator, and every time it's done enumerating subdomains on sites like google.com the program just freezes and doesn't exit so it doesn't print the final line print("\\n\[+\] Done enumerating").
import requests
import validators
from concurrent.futures import ThreadPoolExecutor
def enumerate_subdomain(subdomain):
http_url = f"http://{subdomain}.{domain}"
https_url = f"https://{subdomain}.{domain}"
try:
if validators.url(https_url) == True:
requests.get(https_url)
print(f"[!] Subdomain found: {https_url}")
else:
requests.get(http_url)
print(f"[!] Subdomain found: {http_url}")
except requests.ConnectionError:
pass
domain = input("[+] Domain (e.g. example.com): ")
file = input("[+] Path to wordlist file: ")
threads = int(input("[+] Amount of threads (10-50 is recommended): "))
with open(file, "r") as f:
content = f.read()
subdomains = content.splitlines()
if __name__ == "__main__":
with ThreadPoolExecutor(max_workers=threads) as executor:
executor.map(enumerate_subdomain, subdomains)
executor.shutdown(wait=False)
print("\n[+] Done enumerating")
I tried adding the following line executor.shutdown(wait=True) after executor.map but it still doesn't work

Python Speech Recognition not working when the file is converted to exe with pyinstaller

I created a Voice Assistant using speech recognition and GTTS modules in Python. The code works perfectly fine when run from script. But when I converted it using pyinstaller --onefile Speak.py(The name of the file) it stopped working. It is using my microphone but its not responding to anything. Suppose if I say hey google which is the wake up keyword it simply doesnt respond. I tried after a while but of no use. Can anyone please help me???
Code:
"from gtts import gTTS
import speech_recognition as sr
import os
import playsound
from datetime import datetime
import webbrowser
keeprunning = True
WAKING = "HEY GOOGLE"
def chec(cond, tex):
if cond in tex:
return True
else:
return False
def speak(text):
speaker = gTTS(text = text, lang = "en")
speaker.save("Voice.mp3")
playsound.playsound("voice.mp3")
os.remove("Voice.mp3")
def cleanify(text, wtremove, wtremove2=""):
try:
text = text.replace(wtremove)
except:
if not wtremove2 == "":
text = text.replace(wtremove2, "")
return text
#Main controlling part here(Oof!)
def Control(comnd):
if chec("SEARCH", comnd) or chec("GOOGLE", comnd):
comnd = cleanify(comnd, "SEARCH", "GOOGLE")
webbrowser.open(f"https://google.com/search?q={comnd.lower()}")
elif chec("WHO ARE YOU", comnd):
speak("I am your virtual assistant, google")
keepcontrol()
elif chec("TIME", comnd):
t = datetime.now()
t = time.strptime(t.strftime("%H:%S"), "%H:%M")
tt = time.strftime( "%I:%M %p", t )
speak(f"The current time is {tt}")
elif chec("NOTE", comnd) or chec("REMEMBER", comnd) or chec("JOT", comnd):
try:
text = comnd.replace("NOTE")
except:
try:
text = text.replace("REMEMBER")
except:
text = text.replace("JOT")
try:
with open("This_File_Name_Is_Very_Big_Because_I_dont_Want_to_overwrite_anyother_files_so_forgive_me_plz.txt", "rt") as file:
previous = file.read()
except:
with open("This_File_Name_Is_Very_Big_Because_I_dont_want_to_overwrite_any_other_files_so_forgive_me_plz.txt", "wt") as file:
ttw = f"""
•{text.lower()}
"""
file.write(previous + ttw)
previous = ""
with open("Notes.txt", "wt") as file:
ttw = previous + " •" + text
file.write(ttw)
speak("Got it! I noted it down")
elif chec("OPEN", comnd):
web = cleanify(comnd, "OPEN")
bruh = cleanify(web, ".com")
speak(f"Opening {bruh}")
print(comnd)
web = cleanify(comnd, "OPEN")
if web == "":
web = listen()
else:
if "https://" in web:
webbrowser.open(web.lower())
else:
web = "https://" + web
webbrowser.open(web.lower())
keepcontrol()
#Main controlling part ends
def listen():
r = sr.Recognizer()
with sr.Microphone() as source:
listen = r.listen(source)
try:
text = r.recognize_google(listen)
return text.upper()
except Exception as e:
if not e == "":
return ""
keepcontrol()
else:
speak("Sorry we couldnt catch that, please try again")
keepcontrol()
def keepcontrol():
while keeprunning:
text = listen()
if not text == None:
if text.count(WAKING) == 1:
speak("I am listening..")
text = listen()
if not text == None and not text == "":
Control(text)
else:
speak("Sorry i did not get that. Try again in a few seconds")
keepcontrol()
elif chec("QUIT", text):
exit()
elif chec("", text):
keepcontrol()
else:
speak("Sorry we didnt get that right. Please try again.")
speak("I am booting up...")
keepcontrol()
"
When you have converted it into exe,I think you have forgot to put files that you have used to build the assistant in the folder.
When your exe get converted, just simply copy those files(the files you have used) in the same folder in which you have kept your exe.
Hope it will work.

problem finishing coding my python script using asyncio

I'm new to python and coding in general
here the code:
def job():
try:
users = sub_client.get_all_users(size=1)
except json.decoder.JSONDecodeError:
pass
for uid in users.profile.id:
with open("uid.txt", "r") as file:
uids = file.read().split("\n")[:-1]
if uid in uids:
print("already done")
else:
print("done")
sub_client.comment(userId=uid, message="welcome")
print(uid)
with open("uid.txt", "a") as f:
f.write(f"{uid}\n")
f.close()
while True:
readChat = ['4044f0f7-7963-46ad-b453-bb7d417be19a']
for chat in readChat:
messageList = sub_client.get_chat_messages(size=1, chatId=chat)
chatInfo = sub_client.get_chat_thread(chatId=chat)
for nickname, content, id in zip(messageList.author.nickname, messageList.content, messageList.messageId):
print(nickname, content)
content = str(content).split(" ")
if content[0][0] == "!":
if content[0][1:].lower() == "start":
sub_client.send_message(message="🤖 | ok! bot activé",chatId=chatInfo.chatId)
asyncio.create_task(job())
if content[0][1:].lower() == "stop":
sub_client.send_message(message="🤖 | ok! bot désactivé", chatId=chatInfo.chatId)
break
Would like that the first "job" run all the time when someone write "!start" into a chat, and that the task stop when someone write "!stop" (but not completly stopped, for example if someone write "!start" again into the chat, it restart the task, etc...)
Is this even possible?
The script will run 24/24, 7/7

How to run code every x seconds inside while true - python

I need to execute code inside while loop every x seconds without stoping loop work
I have trying threading and lock combinations but it is still not working. I am working on python 3.7.4, pycharm 2019.2
#!/usr/bin/env python3
import configparser
import logging
import threading
import time
import ts3
__all__ = ["notify_bot"]
logging.basicConfig(filename='ts3bot.log',
level=logging.INFO,
format="%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s",
)
logging.getLogger().addHandler(logging.StreamHandler())
def notify_bot(ts3conn, config, lock):
logging.info("Start Notify Bot ...")
lock.acquire()
ts3conn.exec_("servernotifyregister", event="server")
lock.release()
while True:
event = ts3conn.wait_for_event()
try:
reasonid_ = event[0]["reasonid"]
except KeyError:
continue
if reasonid_ == "0":
logging.info("User joined Lobby:")
logging.info(event[0])
servergroups = event[0]['client_servergroups']
guestname = event[0]['client_nickname']
lock.acquire()
if not set(servergroups):
print(f"s1 {guestname}")
else:
print(f"s2{guestname}")
lock.release()
return None
def keep_alive(ts3conn, lock):
while True:
logging.info("Send keep alive!")
lock.acquire()
ts3conn.send_keepalive()
lock.release()
time.sleep(5)
if __name__ == "__main__":
logging.info("Start TS Bot ...")
config = configparser.ConfigParser()
config.sections()
config.read("settings_test.ini")
logging.info("Config loaded!")
HOST = config['server']['url']
PORT = config['server']['query_port']
USER = config['server']['query_user']
PASS = config['server']['query_pw']
SID = config['server']['sid']
NAME = config['bot']['name']
logging.info("Connecting to query interface ...")
URI = f"telnet://{USER}:{PASS}#{HOST}:{PORT}"
try:
with ts3.query.TS3ServerConnection(URI) as ts3conn:
ts3conn.exec_("use", sid=SID)
ts3conn.query("clientupdate", client_nickname="x123d")
logging.info("Connected!")
lock = threading.Lock()
notify_thread = threading.Thread(target=notify_bot, args=(ts3conn, config, lock), daemon=True,
name="notify")
keep_alive_thread = threading.Thread(target=keep_alive, args=(ts3conn, lock), daemon=True,
name="keep_alive")
notify_thread.start()
keep_alive_thread.start()
keep_alive_thread.join()
notify_thread.join()
except KeyboardInterrupt:
logging.INFO(60 * "=")
logging.info("TS Bot terminated by user!")
logging.INFO(60 * "=")
After run work for 1 person who join server and do nothing, dont send keep alive and dont work at all
you can use Bibio TIME
You can check it from official python website (https://docs.python.org/3/library/time.html)
Personally, for simple things, I find the _thread library easier. Here's a function that you can run in a thread, and an example of starting that thread:
import _thread
def mythread(arg1):
while True:
time.sleep(arg1)
do.whatever()
_thread.start_new_thread(mythread, (5,))
The important thing to note is the second argument I passed to the _thread.start_new_thread function. It must be a tuple, which is why there is a comma after the 5. Even if your function doesn't require any arguments, you have to pass a tuple.
I am using time module and threading,
I'v made some changes and it seems to work
#!/usr/bin/env python3
import configparser
import logging
import threading
import time
import ts3
logging.basicConfig(filename='ts3bot.log',
level=logging.INFO,
format="%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s",
)
logging.getLogger().addHandler(logging.StreamHandler())
def notify_bot(ts3conn):
logging.info("Start Notify Bot ...")
ts3conn.exec_("servernotifyregister", event="server")
while True:
event = ts3conn.wait_for_event()
try:
reasonid_ = event[0]["reasonid"]
except KeyError:
continue
if reasonid_ == "0":
logging.info("User joined Lobby:")
logging.info(event[0])
servergroups = event[0]['client_servergroups']
guestname = event[0]['client_nickname']
if not set(servergroups):
print(f"s1 {guestname}")
else:
print(f"s2{guestname}")
return None
def keep_alive(ts3conn, time):
while True:
logging.info("Send keep alive!")
ts3conn.send_keepalive()
time.sleep(20)
if __name__ == "__main__":
logging.info("Start TS Bot ...")
config = configparser.ConfigParser()
config.sections()
config.read("settings_test.ini")
logging.info("Config loaded!")
HOST = config['server']['url']
PORT = config['server']['query_port']
USER = config['server']['query_user']
PASS = config['server']['query_pw']
SID = config['server']['sid']
NAME = config['bot']['name']
logging.info("Connecting to query interface ...")
URI = f"telnet://{USER}:{PASS}#{HOST}:{PORT}"
try:
with ts3.query.TS3ServerConnection(URI) as ts3conn:
ts3conn.exec_("use", sid=SID)
ts3conn.query("clientupdate", client_nickname="x123d")
logging.info("Connected!")
notify_thread = threading.Thread(target=notify_bot, args=(ts3conn,), daemon=True,
name="notify")
keep_alive_thread = threading.Thread(target=keep_alive, args=(ts3conn, time), daemon=True,
name="keep_alive")
notify_thread.start()
keep_alive_thread.start()
keep_alive_thread.join()
notify_thread.join()
except KeyboardInterrupt:
logging.INFO(60 * "=")
logging.info("TS Bot terminated by user!")
logging.INFO(60 * "=")
It looks like ts3conn.send_keepalive() making error, when I delete it, code work fine, when I'v add it, code stop working after send ts3conn.send_keepalive() once

Enumeration Program

I'm in the process of creating a program that takes an IP address, performs an nmap scan, and takes the output and puts it in a text file. The scan works fine, but I can't seem to figure out why it's not writing anything to the text file.
Here is what I have so far
if __name__ == "__main__":
import socket
import nmap
import sys
import io
from libnmap.parser import NmapParser, NmapParserException
from libnmap.process import NmapProcess
from time import sleep
from os import path
#Program Banner
if len(sys.argv) <= 1:
print(
"""
test
""")
sys.exit()
#Grab IP Address as argument
if len(sys.argv)==2:
ip = sys.argv[1]
print "\n[+] Reading IP Address"
#Function - Pass IP to Nmap then start scanning
print "\n[+] Passing " + ip + " to Nmap..."
print("\n[+] Starting Nmap Scan\n")
def nmap_scan(ip, options):
parsed = None
nmproc = NmapProcess(ip, options)
rc = nmproc.run()
if rc != 0:
print("nmap scan failed: {0}".format(nmproc.stderr))
try:
parsed = NmapParser.parse(nmproc.stdout)
except NmapParserException as e:
print("Exception raised while parsing scan: {0}".format(e.msg))
return parsed
#Function - Display Nmap scan results
def show_scan(nmap_report):
for host in nmap_report.hosts:
if len(host.hostnames):
tmp_host = host.hostnames.pop()
else:
tmp_host = host.address
print("Host is [ %s ]\n" % str.upper(host.status))
print(" PORT STATE SERVICE")
for serv in host.services:
pserv = "{0:>5s}/{1:3s} {2:12s} {3}".format(
str(serv.port),
serv.protocol,
serv.state,
serv.service)
if len(serv.banner):
pserv += " ({0})".format(serv.banner)
print(pserv)
#Function - Define output text file name & write to file
def createFile(dest):
name = "Enumerator-Results.txt"
if not(path.isfile(dest+name)):
f = open(dest+name,"a+")
f.write(show_scan(report))
f.close()
if __name__ == "__main__":
report = nmap_scan(ip, "-sV")
if report:
destination = "/root/Desktop/"
createFile(destination)
show_scan(report)
print "\nReport Complete!"
else:
print("No results returned")
You're using print statements in your show_scan() function. Instead try passing the file reference to show_scan() and replacing the print() calls with f.write() calls. This would save to file everything you're currently printing to the terminal.
Alternatively you could just change your code so that the show_scan is separate from the f.write().
ie change
f.write(show_scan(report))
to
f.write(report)
It depends on whether you want to save the raw output or what you're printing to the screen.
Also you will need to pass the reference of the report to createFile so that it has the report to print ie
createFile(destination, report)
Just make sure you are always calling f.write() with a string as its parameter.
#Function - Define output text file name & write to file
def createFile(dest, report):
name = "Enumerator-Results.txt"
if not(path.isfile(dest+name)):
f = open(dest+name,"a+")
f.write(report)
f.close()
if __name__ == "__main__":
report = nmap_scan(ip, "-sV")
if report:
destination = "/root/Desktop/"
createFile(destination, report)
show_scan(report)
print "\nReport Complete!"
else:
print("No results returned")

Categories

Resources