Compare commits
11 commits
Author | SHA1 | Date | |
---|---|---|---|
84d1b0cb59 | |||
9389441262 | |||
45d6b9f3c8 | |||
45b1b767ac | |||
8658955998 | |||
8ade781d4b | |||
cf47a5b2ad | |||
c08afa08c3 | |||
5a709197e7 | |||
487dfbd96d | |||
7fc3ca701c |
11 changed files with 146 additions and 355 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
@ -165,3 +165,4 @@ db/
|
||||||
test.py
|
test.py
|
||||||
data/
|
data/
|
||||||
export/
|
export/
|
||||||
|
temp/
|
44
dislocker.py
44
dislocker.py
|
@ -48,7 +48,10 @@ class DL():
|
||||||
"search_frequency": 1,
|
"search_frequency": 1,
|
||||||
"allowable_time": 180,
|
"allowable_time": 180,
|
||||||
"fstop_time": "21:00:00"
|
"fstop_time": "21:00:00"
|
||||||
}
|
},
|
||||||
|
"preset_games": ["TEST1", "TEST2", "TEST3", "TEST4", "TEST5"],
|
||||||
|
"admin_user_id": "TYPE HERE CHANNEL ID (YOU MUST USE INT !!!!)",
|
||||||
|
"debug": False
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -74,6 +77,7 @@ class DL():
|
||||||
cursor = self.db.cursor()
|
cursor = self.db.cursor()
|
||||||
|
|
||||||
self.pc_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
self.pc_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
||||||
|
self.preset_games = self.server_config["bot"]["preset_games"]
|
||||||
|
|
||||||
cursor.execute("SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'club_member')")
|
cursor.execute("SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'club_member')")
|
||||||
find_club_member_table = cursor.fetchall()
|
find_club_member_table = cursor.fetchall()
|
||||||
|
@ -615,6 +619,8 @@ class Bot(discord.Client):
|
||||||
for i in range(1, 11):
|
for i in range(1, 11):
|
||||||
device_register_button = discord.ui.Button(style=discord.ButtonStyle.primary, label=f"{i}", custom_id=f"deviceregister_{str(pc_number)}_{i}")
|
device_register_button = discord.ui.Button(style=discord.ButtonStyle.primary, label=f"{i}", custom_id=f"deviceregister_{str(pc_number)}_{i}")
|
||||||
device_register_view.add_item(device_register_button)
|
device_register_view.add_item(device_register_button)
|
||||||
|
device_own_register_button = discord.ui.Button(style=discord.ButtonStyle.primary, label="自前", custom_id=f"deviceregister_{str(pc_number)}_own")
|
||||||
|
device_register_view.add_item(device_own_register_button)
|
||||||
|
|
||||||
await interaction.response.send_message(f"# :keyboard: デバイス番号を選んでください!\n>>> # PC番号 | {str(pc_number)}", view=device_register_view, ephemeral=True)
|
await interaction.response.send_message(f"# :keyboard: デバイス番号を選んでください!\n>>> # PC番号 | {str(pc_number)}", view=device_register_view, ephemeral=True)
|
||||||
|
|
||||||
|
@ -622,6 +628,9 @@ class Bot(discord.Client):
|
||||||
pc_number = custom_id_split[1]
|
pc_number = custom_id_split[1]
|
||||||
device_number = custom_id_split[2]
|
device_number = custom_id_split[2]
|
||||||
reason_register_view = View(timeout=15)
|
reason_register_view = View(timeout=15)
|
||||||
|
for i in dislocker.preset_games:
|
||||||
|
reason_quick_button = reason_button = discord.ui.Button(style=discord.ButtonStyle.primary, label=f"{str(i)}", custom_id=f"reasonregister_{str(pc_number)}_{str(device_number)}_quick_{str(i)}")
|
||||||
|
reason_register_view.add_item(reason_quick_button)
|
||||||
reason_button = discord.ui.Button(style=discord.ButtonStyle.primary, label="使用目的を入力する", custom_id=f"reasonregister_{str(pc_number)}_{str(device_number)}")
|
reason_button = discord.ui.Button(style=discord.ButtonStyle.primary, label="使用目的を入力する", custom_id=f"reasonregister_{str(pc_number)}_{str(device_number)}")
|
||||||
reason_register_view.add_item(reason_button)
|
reason_register_view.add_item(reason_button)
|
||||||
|
|
||||||
|
@ -630,6 +639,33 @@ class Bot(discord.Client):
|
||||||
elif custom_id_split[0] == "reasonregister":
|
elif custom_id_split[0] == "reasonregister":
|
||||||
pc_number = custom_id_split[1]
|
pc_number = custom_id_split[1]
|
||||||
device_number = custom_id_split[2]
|
device_number = custom_id_split[2]
|
||||||
|
|
||||||
|
if len(custom_id_split) >= 4:
|
||||||
|
if custom_id_split[3] == "quick":
|
||||||
|
reason = custom_id_split[4]
|
||||||
|
if device_number == "own":
|
||||||
|
device_number = 0
|
||||||
|
else:
|
||||||
|
device_number = custom_id_split[2]
|
||||||
|
|
||||||
|
register = bot.register(user_id=interaction.user.id, name=interaction.user.name, display_name=interaction.user.display_name, pc_number=pc_number, device_number=device_number, detail=reason)
|
||||||
|
print(register["result"])
|
||||||
|
|
||||||
|
if register["result"] == "ok":
|
||||||
|
await interaction.response.send_message(f":white_check_mark: 使用が開始されました。\n>>> # パスワード | {register["password"]}\n## PC番号 | {pc_number}\n## デバイス番号 | {device_number}\n## 使用目的 | {reason}", ephemeral=True)
|
||||||
|
await bot.get_channel(dislocker.server_config["bot"]["log_channel_id"]).send(f':white_check_mark: {register["name"]} さんがPC {pc_number} の使用を開始しました。')
|
||||||
|
elif register["result"] == "pc_already_in_use_by_you":
|
||||||
|
await interaction.response.send_message(f"# :exploding_head: あなたはPCをもう使用されているようです。\n使用状態を解除するには 終了ボタン で使用終了をお知らせください。\n>>> # PC番号 | {register["pc_number"]}\n# デバイス番号 | {register["device_number"]}\n# 使用開始時刻 | {register["start_time"]}\n# 使用目的 | {register["detail"]}", ephemeral=True)
|
||||||
|
elif register["result"] == "pc_already_in_use_by_other":
|
||||||
|
await interaction.response.send_message(f"# :man_gesturing_no: そのPCは他のメンバーによって使用されています。\n別のPC番号を指定して、再度お試しください。", ephemeral=True)
|
||||||
|
elif register["result"] == "user_data_not_found":
|
||||||
|
await interaction.response.send_message("# :dizzy_face: ユーザーとして登録されていないようです。\n最初にサーバーで登録を行ってください。", ephemeral=True)
|
||||||
|
else:
|
||||||
|
await interaction.response.send_message("# :skull_crossbones: 登録できませんでした。\n内部エラーが発生しています。", ephemeral=True)
|
||||||
|
else:
|
||||||
|
reason_input_form = Reason(title="Dislocker | 登録", pc_number=str(pc_number), device_number=str(device_number))
|
||||||
|
await interaction.response.send_modal(reason_input_form)
|
||||||
|
else:
|
||||||
reason_input_form = Reason(title="Dislocker | 登録", pc_number=str(pc_number), device_number=str(device_number))
|
reason_input_form = Reason(title="Dislocker | 登録", pc_number=str(pc_number), device_number=str(device_number))
|
||||||
await interaction.response.send_modal(reason_input_form)
|
await interaction.response.send_modal(reason_input_form)
|
||||||
|
|
||||||
|
@ -771,6 +807,12 @@ class Reason(Modal):
|
||||||
custom_id_split = custom_id.split("_")
|
custom_id_split = custom_id.split("_")
|
||||||
pc_number = custom_id_split[1]
|
pc_number = custom_id_split[1]
|
||||||
device_number = custom_id_split[2]
|
device_number = custom_id_split[2]
|
||||||
|
|
||||||
|
if device_number == "own":
|
||||||
|
device_number = 0
|
||||||
|
else:
|
||||||
|
device_number = custom_id_split[2]
|
||||||
|
|
||||||
register = bot.register(user_id=interaction.user.id, name=interaction.user.name, display_name=interaction.user.display_name, pc_number=pc_number, device_number=device_number, detail=self.reason_input_form.value)
|
register = bot.register(user_id=interaction.user.id, name=interaction.user.name, display_name=interaction.user.display_name, pc_number=pc_number, device_number=device_number, detail=self.reason_input_form.value)
|
||||||
print(register["result"])
|
print(register["result"])
|
||||||
|
|
||||||
|
|
|
@ -11,9 +11,10 @@ import string
|
||||||
import random
|
import random
|
||||||
import tkinter
|
import tkinter
|
||||||
import threading
|
import threading
|
||||||
import signal
|
|
||||||
import sys
|
import sys
|
||||||
import shutil
|
import shutil
|
||||||
|
import time
|
||||||
|
|
||||||
|
|
||||||
app_name = "Dislocker"
|
app_name = "Dislocker"
|
||||||
dislocker_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
|
dislocker_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
|
||||||
|
@ -32,7 +33,8 @@ if not os.path.isfile(client_config_path):
|
||||||
"auth_host_url": "http://localhost",
|
"auth_host_url": "http://localhost",
|
||||||
"pc_number": 1,
|
"pc_number": 1,
|
||||||
"master_password_hash": "",
|
"master_password_hash": "",
|
||||||
"testing": 0
|
"testing": 0,
|
||||||
|
"eraser": 1
|
||||||
}
|
}
|
||||||
|
|
||||||
elif os.path.isfile(client_config_path):
|
elif os.path.isfile(client_config_path):
|
||||||
|
@ -98,28 +100,37 @@ class App(customtkinter.CTk):
|
||||||
print(f"エラー: 指定されたディレクトリ {dir_path} が存在しません。")
|
print(f"エラー: 指定されたディレクトリ {dir_path} が存在しません。")
|
||||||
return 1
|
return 1
|
||||||
|
|
||||||
|
i = 0
|
||||||
|
i_max = 10
|
||||||
|
result = 1
|
||||||
|
while i != i_max:
|
||||||
|
i += 1
|
||||||
try:
|
try:
|
||||||
# プロセスの終了
|
# プロセスの終了
|
||||||
subprocess.run(['taskkill', '/f', '/t', '/im', process_name])
|
subprocess.run(['taskkill', '/f', '/t', '/im', process_name])
|
||||||
print(f"{process_name} を終了しました。")
|
print(f"{process_name} を終了しました。")
|
||||||
|
time.sleep(0.1)
|
||||||
# ディレクトリの削除
|
# ディレクトリの削除
|
||||||
shutil.rmtree(dir_path)
|
shutil.rmtree(dir_path)
|
||||||
|
if os.path.isdir(dir_path):
|
||||||
|
pass
|
||||||
|
else:
|
||||||
print(f"{dir_path} を削除しました。")
|
print(f"{dir_path} を削除しました。")
|
||||||
|
result = 0
|
||||||
|
i = i_max
|
||||||
|
|
||||||
return 0
|
|
||||||
except subprocess.CalledProcessError as e:
|
except subprocess.CalledProcessError as e:
|
||||||
print(f"プロセス終了エラー: {e}")
|
print(f"プロセス終了エラー: {e}")
|
||||||
return 1
|
|
||||||
except PermissionError as e:
|
except PermissionError as e:
|
||||||
print(f"権限エラー: {e}")
|
print(f"権限エラー: {e}")
|
||||||
return 1
|
|
||||||
except Exception as error:
|
except Exception as e:
|
||||||
print("エラーが発生しました。\nエラー内容:")
|
print("エラーが発生しました。\nエラー内容:")
|
||||||
print(f"エラータイプ: {error.__class__.__name__}")
|
print(f"エラータイプ: {e.__class__.__name__}")
|
||||||
print(f"エラー引数: {error.args}")
|
print(f"エラー引数: {e.args}")
|
||||||
print(f"エラーメッセージ: {str(error)}")
|
print(f"エラーメッセージ: {str(e)}")
|
||||||
return 1
|
|
||||||
|
|
||||||
def block_key(self):
|
def block_key(self):
|
||||||
block_keys = ['ctrl', 'alt', 'windows', 'shift', 'delete']
|
block_keys = ['ctrl', 'alt', 'windows', 'shift', 'delete']
|
||||||
|
@ -350,16 +361,63 @@ class Help(customtkinter.CTkToplevel):
|
||||||
def handler_close(self):
|
def handler_close(self):
|
||||||
self.destroy()
|
self.destroy()
|
||||||
|
|
||||||
class Monitor():
|
|
||||||
|
class Stop():
|
||||||
def __init__(self) -> None:
|
def __init__(self) -> None:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def start(self):
|
def run(self):
|
||||||
monitor_thread = threading.Thread(target=self.run)
|
stop_thread = threading.Thread(target=self.stop)
|
||||||
monitor_thread.start()
|
stop_thread.run()
|
||||||
|
|
||||||
def signal_handler(self):
|
def delete_appdata(self, **kwargs):
|
||||||
|
process_name = kwargs["process_name"]
|
||||||
|
dir_path = kwargs["dir_path"]
|
||||||
|
|
||||||
|
if not os.path.exists(dir_path):
|
||||||
|
print(f"エラー: 指定されたディレクトリ {dir_path} が存在しません。")
|
||||||
|
return 1
|
||||||
|
|
||||||
|
i = 0
|
||||||
|
i_max = 10
|
||||||
|
result = 1
|
||||||
|
while i != i_max:
|
||||||
|
i += 1
|
||||||
|
try:
|
||||||
|
# プロセスの終了
|
||||||
|
subprocess.run(['taskkill', '/f', '/t', '/im', process_name])
|
||||||
|
print(f"{process_name} を終了しました。")
|
||||||
|
time.sleep(0.1)
|
||||||
|
# ディレクトリの削除
|
||||||
|
shutil.rmtree(dir_path)
|
||||||
|
if os.path.isdir(dir_path):
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
print(f"{dir_path} を削除しました。")
|
||||||
|
result = 0
|
||||||
|
i = i_max
|
||||||
|
|
||||||
|
except subprocess.CalledProcessError as e:
|
||||||
|
print(f"プロセス終了エラー: {e}")
|
||||||
|
|
||||||
|
except PermissionError as e:
|
||||||
|
print(f"権限エラー: {e}")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print("エラーが発生しました。\nエラー内容:")
|
||||||
|
print(f"エラータイプ: {e.__class__.__name__}")
|
||||||
|
print(f"エラー引数: {e.args}")
|
||||||
|
print(f"エラーメッセージ: {str(e)}")
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def shutdown(self):
|
||||||
|
shutdown_command = subprocess.run(['shutdown', '/s', '/t', '1'])
|
||||||
|
|
||||||
|
def stop(self):
|
||||||
print("停止処理を実行。")
|
print("停止処理を実行。")
|
||||||
|
if client_config["eraser"] == 1:
|
||||||
appdata_local = os.path.expandvars("%LOCALAPPDATA%")
|
appdata_local = os.path.expandvars("%LOCALAPPDATA%")
|
||||||
appdata_roaming = os.path.expandvars("%APPDATA%")
|
appdata_roaming = os.path.expandvars("%APPDATA%")
|
||||||
epic_del = app.delete_appdata(process_name="EpicGamesLauncher.exe", dir_path=f"{appdata_local}\\EpicGamesLauncher\\Saved")
|
epic_del = app.delete_appdata(process_name="EpicGamesLauncher.exe", dir_path=f"{appdata_local}\\EpicGamesLauncher\\Saved")
|
||||||
|
@ -368,6 +426,8 @@ class Monitor():
|
||||||
steam_del = app.delete_appdata(process_name="steam.exe", dir_path=f"{appdata_local}\\Steam")
|
steam_del = app.delete_appdata(process_name="steam.exe", dir_path=f"{appdata_local}\\Steam")
|
||||||
ea_del = app.delete_appdata(process_name="EADesktop.exe", dir_path=f"{appdata_local}\\Electronic Arts")
|
ea_del = app.delete_appdata(process_name="EADesktop.exe", dir_path=f"{appdata_local}\\Electronic Arts")
|
||||||
riot_del = app.delete_appdata(process_name="RiotClientServices.exe", dir_path=f"{appdata_local}\\Riot Games\\Riot Client")
|
riot_del = app.delete_appdata(process_name="RiotClientServices.exe", dir_path=f"{appdata_local}\\Riot Games\\Riot Client")
|
||||||
|
else:
|
||||||
|
print("削除処理をスキップ。")
|
||||||
stop_url = client_config["auth_host_url"] + "/stop"
|
stop_url = client_config["auth_host_url"] + "/stop"
|
||||||
stop_json = {
|
stop_json = {
|
||||||
"pc_number": int(client_config["pc_number"])
|
"pc_number": int(client_config["pc_number"])
|
||||||
|
@ -378,20 +438,11 @@ class Monitor():
|
||||||
print("停止処理は成功しました。")
|
print("停止処理は成功しました。")
|
||||||
else:
|
else:
|
||||||
print("内部エラーにより停止処理に失敗しました。")
|
print("内部エラーにより停止処理に失敗しました。")
|
||||||
result_msgbox = tkinter.messagebox.showwarning(title=f"{app_name} | エラー", message=f"内部エラーにより停止処理に失敗しました。\nDiscordサーバーの指示に従って、停止処理を自身で行ってください。")
|
|
||||||
except:
|
except:
|
||||||
print("ネットワークエラーにより停止処理に失敗しました。")
|
print("ネットワークエラーにより停止処理に失敗しました。")
|
||||||
result_msgbox = tkinter.messagebox.showwarning(title=f"{app_name} | エラー", message=f"ネットワークエラーにより停止処理に失敗しました。\nDiscordサーバーの指示に従って、停止処理を自身で行ってください。")
|
|
||||||
finally:
|
finally:
|
||||||
self.shutdown()
|
self.shutdown()
|
||||||
|
|
||||||
def shutdown(self):
|
|
||||||
shutdown_command = subprocess.run(['shutdown', '/s', '/t', '1'])
|
|
||||||
|
|
||||||
|
|
||||||
def run(self):
|
|
||||||
signal.signal(signal.SIGTERM, self.signal_handler)
|
|
||||||
|
|
||||||
|
|
||||||
def master_password_gen():
|
def master_password_gen():
|
||||||
numbers = string.digits # (1)
|
numbers = string.digits # (1)
|
||||||
|
@ -407,13 +458,12 @@ if __name__ == '__main__':
|
||||||
if args[1] == "stop":
|
if args[1] == "stop":
|
||||||
init_result = init()
|
init_result = init()
|
||||||
if init_result == 1:
|
if init_result == 1:
|
||||||
warning_msgbox = tkinter.messagebox.showwarning(title=f"{app_name} | 多重起動エラー", message=f"もう終了処理を行っています。\nPCがシャットダウンするまで、もう少しお待ちください。")
|
print("多重起動エラー。")
|
||||||
elif init_result == 2:
|
elif init_result == 2:
|
||||||
pass
|
pass
|
||||||
else:
|
else:
|
||||||
app = App()
|
stop = Stop()
|
||||||
monitor = Monitor()
|
stop.run()
|
||||||
monitor.signal_handler()
|
|
||||||
elif args[1] == "setup":
|
elif args[1] == "setup":
|
||||||
init_result = init(pc_number=args[2])
|
init_result = init(pc_number=args[2])
|
||||||
if init_result == 1:
|
if init_result == 1:
|
||||||
|
|
|
@ -1,40 +0,0 @@
|
||||||
import os
|
|
||||||
import subprocess
|
|
||||||
import shutil
|
|
||||||
|
|
||||||
def delete_appdata(**kwargs):
|
|
||||||
process_name = kwargs["process_name"]
|
|
||||||
dir_path = kwargs["dir_path"]
|
|
||||||
|
|
||||||
if not os.path.exists(dir_path):
|
|
||||||
print(f"エラー: 指定されたディレクトリ {dir_path} が存在しません。")
|
|
||||||
return 1
|
|
||||||
|
|
||||||
try:
|
|
||||||
# プロセスの終了
|
|
||||||
subprocess.run(['taskkill', '/f', '/t', '/im', process_name])
|
|
||||||
print(f"{process_name} を終了しました。")
|
|
||||||
|
|
||||||
# ディレクトリの削除
|
|
||||||
shutil.rmtree(dir_path)
|
|
||||||
print(f"{dir_path} を削除しました。")
|
|
||||||
|
|
||||||
return 0
|
|
||||||
except subprocess.CalledProcessError as e:
|
|
||||||
print(f"プロセス終了エラー: {e}")
|
|
||||||
return 1
|
|
||||||
except PermissionError as e:
|
|
||||||
print(f"権限エラー: {e}")
|
|
||||||
return 1
|
|
||||||
except Exception as error:
|
|
||||||
print("エラーが発生しました。\nエラー内容:")
|
|
||||||
print(f"エラータイプ: {error.__class__.__name__}")
|
|
||||||
print(f"エラー引数: {error.args}")
|
|
||||||
print(f"エラーメッセージ: {str(error)}")
|
|
||||||
return 1
|
|
||||||
|
|
||||||
appdata_local = os.path.expandvars("%LOCALAPPDATA%")
|
|
||||||
appdata_roaming = os.path.expandvars("%APPDATA%")
|
|
||||||
print(appdata_local, appdata_roaming)
|
|
||||||
print(f"{appdata_local}\\Steam")
|
|
||||||
steam_del = delete_appdata(process_name="steam.exe", dir_path=f"{appdata_local}\\Steam")
|
|
|
@ -1,77 +0,0 @@
|
||||||
import psycopg2
|
|
||||||
import csv
|
|
||||||
from psycopg2 import sql
|
|
||||||
from datetime import datetime
|
|
||||||
|
|
||||||
def format_datetime(value):
|
|
||||||
if isinstance(value, datetime):
|
|
||||||
return value.strftime('%Y-%m-%d %H:%M:%S')
|
|
||||||
return value
|
|
||||||
|
|
||||||
def export_table_to_csv(host, port, database, user, password, main_table, related_table, related_column, csv_file_path):
|
|
||||||
try:
|
|
||||||
# データベースに接続
|
|
||||||
conn = psycopg2.connect(
|
|
||||||
host=host,
|
|
||||||
port=port,
|
|
||||||
database=database,
|
|
||||||
user=user,
|
|
||||||
password=password
|
|
||||||
)
|
|
||||||
|
|
||||||
cur = conn.cursor()
|
|
||||||
|
|
||||||
# メインテーブルの列情報を取得(user_idを除く)
|
|
||||||
cur.execute(sql.SQL("SELECT * FROM {} LIMIT 0").format(sql.Identifier(main_table)))
|
|
||||||
main_columns = [desc[0] for desc in cur.description if desc[0] != 'member_id']
|
|
||||||
|
|
||||||
# クエリを作成(列名を明確に指定)
|
|
||||||
query = sql.SQL("""
|
|
||||||
SELECT {main_columns}, {related_table}.name
|
|
||||||
FROM {main_table}
|
|
||||||
LEFT JOIN {related_table} ON {main_table}.member_id = {related_table}.id
|
|
||||||
""").format(
|
|
||||||
main_columns=sql.SQL(', ').join([sql.SQL("{}.{}").format(sql.Identifier(main_table), sql.Identifier(col)) for col in main_columns]),
|
|
||||||
main_table=sql.Identifier(main_table),
|
|
||||||
related_table=sql.Identifier(related_table)
|
|
||||||
)
|
|
||||||
|
|
||||||
cur.execute(query)
|
|
||||||
|
|
||||||
# 列名を再構成(nameを2番目に配置)
|
|
||||||
column_names = [main_columns[0], 'name'] + main_columns[1:]
|
|
||||||
|
|
||||||
rows = cur.fetchall()
|
|
||||||
|
|
||||||
with open(csv_file_path, 'w', newline='', encoding='utf-8-sig') as csvfile:
|
|
||||||
csvwriter = csv.writer(csvfile)
|
|
||||||
csvwriter.writerow(column_names)
|
|
||||||
|
|
||||||
for row in rows:
|
|
||||||
# nameを2番目に移動
|
|
||||||
formatted_row = [format_datetime(row[0])] + [row[-1]] + [format_datetime(field) if field is not None else '' for field in row[1:-1]]
|
|
||||||
csvwriter.writerow(formatted_row)
|
|
||||||
|
|
||||||
print(f"テーブル '{main_table}' の内容を '{csv_file_path}' に出力しました。")
|
|
||||||
|
|
||||||
except (Exception, psycopg2.Error) as error:
|
|
||||||
print("エラーが発生しました:", error)
|
|
||||||
|
|
||||||
finally:
|
|
||||||
if conn:
|
|
||||||
cur.close()
|
|
||||||
conn.close()
|
|
||||||
print("データベース接続を閉じました。")
|
|
||||||
|
|
||||||
# 使用例
|
|
||||||
host = "192.168.1.220"
|
|
||||||
port = "12245"
|
|
||||||
database = "dislocker"
|
|
||||||
user = "suti7"
|
|
||||||
password = "Testing1234"
|
|
||||||
main_table = "pc_usage_history"
|
|
||||||
related_table = "club_member"
|
|
||||||
related_column = "name" # 例: 登録者の名前を表示したい場合
|
|
||||||
csv_file_path = "output.csv"
|
|
||||||
|
|
||||||
export_table_to_csv(host, port, database, user, password, main_table, related_table, related_column, csv_file_path)
|
|
22
temp/kill.py
22
temp/kill.py
|
@ -1,22 +0,0 @@
|
||||||
import wmi
|
|
||||||
import asyncio
|
|
||||||
|
|
||||||
async def watcher():
|
|
||||||
c=wmi.WMI()
|
|
||||||
cre_process_watcher=c.Win32_Process.watch_for("creation")
|
|
||||||
del_process_watcher=c.Win32_Process.watch_for("deletion")
|
|
||||||
|
|
||||||
while True:
|
|
||||||
new_cre_process=cre_process_watcher()
|
|
||||||
new_del_process=del_process_watcher()
|
|
||||||
print(new_cre_process.Caption+" has been created")
|
|
||||||
print(new_del_process.Caption+" has been deleted ")
|
|
||||||
|
|
||||||
async def main():
|
|
||||||
kill_task = asyncio.TaskGroup(watcher())
|
|
||||||
print('hello world')
|
|
||||||
await asyncio.sleep(1)
|
|
||||||
print('1sec')
|
|
||||||
await kill_task
|
|
||||||
|
|
||||||
asyncio.run(main())
|
|
|
@ -1,16 +0,0 @@
|
||||||
import random
|
|
||||||
import string
|
|
||||||
# パスワードをファイルから読み込む
|
|
||||||
|
|
||||||
with open('password.txt', 'r') as f:
|
|
||||||
secret = f.read()
|
|
||||||
|
|
||||||
check=int(input("password :"))
|
|
||||||
|
|
||||||
if check==int(secret):
|
|
||||||
print("ok")
|
|
||||||
secret=0
|
|
||||||
with open('password.txt', 'w') as file:
|
|
||||||
file.write('')
|
|
||||||
else:
|
|
||||||
print("out")
|
|
|
@ -1,9 +0,0 @@
|
||||||
import os
|
|
||||||
|
|
||||||
# PowerShellコマンドを実行する関数
|
|
||||||
def run_powershell_command(command):
|
|
||||||
# PowerShellコマンドを実行
|
|
||||||
os.system(f"powershell -Command {command}")
|
|
||||||
|
|
||||||
# 例としてGet-Dateコマンドを実行して現在の日時を取得
|
|
||||||
run_powershell_command("Get-Date")
|
|
41
temp/test.py
41
temp/test.py
|
@ -1,41 +0,0 @@
|
||||||
|
|
||||||
import discord
|
|
||||||
import string
|
|
||||||
import random
|
|
||||||
|
|
||||||
# Intentsの設定
|
|
||||||
intents = discord.Intents.default()
|
|
||||||
intents.message_content = True
|
|
||||||
|
|
||||||
# 接続に必要なオブジェクトを生成
|
|
||||||
client = discord.Client(intents=intents)
|
|
||||||
|
|
||||||
# 起動時に動作する処理
|
|
||||||
@client.event
|
|
||||||
async def on_ready():
|
|
||||||
# 起動したらターミナルにログイン通知が表示される
|
|
||||||
print('ログインしました')
|
|
||||||
|
|
||||||
# メッセージ受信時に動作する処理
|
|
||||||
@client.event
|
|
||||||
async def on_message(message):
|
|
||||||
# メッセージ送信者がBotだった場合は無視する
|
|
||||||
if message.author.bot:
|
|
||||||
return
|
|
||||||
# 「/neko」と発言したら「にゃーん」が返る処理
|
|
||||||
if message.content == "/neko":
|
|
||||||
await message.channel.send('にゃーん')
|
|
||||||
|
|
||||||
if message.content == '/password':
|
|
||||||
secret=password_generator_n(4)
|
|
||||||
await message.channel.send(str(secret))
|
|
||||||
with open('password.txt', 'a') as file:
|
|
||||||
file.write(secret)
|
|
||||||
|
|
||||||
def password_generator_n(length):
|
|
||||||
numbers = string.digits # (1)
|
|
||||||
password = ''.join(random.choice(numbers) for _ in range(length)) # (2)
|
|
||||||
return password
|
|
||||||
|
|
||||||
# Botの起動とDiscordサーバーへの接続
|
|
||||||
client.run('MTI0NzA1Mzc1NzUxOTM2NDEyNw.Gh5gIt.kz1acBMxphff9mEZLLWrEdEoVD4RJwgBW5P14o')
|
|
97
temp/xcel.py
97
temp/xcel.py
|
@ -1,97 +0,0 @@
|
||||||
import psycopg2
|
|
||||||
import csv
|
|
||||||
from psycopg2 import sql
|
|
||||||
from datetime import datetime
|
|
||||||
from openpyxl import Workbook
|
|
||||||
from openpyxl.utils import get_column_letter
|
|
||||||
|
|
||||||
def format_datetime(value):
|
|
||||||
if isinstance(value, datetime):
|
|
||||||
return value.strftime('%Y-%m-%d %H:%M:%S')
|
|
||||||
return value
|
|
||||||
|
|
||||||
def export_table_to_excel(host, port, database, user, password, main_table, related_table, excel_file_path):
|
|
||||||
try:
|
|
||||||
conn = psycopg2.connect(
|
|
||||||
host=host,
|
|
||||||
port=port,
|
|
||||||
database=database,
|
|
||||||
user=user,
|
|
||||||
password=password
|
|
||||||
)
|
|
||||||
|
|
||||||
cur = conn.cursor()
|
|
||||||
|
|
||||||
# メインテーブルの列情報を取得(member_idを除く)
|
|
||||||
cur.execute(sql.SQL("SELECT * FROM {} LIMIT 0").format(sql.Identifier(main_table)))
|
|
||||||
main_columns = [desc[0] for desc in cur.description if desc[0] != 'member_id']
|
|
||||||
|
|
||||||
# クエリを作成(列名を明確に指定)
|
|
||||||
query = sql.SQL("""
|
|
||||||
SELECT {main_columns}, {related_table}.name
|
|
||||||
FROM {main_table}
|
|
||||||
LEFT JOIN {related_table} ON {main_table}.member_id = {related_table}.id
|
|
||||||
""").format(
|
|
||||||
main_columns=sql.SQL(', ').join([sql.SQL("{}.{}").format(sql.Identifier(main_table), sql.Identifier(col)) for col in main_columns]),
|
|
||||||
main_table=sql.Identifier(main_table),
|
|
||||||
related_table=sql.Identifier(related_table)
|
|
||||||
)
|
|
||||||
|
|
||||||
cur.execute(query)
|
|
||||||
|
|
||||||
# 列名を再構成(nameを2番目に配置)
|
|
||||||
column_names = [main_columns[0], 'name'] + main_columns[1:]
|
|
||||||
|
|
||||||
rows = cur.fetchall()
|
|
||||||
|
|
||||||
# Excelワークブックを作成
|
|
||||||
wb = Workbook()
|
|
||||||
ws = wb.active
|
|
||||||
|
|
||||||
# 列名を書き込み
|
|
||||||
ws.append(column_names)
|
|
||||||
|
|
||||||
# データを書き込み
|
|
||||||
for row in rows:
|
|
||||||
# nameを2番目に移動
|
|
||||||
formatted_row = [format_datetime(row[0])] + [row[-1]] + [format_datetime(field) if field is not None else '' for field in row[1:-1]]
|
|
||||||
ws.append(formatted_row)
|
|
||||||
|
|
||||||
# 列幅を自動調整
|
|
||||||
for col in ws.columns:
|
|
||||||
max_length = 0
|
|
||||||
column = col[0].column_letter
|
|
||||||
for cell in col:
|
|
||||||
try:
|
|
||||||
if len(str(cell.value)) > max_length:
|
|
||||||
max_length = len(str(cell.value))
|
|
||||||
except:
|
|
||||||
pass
|
|
||||||
adjusted_width = (max_length + 2) * 1.2
|
|
||||||
ws.column_dimensions[column].width = adjusted_width
|
|
||||||
|
|
||||||
# Excelファイルを保存
|
|
||||||
wb.save(excel_file_path)
|
|
||||||
|
|
||||||
print(f"テーブル '{main_table}' の内容を '{excel_file_path}' に出力しました。")
|
|
||||||
|
|
||||||
except (Exception, psycopg2.Error) as error:
|
|
||||||
print("エラーが発生しました:", error)
|
|
||||||
|
|
||||||
finally:
|
|
||||||
if conn:
|
|
||||||
cur.close()
|
|
||||||
conn.close()
|
|
||||||
print("データベース接続を閉じました。")
|
|
||||||
|
|
||||||
# 使用例
|
|
||||||
host = "192.168.1.220"
|
|
||||||
port = "12245"
|
|
||||||
database = "dislocker"
|
|
||||||
user = "suti7"
|
|
||||||
password = "Testing1234"
|
|
||||||
main_table = "pc_usage_history"
|
|
||||||
related_table = "club_member"
|
|
||||||
excel_file_path = "output.xlsx"
|
|
||||||
|
|
||||||
export_table_to_excel(host, port, database, user, password, main_table, related_table, excel_file_path)
|
|
Loading…
Reference in a new issue