rpa-config 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ Metadata-Version: 2.1
2
+ Name: rpa_config
3
+ Version: 1.0.0
@@ -0,0 +1,3 @@
1
+ Metadata-Version: 2.1
2
+ Name: rpa_config
3
+ Version: 1.0.0
@@ -0,0 +1,6 @@
1
+ rpa_config.py
2
+ setup.py
3
+ rpa_config.egg-info/PKG-INFO
4
+ rpa_config.egg-info/SOURCES.txt
5
+ rpa_config.egg-info/dependency_links.txt
6
+ rpa_config.egg-info/top_level.txt
@@ -0,0 +1 @@
1
+ rpa_config
@@ -0,0 +1,347 @@
1
+ # 2023/10/16 빌드
2
+ # 2023/12/27 셀레니움 세이프브라우징 해제 옵션 추가
3
+ # 2024/08/22 Teams 채팅 메시지 함수 추가
4
+
5
+ from myinfo import *
6
+ from colorama import init, Back, Fore, Style
7
+ from selenium import webdriver
8
+ from selenium.webdriver.common.by import By
9
+ from selenium.webdriver.common.alert import Alert
10
+ from selenium.webdriver.support import expected_conditions as EC
11
+ from selenium.webdriver.support.ui import WebDriverWait
12
+ from selenium.webdriver.chrome.options import Options
13
+ from selenium.common.exceptions import NoAlertPresentException, TimeoutException
14
+ from selenium.webdriver.support.ui import Select
15
+ from selenium.webdriver.common.keys import Keys
16
+ from datetime import datetime
17
+ from time import sleep
18
+ import pytesseract
19
+ import shutil
20
+ import os
21
+ import sys
22
+ import pyperclip
23
+ import requests
24
+ import json
25
+
26
+ # colorama 초기화
27
+ init(autoreset=True)
28
+
29
+ # 날짜
30
+ now = datetime.now()
31
+ today = datetime.today().strftime('%Y-%m-%d')
32
+ date_mdhm = now.strftime('%m%d%H%M')
33
+ temp_folder = 'c:/rpa_temp/'
34
+
35
+ # temp_folder 초기화
36
+ if os.path.isdir(temp_folder) :
37
+ for file in os.listdir(temp_folder):
38
+ try:
39
+ shutil.rmtree(temp_folder)
40
+ except Exception as e:
41
+ pass
42
+
43
+ if not os.path.exists(temp_folder):
44
+ os.makedirs(temp_folder)
45
+
46
+ # 확인 팝업 처리
47
+ def handle_alert(driver):
48
+ while True:
49
+ try:
50
+ alert = driver.switch_to.alert
51
+ alert.accept()
52
+ break
53
+ except:
54
+ sleep(1)
55
+
56
+ # 로딩 처리
57
+ def handle_loading(driver):
58
+ while True:
59
+ try:
60
+ # 얼럿이 있는지 먼저 확인
61
+ alert = driver.switch_to.alert
62
+ # 얼럿이 존재할 경우 아무 작업도 하지 않음
63
+ break # 얼럿이 있어도 계속 대기
64
+ except NoAlertPresentException:
65
+ # 얼럿이 없을 경우 로딩 요소가 더 이상 존재하지 않을 때까지 대기
66
+ try:
67
+ WebDriverWait(driver, 1).until_not(EC.presence_of_element_located((By.ID, 'loading')))
68
+ sleep(1)
69
+ break
70
+ except TimeoutException:
71
+ # 로딩이 계속 진행 중일 경우 계속 대기
72
+ continue
73
+
74
+ # 로그 타임 처리
75
+ def current_time():
76
+ now = datetime.now()
77
+ time_str = now.strftime("%Y-%m-%d %H:%M:%S")
78
+ time_list = time_str.split(" ")
79
+ time_str = "[" + time_list[0] + " " + time_list[1] + "]"
80
+ return time_str
81
+
82
+ # 크롬 실행
83
+ def create_webbrowser():
84
+ options = Options()
85
+ options.add_argument("--start-maximized")
86
+ options.add_argument("--disable-features=InsecureDownloadWarnings")
87
+ # options.add_argument("--headless")
88
+ options.add_experimental_option('detach', True) # 브라우저 바로 닫힘 방지
89
+ options.add_experimental_option('excludeSwitches', ['enable-logging']) # 불필요한 메시지 제거
90
+ options.add_experimental_option('prefs', {'download.default_directory':r'C:\rpa_temp' , 'safebrowsing.enabled': 'False'})
91
+ driver = webdriver.Chrome(options=options)
92
+
93
+ return driver
94
+
95
+ # sdp url 처리
96
+ def get_text_after_pattern(pattern):
97
+ patterns = {
98
+ "PRD": "",
99
+ "QA": "qt-",
100
+ "QA2": "qt2-",
101
+ }
102
+ if pattern in patterns:
103
+ return patterns[pattern]
104
+ return None
105
+
106
+
107
+ # SDP 자동 로그인
108
+ def sdp_login(target_server):
109
+ server_url = get_text_after_pattern(target_server)
110
+ url = f'http://{server_url}kic.smartdesk.lge.com/admin/main.lge'
111
+ if target_server == 'PRD':
112
+ print(f'[RPA] 운영 서버에 {EPID} 계정으로 로그인 합니다.')
113
+ options = Options()
114
+ options.add_argument("--start-maximized")
115
+ options.add_argument("--disable-features=InsecureDownloadWarnings")
116
+ options.add_experimental_option('detach', True) # 브라우저 바로 닫힘 방지
117
+ options.add_experimental_option('excludeSwitches', ['enable-logging']) # 불필요한 메시지 제거
118
+ options.add_experimental_option('prefs', {'download.default_directory':r'C:\rpa_temp' , 'safebrowsing.enabled': 'False'})
119
+ driver = webdriver.Chrome(options=options)
120
+ driver.get(url)
121
+
122
+ driver.implicitly_wait(2)
123
+ driver.find_element(By.ID,'USER').send_keys(EPID)
124
+ driver.find_element(By.ID,'LDAPPASSWORD').send_keys(EPPW)
125
+ driver.implicitly_wait(2)
126
+ driver.find_element(By.ID,'OTP').click()
127
+
128
+ driver.switch_to.window(driver.window_handles[1])
129
+
130
+ driver.find_element(By.ID,'pw').send_keys(EPPW)
131
+ driver.find_element(By.ID,'myButton').click()
132
+
133
+ sleep(1)
134
+ driver.switch_to.window(driver.window_handles[1])
135
+ driver.find_element(By.XPATH,'//*[@id="TA_01"]/div[4]/div[1]').click()
136
+ driver.switch_to.window(driver.window_handles[2])
137
+
138
+ while True:
139
+ try:
140
+ driver.refresh()
141
+ element1 = driver.find_element(By.ID,'photo_imageK')
142
+ element_png = element1.screenshot_as_png
143
+ with open("otpimg.png", "wb") as file: file.write(element_png)
144
+ pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract'
145
+ otpimg = pytesseract.image_to_string(r'otpimg.png')
146
+ driver.find_element(By.ID,'bizidK').send_keys(XID)
147
+ driver.find_element(By.ID,'pcodeK').send_keys(BDAY)
148
+ driver.find_element(By.ID,'answerK').send_keys(otpimg.replace(" ",""))
149
+ driver.find_element(By.XPATH,'//*[@id="form1"]/div[1]/table/tbody/tr[8]/td/input[1]').click()
150
+ sleep(2)
151
+ try:
152
+ sleep(1)
153
+ result = Alert(driver)
154
+ print("[RPA] OTP 입력 오류, 재시도 합니다.")
155
+ result.accept()
156
+ except:
157
+ print("[RPA] OTP 정상 입력.")
158
+ break
159
+ except:
160
+ pass
161
+
162
+ sleep(1)
163
+ driver.switch_to.window(driver.window_handles[3])
164
+ OTPD = driver.find_element(By.XPATH,'//*[@id="loadingK"]/b').text
165
+ driver.close()
166
+ driver.switch_to.window(driver.window_handles[2])
167
+ driver.close()
168
+ driver.switch_to.window(driver.window_handles[1])
169
+ driver.close()
170
+ driver.switch_to.window(driver.window_handles[0])
171
+ driver.find_element(By.ID,'OTPPASSWORD').send_keys(OTPD)
172
+ driver.find_element(By.ID,'loginSsobtn').click()
173
+ driver.get(url)
174
+ return driver
175
+
176
+ elif target_server == 'QA':
177
+ print(f'[RPA] QA 서버에 {QAID} 계정으로 로그인 합니다.')
178
+ server_url = get_text_after_pattern(target_server)
179
+ url = f'http://{server_url}kic.smartdesk.lge.com/admin/main.lge'
180
+ options = Options()
181
+ options.add_argument("--start-maximized")
182
+ options.add_argument("--disable-features=InsecureDownloadWarnings")
183
+ options.add_experimental_option('detach', True) # 브라우저 바로 닫힘 방지
184
+ options.add_experimental_option('excludeSwitches', ['enable-logging']) # 불필요한 메시지 제거
185
+ options.add_experimental_option('prefs', {'download.default_directory':r'C:\rpa_temp' , 'safebrowsing.enabled': 'False'})
186
+ driver = webdriver.Chrome(options=options)
187
+ driver.get(url)
188
+ handle_alert(driver)
189
+ driver.find_element(By.ID,'USER').send_keys(QAID)
190
+ driver.find_element(By.ID,'LDAPPASSWORD').send_keys(QAPW)
191
+ driver.find_element(By.ID,'loginSsobtn').click()
192
+ # 비밀번호 변경 메시지 처리
193
+ try:
194
+ WebDriverWait(driver, 3).until(EC.alert_is_present())
195
+ alert = driver.switch_to.alert
196
+ alert.dismiss()
197
+ except:
198
+ pass
199
+
200
+ pyperclip.copy(url)
201
+ print('[RPA] QA서버 http 접근을 위해, 브라우저에서 url 을 직접 입력해 주세요 (url 이 복사 되었습니다.)')
202
+
203
+ while True :
204
+ if url in driver.current_url:
205
+ break
206
+ else:
207
+ print(f'[RPA] url 입력 까지 대기 합니다.')
208
+ print(f'[RPA] 현제 페이지 : {driver.current_url}')
209
+ sleep(3)
210
+ return driver
211
+
212
+
213
+
214
+ else :
215
+ print(f'[RPA] QA2 서버에 {QAID} 계정으로 로그인 합니다.')
216
+ server_url = get_text_after_pattern(target_server)
217
+ url = f'http://{server_url}kic.smartdesk.lge.com/admin/main.lge'
218
+ options = Options()
219
+ options.add_argument("--start-maximized")
220
+ options.add_argument("--disable-features=InsecureDownloadWarnings")
221
+ options.add_experimental_option('detach', True) # 브라우저 바로 닫힘 방지
222
+ options.add_experimental_option('excludeSwitches', ['enable-logging']) # 불필요한 메시지 제거
223
+ options.add_experimental_option('prefs', {'download.default_directory':r'C:\rpa_temp' , 'safebrowsing.enabled': 'False'})
224
+ driver = webdriver.Chrome(options=options)
225
+ driver.get(url)
226
+ handle_alert(driver)
227
+ driver.find_element(By.ID,'USER').send_keys(QAID)
228
+ driver.find_element(By.ID,'LDAPPASSWORD').send_keys(QAPW)
229
+ driver.find_element(By.ID,'loginSsobtn').click()
230
+ # 비밀번호 변경 메시지 처리
231
+ try:
232
+ WebDriverWait(driver, 3).until(EC.alert_is_present())
233
+ alert = driver.switch_to.alert
234
+ alert.dismiss()
235
+ except:
236
+ pass
237
+ driver.get(url)
238
+ return driver
239
+
240
+ # 화면 보호기 방지
241
+ import ctypes
242
+ ES_CONTINUOUS = 0x80000000
243
+ ES_DISPLAY_REQUIRED = 0x00000002
244
+ SetThreadExecutionState = ctypes.windll.kernel32.SetThreadExecutionState
245
+ # 화면 보호기 방지 설정
246
+ def prevent_screensaver():
247
+ return SetThreadExecutionState(ES_CONTINUOUS | ES_DISPLAY_REQUIRED)
248
+ # 화면 보호기 방지 해제 설정
249
+ def allow_screensaver():
250
+ return SetThreadExecutionState(ES_CONTINUOUS)
251
+
252
+ # 오브 젝트 조작
253
+ def find_e(driver, locator, action, value=None, index=None, timeout=10, max_tries=3):
254
+ for i in range(max_tries):
255
+ try:
256
+ elements = WebDriverWait(driver, timeout).until(EC.presence_of_all_elements_located(locator))
257
+ if index is not None:
258
+ element = elements[index]
259
+ else:
260
+ element = elements[0]
261
+ if action == 'click':
262
+ element.click()
263
+ elif action == 'send_keys':
264
+ element.send_keys(value)
265
+ elif action == 'clear':
266
+ element.clear()
267
+ else:
268
+ raise ValueError(f"Unsupported action '{action}'")
269
+ break
270
+ except TimeoutException:
271
+ print(current_time(),f"Timeout waiting for element located by {locator}, attempt {i+1} of {max_tries}")
272
+ else:
273
+ print(current_time(),f"Failed to locate element after {max_tries} tries")
274
+
275
+ def rpa_progress(status):
276
+ # 현재 실행 중인 파이썬 파일명을 얻습니다.
277
+ file_path = sys.argv[0]
278
+
279
+ # 파일명만 추출합니다.
280
+ file_name = os.path.basename(file_path)
281
+
282
+ # 파일명 + '시작'을 출력합니다.
283
+ print('\n[RPA] ' + current_time() + ' ' + file_name + ' ' + status)
284
+
285
+ return file_name
286
+
287
+
288
+ import ctypes
289
+ import os
290
+
291
+ ES_CONTINUOUS = 0x80000000
292
+ ES_DISPLAY_REQUIRED = 0x00000002
293
+ SetThreadExecutionState = ctypes.windll.kernel32.SetThreadExecutionState
294
+
295
+ # 화면 보호기 방지 설정
296
+ def prevent_screensaver():
297
+ return SetThreadExecutionState(ES_CONTINUOUS | ES_DISPLAY_REQUIRED)
298
+
299
+ # 화면 보호기 방지 해제 설정
300
+ def allow_screensaver():
301
+ return SetThreadExecutionState(ES_CONTINUOUS)
302
+
303
+ # 디스플레이 끄기 및 절전 모드 비활성화
304
+ def disable_power_settings():
305
+ os.system("powercfg -change -monitor-timeout-ac 0")
306
+ os.system("powercfg -change -standby-timeout-ac 0")
307
+ os.system("powercfg -change -hibernate-timeout-ac 0")
308
+
309
+ # 전원 설정 복구
310
+ def enable_power_settings(monitor_timeout, standby_timeout, hibernate_timeout):
311
+ os.system(f"powercfg -change -monitor-timeout-ac {monitor_timeout}")
312
+ os.system(f"powercfg -change -standby-timeout-ac {standby_timeout}")
313
+ os.system(f"powercfg -change -hibernate-timeout-ac {hibernate_timeout}")
314
+
315
+ # HTTP POST 요청을 보내는 함수 정의
316
+ def print_webhook(webhook_url, webhook_data, n_print=None):
317
+ # 전송할 데이터 구성
318
+ data = {
319
+ "type": "message",
320
+ "attachments": [
321
+ {
322
+ "contentType": "application/vnd.microsoft.card.adaptive",
323
+ "content": {
324
+ "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
325
+ "type": "AdaptiveCard",
326
+ "version": "1.0",
327
+ "body": [
328
+ {
329
+ "type": "TextBlock",
330
+ "text": '🕹 ' + webhook_data,
331
+ "wrap": True
332
+ }
333
+ ]
334
+ }
335
+ }
336
+ ]
337
+ }
338
+
339
+ # HTTP POST 요청 보내기
340
+ response = requests.post(webhook_url, headers={"Content-Type": "application/json"}, data=json.dumps(data))
341
+
342
+ # n_print가 없을 때만 print 호출
343
+ if not n_print:
344
+ print(webhook_data)
345
+
346
+ return response
347
+
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,8 @@
1
+ from setuptools import setup
2
+
3
+ setup(
4
+ name="rpa_config",
5
+ version="1.0.0",
6
+ py_modules=["rpa_config"],
7
+ install_requires=[],
8
+ )