-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup_sqlite_simple.py
More file actions
317 lines (272 loc) · 11.6 KB
/
setup_sqlite_simple.py
File metadata and controls
317 lines (272 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
PythonAnywhere SQLite Basit Kurulum Scripti
"""
import os
import sys
import subprocess
from datetime import datetime
def print_header():
print("🚀 PythonAnywhere SQLite Kurulum Scripti")
print("=" * 60)
print(f"📅 Tarih: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print(f"🌐 Ortam: {'PythonAnywhere' if 'PYTHONANYWHERE_SITE' in os.environ else 'Local'}")
print(f"📁 Dizin: {os.getcwd()}")
print(f"🐍 Python: {sys.version}")
print("=" * 60)
def check_pythonanywhere():
"""PythonAnywhere ortamını kontrol et"""
print("\n🌐 PythonAnywhere Ortam Kontrolü:")
if 'PYTHONANYWHERE_SITE' in os.environ:
print("✅ PythonAnywhere ortamında çalışıyor")
return True
else:
print("⚠️ Local ortamda çalışıyor (PythonAnywhere değil)")
return False
def install_cryptography():
"""Cryptography kütüphanesini yükle"""
print("\n📦 Cryptography Kütüphanesi Kurulumu:")
try:
print("📥 Cryptography yükleniyor...")
result = subprocess.run([
sys.executable, "-m", "pip", "install",
"cryptography==41.0.7", "--user"
], capture_output=True, text=True, timeout=300)
if result.returncode == 0:
print("✅ Cryptography başarıyla yüklendi")
return True
else:
print(f"❌ Cryptography yükleme hatası: {result.stderr}")
return False
except Exception as e:
print(f"❌ Yükleme hatası: {e}")
return False
def check_sqlite():
"""SQLite desteğini kontrol et"""
print("\n🗄️ SQLite Desteği Kontrolü:")
try:
import sqlite3
print("✅ SQLite3 modülü mevcut")
print(f"📊 SQLite versiyonu: {sqlite3.sqlite_version}")
# Test veritabanı oluştur
test_db = "test_sqlite.db"
conn = sqlite3.connect(test_db)
cursor = conn.cursor()
cursor.execute("SELECT sqlite_version()")
result = cursor.fetchone()
conn.close()
# Test dosyasını sil
if os.path.exists(test_db):
os.remove(test_db)
print(f"✅ SQLite test başarılı: {result[0]}")
return True
except ImportError:
print("❌ SQLite3 modülü bulunamadı")
return False
except Exception as e:
print(f"❌ SQLite test hatası: {e}")
return False
def create_simple_sqlite_manager():
"""Basit SQLite SecurityManager oluştur"""
print("\n📝 Basit SQLite SecurityManager Oluşturma:")
if os.path.exists("sqlite_security_manager.py"):
print("✅ sqlite_security_manager.py dosyası mevcut")
return True
try:
# SQLite SecurityManager içeriği
lines = [
"#!/usr/bin/env python3",
"# -*- coding: utf-8 -*-",
'"""',
"Basit SQLite Security Manager",
'"""',
"",
"import sqlite3",
"import os",
"from datetime import datetime",
"",
"class SQLiteSecurityManager:",
" def __init__(self, db_path=\"passwords.db\"):",
" self.db_path = db_path",
" self.is_pythonanywhere = 'PYTHONANYWHERE_SITE' in os.environ",
" ",
" if self.is_pythonanywhere:",
" self.db_path = os.path.join(os.getcwd(), \"passwords.db\")",
" print(f\"🔍 PythonAnywhere SQLite DB: {self.db_path}\")",
" ",
" self.init_database()",
" ",
" def init_database(self):",
" with sqlite3.connect(self.db_path) as conn:",
" cursor = conn.cursor()",
" cursor.execute('''",
" CREATE TABLE IF NOT EXISTS passwords (",
" id INTEGER PRIMARY KEY AUTOINCREMENT,",
" user_id TEXT NOT NULL,",
" site_name TEXT NOT NULL,",
" username TEXT NOT NULL,",
" password TEXT NOT NULL,",
" created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP",
" )",
" ''')",
" conn.commit()",
" print(\"✅ Veritabanı başlatıldı\")",
" ",
" def save_password(self, user_id, site_name, username, password, master_password):",
" try:",
" with sqlite3.connect(self.db_path) as conn:",
" cursor = conn.cursor()",
" cursor.execute('''",
" INSERT OR REPLACE INTO passwords ",
" (user_id, site_name, username, password)",
" VALUES (?, ?, ?, ?)",
" ''', (user_id, site_name, username, password))",
" conn.commit()",
" print(f\"✅ Şifre kaydedildi: {site_name}\")",
" return True",
" except Exception as e:",
" print(f\"❌ Şifre kaydetme hatası: {e}\")",
" return False",
" ",
" def get_passwords(self, user_id, master_password=None):",
" try:",
" with sqlite3.connect(self.db_path) as conn:",
" cursor = conn.cursor()",
" cursor.execute('''",
" SELECT site_name, username, password, created_at",
" FROM passwords WHERE user_id = ?",
" ORDER BY created_at DESC",
" ''', (user_id,))",
" ",
" passwords = []",
" for row in cursor.fetchall():",
" passwords.append({",
" 'site_name': row[0],",
" 'username': row[1],",
" 'password': row[2] if master_password else '****',",
" 'created_at': row[3]",
" })",
" print(f\"✅ {len(passwords)} şifre getirildi\")",
" return passwords",
" except Exception as e:",
" print(f\"❌ Şifre okuma hatası: {e}\")",
" return []",
" ",
" def delete_password(self, user_id, site_name):",
" try:",
" with sqlite3.connect(self.db_path) as conn:",
" cursor = conn.cursor()",
" cursor.execute('''",
" DELETE FROM passwords ",
" WHERE user_id = ? AND site_name = ?",
" ''', (user_id, site_name))",
" conn.commit()",
" ",
" if cursor.rowcount > 0:",
" print(f\"✅ Şifre silindi: {site_name}\")",
" return True",
" else:",
" print(f\"⚠️ Silinecek şifre bulunamadı: {site_name}\")",
" return False",
" except Exception as e:",
" print(f\"❌ Şifre silme hatası: {e}\")",
" return False"
]
content = "\n".join(lines)
with open("sqlite_security_manager.py", "w", encoding="utf-8") as f:
f.write(content)
print("✅ sqlite_security_manager.py dosyası oluşturuldu")
return True
except Exception as e:
print(f"❌ Dosya oluşturma hatası: {e}")
return False
def test_sqlite_system():
"""SQLite sistemini test et"""
print("\n🧪 SQLite Sistemi Testi:")
try:
from sqlite_security_manager import SQLiteSecurityManager
# Test veritabanı oluştur
test_db = "test_setup.db"
if os.path.exists(test_db):
os.remove(test_db)
sm = SQLiteSecurityManager(test_db)
# Test şifre kaydet
success = sm.save_password(
"test_user", "test_site", "test_user",
"test_password", "master_password"
)
if not success:
print("❌ Test şifre kaydetme başarısız")
return False
# Test şifre oku
passwords = sm.get_passwords("test_user", "master_password")
if len(passwords) == 0:
print("❌ Test şifre okuma başarısız")
return False
# Test veritabanını temizle
if os.path.exists(test_db):
os.remove(test_db)
print("✅ SQLite sistemi test başarılı")
return True
except Exception as e:
print(f"❌ SQLite test hatası: {e}")
return False
def main():
"""Ana kurulum fonksiyonu"""
print_header()
# Kurulum adımları
steps = [
("PythonAnywhere Ortam Kontrolü", check_pythonanywhere),
("SQLite Desteği Kontrolü", check_sqlite),
("Cryptography Kurulumu", install_cryptography),
("Basit SQLite SecurityManager Oluşturma", create_simple_sqlite_manager),
("SQLite Sistemi Testi", test_sqlite_system)
]
results = []
for step_name, step_func in steps:
try:
print(f"\n{'='*20} {step_name} {'='*20}")
result = step_func()
results.append((step_name, result))
if result:
print(f"✅ {step_name}: BAŞARILI")
else:
print(f"❌ {step_name}: BAŞARISIZ")
except Exception as e:
print(f"❌ {step_name}: HATA - {e}")
results.append((step_name, False))
# Sonuç özeti
print("\n" + "=" * 60)
print("📊 KURULUM SONUÇLARI:")
print("=" * 60)
passed = 0
total = len(results)
for step_name, result in results:
status = "✅ BAŞARILI" if result else "❌ BAŞARISIZ"
print(f"{step_name}: {status}")
if result:
passed += 1
print(f"\n📈 Başarı Oranı: {passed}/{total} ({passed/total*100:.1f}%)")
if passed >= total - 1:
print("\n🎉 SQLite kurulumu başarılı!")
print("\n💡 Şimdi yapmanız gerekenler:")
print("1. Web uygulamasını yeniden başlatın:")
print(" - PythonAnywhere Console'da: touch /var/www/umutins62_pythonanywhere_com_wsgi.py")
print("2. Şifre yöneticisini test edin")
print("3. Yeni şifreler ekleyin")
else:
print(f"\n❌ {total-passed} adım başarısız! Sorunları çözün.")
return passed >= total - 1
if __name__ == "__main__":
try:
success = main()
print("\n" + "=" * 60)
if success:
print("✅ Kurulum tamamlandı - SQLite sistemi hazır!")
else:
print("❌ Kurulum tamamlandı - Sorunlar var!")
except KeyboardInterrupt:
print("\n\n⏹️ Kurulum kullanıcı tarafından durduruldu")
except Exception as e:
print(f"\n\n❌ Beklenmeyen hata: {e}")