-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp_enhanced.py
More file actions
3172 lines (2699 loc) · 134 KB
/
Copy pathapp_enhanced.py
File metadata and controls
3172 lines (2699 loc) · 134 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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
SCP Web Application - Enhanced Secure File Transfer Interface
A web-based application that provides SCP functionality with Windows 7 Aero UI
Enhanced with multiple file selection, multiple views, and improved credentials storage
"""
import os
import json
import base64
import hashlib
import paramiko
import threading
import stat
import time
import platform
import sys
from datetime import datetime
from flask import Flask, render_template, request, jsonify, send_file, send_from_directory, session
from werkzeug.utils import secure_filename
from cryptography.fernet import Fernet
import tempfile
import zipfile
import stat
import socket
import subprocess
import logging
def is_safe_path(path):
"""Check if path is safe for file operations (not root or system directories)"""
if not path or path == '/':
return False
# Normalize path
normalized_path = os.path.normpath(path)
# Dangerous system directories
dangerous_paths = [
'/', '/bin', '/boot', '/dev', '/etc', '/lib', '/lib64',
'/proc', '/root', '/sbin', '/sys', '/usr', '/var'
]
# Check if path starts with any dangerous directory
for dangerous in dangerous_paths:
if normalized_path == dangerous or normalized_path.startswith(dangerous + '/'):
return False
return True
def validate_remote_operation(path, operation_name):
"""Validate if remote operation is allowed on the given path"""
if not is_safe_path(path):
return {
'allowed': False,
'error': f'❌ {operation_name} not allowed in system directory: {path}. Please navigate to /home or other user directories.'
}
return {'allowed': True}
def detect_os_info():
"""Detect current operating system and return appropriate paths and info"""
system = platform.system().lower()
# Check if running in WSL
is_wsl = False
try:
with open('/proc/version', 'r') as f:
if 'microsoft' in f.read().lower():
is_wsl = True
except:
pass
os_info = {
'system': system,
'is_wsl': is_wsl,
'default_path': '/',
'home_path': os.path.expanduser('~'),
'navigation_buttons': []
}
if system == 'darwin': # macOS
primary_buttons = [
{'name': 'Desktop', 'path': os.path.join(os.path.expanduser('~'), 'Desktop'), 'icon': '🖥️', 'category': 'primary'},
{'name': 'Documents', 'path': os.path.join(os.path.expanduser('~'), 'Documents'), 'icon': '📄', 'category': 'primary'}
]
quick_access_buttons = [
{'name': 'Users', 'path': '/Users', 'icon': '👥', 'category': 'quick'},
{'name': 'Applications', 'path': '/Applications', 'icon': '📱', 'category': 'quick'},
{'name': 'Downloads', 'path': os.path.join(os.path.expanduser('~'), 'Downloads'), 'icon': '⬇️', 'category': 'quick'}
]
os_info.update({
'default_path': '/Users',
'navigation_buttons': primary_buttons,
'quick_access_buttons': quick_access_buttons
})
elif system == 'windows': # Windows
# For Windows, we don't add primary buttons that conflict with fixed buttons
# Fixed buttons: Back, Up, Root (C:\), Home (C:\Users), Refresh
primary_buttons = [] # No additional primary buttons to avoid confusion
# Detect all available drives on Windows
available_drives = []
try:
import string
for drive_letter in string.ascii_uppercase:
drive_path = f'{drive_letter}:\\'
if os.path.exists(drive_path):
available_drives.append({
'name': f'{drive_letter}: Drive',
'path': drive_path,
'icon': '💾',
'category': 'drives'
})
except Exception as e:
# Fallback to common drives
for drive in ['C:\\', 'D:\\', 'E:\\']:
if os.path.exists(drive):
available_drives.append({
'name': f'{drive[0]}: Drive',
'path': drive,
'icon': '💾',
'category': 'drives'
})
# Quick access for dropdown only
quick_access_buttons = [
{'name': 'Desktop', 'path': os.path.join(os.path.expanduser('~'), 'Desktop'), 'icon': '🖥️', 'category': 'quick'},
{'name': 'Documents', 'path': os.path.join(os.path.expanduser('~'), 'Documents'), 'icon': '📄', 'category': 'quick'},
{'name': 'Downloads', 'path': os.path.join(os.path.expanduser('~'), 'Downloads'), 'icon': '⬇️', 'category': 'quick'},
{'name': 'Program Files', 'path': 'C:\\Program Files', 'icon': '📁', 'category': 'quick'}
] + available_drives
os_info.update({
'default_path': 'C:\\Users',
'navigation_buttons': primary_buttons, # Empty to avoid conflicts
'quick_access_buttons': quick_access_buttons,
'available_drives': available_drives
})
elif system == 'linux':
if is_wsl: # WSL Environment
# Check for Windows drives
windows_drives = []
try:
for item in os.listdir('/mnt'):
drive_path = f'/mnt/{item}'
if os.path.isdir(drive_path) and len(item) == 1:
windows_drives.append({
'name': f'{item.upper()}: Drive',
'path': drive_path,
'icon': '💾',
'category': 'drives'
})
except:
pass
# Categorize navigation buttons
primary_buttons = [
{'name': 'User', 'path': os.path.expanduser('~'), 'icon': '👤', 'category': 'primary', 'title': 'User Home Directory'}
]
quick_access_buttons = [
{'name': 'Home', 'path': '/home', 'icon': '🏠', 'category': 'quick'},
{'name': 'Windows Drives', 'path': '/mnt', 'icon': '🪟', 'category': 'quick'},
] + windows_drives
os_info.update({
'default_path': '/home',
'navigation_buttons': primary_buttons,
'quick_access_buttons': quick_access_buttons,
'available_drives': windows_drives # Add this for WSL Windows drives
})
else: # Regular Linux
primary_buttons = [
{'name': 'Desktop', 'path': os.path.join(os.path.expanduser('~'), 'Desktop'), 'icon': '🖥️', 'category': 'primary'},
{'name': 'Documents', 'path': os.path.join(os.path.expanduser('~'), 'Documents'), 'icon': '📄', 'category': 'primary'}
]
quick_access_buttons = [
{'name': 'Home', 'path': '/home', 'icon': '🏠', 'category': 'quick'},
{'name': 'User', 'path': os.path.expanduser('~'), 'icon': '👤', 'category': 'quick'},
{'name': 'Downloads', 'path': os.path.join(os.path.expanduser('~'), 'Downloads'), 'icon': '⬇️', 'category': 'quick'}
]
os_info.update({
'default_path': '/home',
'navigation_buttons': primary_buttons,
'quick_access_buttons': quick_access_buttons
})
# Filter out non-existent paths for both categories
if 'navigation_buttons' in os_info:
os_info['navigation_buttons'] = [
btn for btn in os_info['navigation_buttons']
if os.path.exists(btn['path'])
]
if 'quick_access_buttons' in os_info:
os_info['quick_access_buttons'] = [
btn for btn in os_info['quick_access_buttons']
if os.path.exists(btn['path'])
]
return os_info
# Get OS info at startup
OS_INFO = detect_os_info()
app = Flask(__name__, static_folder='static', static_url_path='/static')
app.secret_key = os.urandom(24)
# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Configuration
UPLOAD_FOLDER = '/tmp/scp_uploads'
CREDENTIALS_FILE = 'saved_credentials.enc'
ENCRYPTION_KEY_FILE = 'encryption.key'
# Ensure upload directory exists
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
class SCPManager:
def __init__(self):
self.connections = {}
self.encryption_key = self._get_or_create_encryption_key()
def _get_or_create_encryption_key(self):
"""Get or create encryption key for storing credentials"""
try:
if os.path.exists(ENCRYPTION_KEY_FILE):
with open(ENCRYPTION_KEY_FILE, 'rb') as f:
key = f.read()
# Validate key format
if len(key) == 44: # Base64 encoded 32-byte key
return key
else:
logger.warning("Invalid encryption key format, generating new key")
return self._create_new_key()
else:
return self._create_new_key()
except Exception as e:
logger.error(f"Error reading encryption key: {e}")
return self._create_new_key()
def _create_new_key(self):
"""Create a new encryption key"""
key = Fernet.generate_key()
try:
with open(ENCRYPTION_KEY_FILE, 'wb') as f:
f.write(key)
logger.info("New encryption key created")
except Exception as e:
logger.error(f"Error creating encryption key: {e}")
return key
def save_credentials(self, host, username, password=None, key_data=None, port=22):
"""Securely save login credentials"""
try:
fernet = Fernet(self.encryption_key)
credentials = {
'host': host,
'port': port,
'username': username,
'password': password,
'key_data': key_data,
'saved_at': datetime.now().isoformat()
}
encrypted_data = fernet.encrypt(json.dumps(credentials).encode())
# Load existing credentials
saved_creds = self.load_saved_credentials()
credential_key = f"{username}@{host}:{port}"
saved_creds[credential_key] = encrypted_data.decode()
with open(CREDENTIALS_FILE, 'w') as f:
json.dump(saved_creds, f, indent=2)
logger.info(f"Credentials saved for {credential_key}")
return True
except Exception as e:
logger.error(f"Error saving credentials: {e}")
return False
def load_saved_credentials(self):
"""Load saved credentials"""
try:
if os.path.exists(CREDENTIALS_FILE):
with open(CREDENTIALS_FILE, 'r') as f:
return json.load(f)
return {}
except Exception as e:
logger.error(f"Error loading saved credentials: {e}")
return {}
def get_saved_credential_names(self):
"""Get list of saved credential names"""
try:
return list(self.load_saved_credentials().keys())
except Exception as e:
logger.error(f"Error getting credential names: {e}")
return []
def load_credential(self, credential_name):
"""Load specific credential"""
try:
saved_creds = self.load_saved_credentials()
if credential_name in saved_creds:
fernet = Fernet(self.encryption_key)
encrypted_data = saved_creds[credential_name].encode()
decrypted_data = fernet.decrypt(encrypted_data)
return json.loads(decrypted_data.decode())
return None
except Exception as e:
logger.error(f"Error loading credential {credential_name}: {e}")
return None
def delete_credential(self, credential_name):
"""Delete a saved credential"""
try:
saved_creds = self.load_saved_credentials()
if credential_name in saved_creds:
del saved_creds[credential_name]
with open(CREDENTIALS_FILE, 'w') as f:
json.dump(saved_creds, f, indent=2)
logger.info(f"Credential {credential_name} deleted")
return True
return False
except Exception as e:
logger.error(f"Error deleting credential {credential_name}: {e}")
return False
def test_connection(self, host, username, password=None, key_data=None, port=22):
"""Test SSH connection to remote server"""
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
if key_data:
# Handle SSH key authentication
key_file = tempfile.NamedTemporaryFile(delete=False, mode='w')
key_file.write(key_data)
key_file.close()
try:
# Try different key types
for key_class in [paramiko.RSAKey, paramiko.Ed25519Key, paramiko.ECDSAKey, paramiko.DSSKey]:
try:
private_key = key_class.from_private_key_file(key_file.name)
break
except:
continue
else:
raise Exception("Unsupported key format")
ssh.connect(host, port=port, username=username, pkey=private_key, timeout=10)
except Exception as e:
raise Exception(f"SSH key authentication failed: {str(e)}")
finally:
os.unlink(key_file.name)
else:
ssh.connect(host, port=port, username=username, password=password, timeout=10)
# Test basic command
stdin, stdout, stderr = ssh.exec_command('pwd')
home_dir = stdout.read().decode().strip()
# Get system info
stdin, stdout, stderr = ssh.exec_command('uname -a')
system_info = stdout.read().decode().strip()
ssh.close()
return {
'success': True,
'home_dir': home_dir,
'system_info': system_info
}
except Exception as e:
logger.error(f"Connection test failed: {e}")
return {'success': False, 'error': str(e)}
def create_connection(self, session_id, host, username, password=None, key_data=None, port=22):
"""Create and store SSH connection with enhanced keep-alive and large file support"""
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
if key_data:
# Handle SSH key authentication with improved error handling
key_file = tempfile.NamedTemporaryFile(delete=False, mode='w')
key_file.write(key_data)
key_file.close()
try:
private_key = None
key_errors = []
# Try different key types with specific error handling
key_types = [
(paramiko.RSAKey, "RSA"),
(paramiko.Ed25519Key, "Ed25519"),
(paramiko.ECDSAKey, "ECDSA"),
(paramiko.DSSKey, "DSS")
]
for key_class, key_type in key_types:
try:
private_key = key_class.from_private_key_file(key_file.name)
logger.info(f"Successfully loaded {key_type} key for {username}@{host}")
break
except paramiko.PasswordRequiredException:
key_errors.append(f"{key_type} key requires passphrase (not supported)")
except paramiko.SSHException as e:
key_errors.append(f"{key_type} key format error: {str(e)}")
except Exception as e:
key_errors.append(f"{key_type} key error: {str(e)}")
if not private_key:
error_msg = f"Failed to load SSH key. Tried formats: {', '.join([kt[1] for kt in key_types])}. Errors: {'; '.join(key_errors)}"
raise Exception(error_msg)
# Attempt SSH connection with the key
ssh.connect(
host,
port=port,
username=username,
pkey=private_key,
timeout=30,
banner_timeout=30,
auth_timeout=30,
look_for_keys=False, # Don't look for system keys
allow_agent=False # Don't use SSH agent
)
logger.info(f"SSH key authentication successful for {username}@{host}:{port}")
except paramiko.AuthenticationException as e:
raise Exception(f"SSH key authentication failed. Please check:\n• Key file is correct for user '{username}'\n• Key is authorized on the server\n• User account exists\nError: {str(e)}")
except paramiko.SSHException as e:
raise Exception(f"SSH connection error: {str(e)}")
except Exception as e:
if "Failed to load SSH key" in str(e):
raise e # Re-raise key loading errors as-is
else:
raise Exception(f"SSH key authentication error: {str(e)}")
finally:
# Clean up temporary key file
try:
os.unlink(key_file.name)
except:
pass
else:
ssh.connect(
host,
port=port,
username=username,
password=password,
timeout=30,
banner_timeout=30,
auth_timeout=30
)
# Configure enhanced keep-alive for large file transfers
transport = ssh.get_transport()
if transport:
# More aggressive keep-alive for large file transfers
transport.set_keepalive(15) # Send keep-alive every 15 seconds
# Increase window size for better performance with large files
transport.window_size = 2147483647 # Maximum window size
transport.packetizer.REKEY_BYTES = pow(2, 40) # 1TB before rekeying
transport.packetizer.REKEY_PACKETS = pow(2, 40) # Large packet count
# Disable compression for better large file performance
transport.use_compression(False)
logger.info(f"Enhanced SSH keep-alive configured for large files: {username}@{host}")
# Create SFTP client with optimized settings
sftp = ssh.open_sftp()
# Optimize SFTP for large file transfers
sftp.get_channel().settimeout(300) # 5 minute timeout for operations
# Detect remote OS for cross-platform compatibility
remote_os = self._detect_remote_os(ssh)
# Store connection with enhanced metadata
self.connections[session_id] = {
'ssh': ssh,
'sftp': sftp,
'host': host,
'username': username,
'port': port,
'remote_os': remote_os,
'created_at': datetime.now(),
'last_activity': datetime.now(),
'transfer_active': False,
'stored_credentials': {
'password': password,
'key_data': key_data
},
'stats': {
'bytes_transferred': 0,
'files_transferred': 0,
'last_transfer_time': None
}
}
# Start enhanced keep-alive monitoring thread
self._start_enhanced_keepalive_monitor(session_id)
logger.info(f"Enhanced connection created for {username}@{host}:{port} (OS: {remote_os})")
return True
except Exception as e:
logger.error(f"Connection creation failed: {e}")
return False
def _detect_remote_os(self, ssh):
"""Enhanced remote OS detection with detailed information"""
try:
# Try multiple detection methods for better accuracy
detection_results = {}
# Linux distribution detection
commands = [
('cat /etc/os-release 2>/dev/null | grep "^PRETTY_NAME=" | cut -d"=" -f2 | tr -d \'"\'', 'linux_pretty'),
('cat /etc/os-release 2>/dev/null | grep "^NAME=" | cut -d"=" -f2 | tr -d \'"\'', 'linux_name'),
('lsb_release -d 2>/dev/null | cut -f2', 'linux_lsb'),
('cat /etc/redhat-release 2>/dev/null', 'redhat'),
('cat /etc/debian_version 2>/dev/null', 'debian'),
('uname -s', 'uname'),
('uname -r', 'kernel'),
('hostname', 'hostname'),
('sw_vers -productName 2>/dev/null', 'macos'),
('ver 2>/dev/null', 'windows')
]
for command, key in commands:
try:
stdin, stdout, stderr = ssh.exec_command(command, timeout=3)
output = stdout.read().decode().strip()
if output:
detection_results[key] = output
except:
continue
# Analyze results
return self._analyze_remote_os_results(detection_results)
except Exception as e:
logger.warning(f"OS detection failed: {e}")
return 'server' # Better than 'unknown'
def _analyze_remote_os_results(self, results):
"""Analyze detection results and return user-friendly OS name"""
# Check for specific Linux distributions first
if 'linux_pretty' in results:
pretty_name = results['linux_pretty']
if 'Ubuntu' in pretty_name:
return 'ubuntu'
elif 'CentOS' in pretty_name:
return 'centos'
elif 'Red Hat' in pretty_name or 'RHEL' in pretty_name:
return 'redhat'
elif 'Debian' in pretty_name:
return 'debian'
elif 'Fedora' in pretty_name:
return 'fedora'
elif 'SUSE' in pretty_name or 'openSUSE' in pretty_name:
return 'suse'
elif 'Alpine' in pretty_name:
return 'alpine'
elif 'Amazon Linux' in pretty_name:
return 'amazon'
else:
return 'linux'
# Check NAME field
if 'linux_name' in results:
name = results['linux_name']
if 'Ubuntu' in name:
return 'ubuntu'
elif 'CentOS' in name:
return 'centos'
elif 'Debian' in name:
return 'debian'
elif 'Fedora' in name:
return 'fedora'
# Check LSB release
if 'linux_lsb' in results:
lsb = results['linux_lsb'].lower()
if 'ubuntu' in lsb:
return 'ubuntu'
elif 'centos' in lsb:
return 'centos'
elif 'debian' in lsb:
return 'debian'
# Check specific files
if 'redhat' in results:
return 'redhat'
if 'debian' in results:
return 'debian'
# Check macOS
if 'macos' in results:
return 'macos'
# Check Windows
if 'windows' in results:
return 'windows'
# Check uname
if 'uname' in results:
uname = results['uname'].lower()
if 'linux' in uname:
return 'linux'
elif 'darwin' in uname:
return 'macos'
elif 'freebsd' in uname:
return 'freebsd'
# If we have hostname, show it's a server
if 'hostname' in results:
return 'server'
return 'server' # Better default than 'unknown'
def detect_remote_os(self, session_id):
"""Public method to detect remote OS for a session"""
conn = self.get_connection(session_id)
if not conn:
return 'unknown'
# Return cached OS info if available
if 'remote_os' in conn:
return conn['remote_os']
# Detect and cache
try:
remote_os = self._detect_remote_os(conn['ssh'])
conn['remote_os'] = remote_os
return remote_os
except:
return 'server'
def _get_cross_platform_commands(self, remote_os, operation, *args):
"""Get cross-platform compatible commands"""
commands = {
'delete_file': {
'macos': 'rm -f "{}"',
'linux': 'rm -f "{}"',
'freebsd': 'rm -f "{}"',
'unix': 'rm -f "{}"',
'windows': 'del /f "{}"'
},
'delete_dir': {
'macos': 'rm -rf "{}"',
'linux': 'rm -rf "{}"',
'freebsd': 'rm -rf "{}"',
'unix': 'rm -rf "{}"',
'windows': 'rmdir /s /q "{}"'
},
'move': {
'macos': 'mv "{}" "{}"',
'linux': 'mv "{}" "{}"',
'freebsd': 'mv "{}" "{}"',
'unix': 'mv "{}" "{}"',
'windows': 'move "{}" "{}"'
},
'mkdir': {
'macos': 'mkdir -p "{}"',
'linux': 'mkdir -p "{}"',
'freebsd': 'mkdir -p "{}"',
'unix': 'mkdir -p "{}"',
'windows': 'mkdir "{}"'
},
'test_file': {
'macos': 'test -f "{}" && echo "FILE" || echo "NOT_FILE"',
'linux': 'test -f "{}" && echo "FILE" || echo "NOT_FILE"',
'freebsd': 'test -f "{}" && echo "FILE" || echo "NOT_FILE"',
'unix': 'test -f "{}" && echo "FILE" || echo "NOT_FILE"',
'windows': 'if exist "{}" echo FILE'
}
}
cmd_template = commands.get(operation, {}).get(remote_os, commands.get(operation, {}).get('unix', ''))
if cmd_template:
return cmd_template.format(*args)
return None
def _start_enhanced_keepalive_monitor(self, session_id):
"""Start enhanced background thread to monitor and maintain connection during large transfers"""
def enhanced_keepalive_worker():
consecutive_failures = 0
max_failures = 3
while session_id in self.connections:
try:
conn = self.connections[session_id]
transport = conn['ssh'].get_transport()
if transport and transport.is_active():
# Update last activity timestamp
conn['last_activity'] = datetime.now()
# Adjust keep-alive frequency based on transfer activity
if conn.get('transfer_active', False):
# During transfers, use lighter keep-alive
try:
# Just check transport status, don't send commands during transfer
if transport.is_authenticated():
logger.debug(f"Transfer keep-alive check passed for session {session_id}")
consecutive_failures = 0
else:
consecutive_failures += 1
logger.warning(f"Transfer keep-alive authentication check failed for session {session_id}")
except Exception as e:
consecutive_failures += 1
logger.warning(f"Transfer keep-alive failed for session {session_id}: {e}")
else:
# When not transferring, use normal keep-alive with lightweight command
try:
conn['sftp'].normalize('.') # Very lightweight SFTP operation
logger.debug(f"Keep-alive successful for session {session_id}")
consecutive_failures = 0
except Exception as e:
consecutive_failures += 1
logger.warning(f"Keep-alive failed for session {session_id}: {e}")
else:
consecutive_failures += 1
logger.warning(f"Transport inactive for session {session_id}")
# If too many consecutive failures, mark for reconnection
if consecutive_failures >= max_failures:
logger.error(f"Max keep-alive failures reached for session {session_id}, marking for reconnection")
conn['needs_reauth'] = True
consecutive_failures = 0 # Reset counter
except Exception as e:
consecutive_failures += 1
logger.error(f"Keep-alive monitor error for session {session_id}: {e}")
if consecutive_failures >= max_failures:
break
# Adaptive sleep based on transfer activity
if session_id in self.connections and self.connections[session_id].get('transfer_active', False):
time.sleep(30) # Less frequent during transfers
else:
time.sleep(45) # Normal frequency when idle
# Start the enhanced keep-alive thread
keepalive_thread = threading.Thread(target=enhanced_keepalive_worker, daemon=True)
keepalive_thread.start()
logger.info(f"Enhanced keep-alive monitor started for session {session_id}")
def _start_keepalive_monitor(self, session_id):
"""Start background thread to monitor and maintain connection"""
def keepalive_worker():
while session_id in self.connections:
try:
conn = self.connections[session_id]
transport = conn['ssh'].get_transport()
if transport and transport.is_active():
# Update last activity timestamp
conn['last_activity'] = datetime.now()
# Send a lightweight command to keep connection alive
try:
conn['sftp'].listdir('.') # Simple directory listing
logger.debug(f"Keep-alive successful for session {session_id}")
except Exception as e:
logger.warning(f"Keep-alive failed for session {session_id}: {e}")
# Try to reconnect if keep-alive fails
self._attempt_reconnection(session_id)
else:
logger.warning(f"Transport inactive for session {session_id}, attempting reconnection")
self._attempt_reconnection(session_id)
except Exception as e:
logger.error(f"Keep-alive monitor error for session {session_id}: {e}")
break
# Wait 60 seconds before next keep-alive check
time.sleep(60)
# Start the keep-alive thread
keepalive_thread = threading.Thread(target=keepalive_worker, daemon=True)
keepalive_thread.start()
logger.info(f"Keep-alive monitor started for session {session_id}")
def _attempt_reconnection(self, session_id):
"""Attempt to reconnect a dropped connection"""
try:
if session_id not in self.connections:
return False
conn = self.connections[session_id]
host = conn['host']
username = conn['username']
port = conn['port']
logger.info(f"Attempting reconnection for {username}@{host}:{port}")
# Close existing connection
try:
conn['sftp'].close()
conn['ssh'].close()
except:
pass
# Create new connection (this will use stored credentials if available)
# For now, we'll mark the connection as needing re-authentication
conn['needs_reauth'] = True
conn['reconnect_attempts'] = conn.get('reconnect_attempts', 0) + 1
if conn['reconnect_attempts'] > 3:
logger.error(f"Max reconnection attempts reached for session {session_id}")
del self.connections[session_id]
return False
logger.info(f"Connection marked for re-authentication: session {session_id}")
return True
except Exception as e:
logger.error(f"Reconnection failed for session {session_id}: {e}")
return False
def _attempt_auto_reconnect(self, session_id):
"""Attempt automatic reconnection after server restart"""
try:
if session_id not in self.connections:
return {'success': False, 'error': 'Session not found', 'error_type': 'no_session'}
conn = self.connections[session_id]
host = conn['host']
username = conn['username']
port = conn['port']
logger.info(f"Attempting auto-reconnect for {username}@{host}:{port}")
# Close existing connection
try:
conn['sftp'].close()
conn['ssh'].close()
except:
pass
# Test if server is back online
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(5)
try:
result = sock.connect_ex((host, port))
sock.close()
if result != 0:
return {
'success': False,
'error': f'Server {host}:{port} is still unreachable',
'error_type': 'server_unreachable'
}
except:
return {
'success': False,
'error': f'Cannot reach server {host}:{port}',
'error_type': 'network_error'
}
# Check if we have stored credentials for auto-reconnect
stored_creds = conn.get('stored_credentials')
if not stored_creds:
# Mark connection as needing re-authentication
conn['needs_reauth'] = True
return {
'success': False,
'error': 'Server is back online but credentials needed for reconnection',
'error_type': 'auth_required'
}
# Attempt reconnection with stored credentials
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
if stored_creds.get('key_data'):
# Use SSH key authentication
key_file = tempfile.NamedTemporaryFile(delete=False, mode='w')
key_file.write(stored_creds['key_data'])
key_file.close()
try:
private_key = None
# Try different key types
for key_class in [paramiko.RSAKey, paramiko.Ed25519Key, paramiko.ECDSAKey, paramiko.DSSKey]:
try:
private_key = key_class.from_private_key_file(key_file.name)
break
except:
continue
if not private_key:
raise Exception("Could not load SSH key for reconnection")
ssh.connect(
host,
port=port,
username=username,
pkey=private_key,
timeout=30,
look_for_keys=False,
allow_agent=False
)
finally:
try:
os.unlink(key_file.name)
except:
pass
else:
# Use password authentication
ssh.connect(
host,
port=port,
username=username,
password=stored_creds['password'],
timeout=30
)
# Configure keep-alive
transport = ssh.get_transport()
if transport:
transport.set_keepalive(30)
# Create new SFTP client
sftp = ssh.open_sftp()
# Update connection
conn['ssh'] = ssh
conn['sftp'] = sftp
conn['last_activity'] = datetime.now()
conn['reconnected_at'] = datetime.now()
conn['reconnect_count'] = conn.get('reconnect_count', 0) + 1
# Remove reauth flag if it was set
conn.pop('needs_reauth', None)
logger.info(f"Auto-reconnect successful for {username}@{host}:{port}")
return {
'success': True,
'message': f'Successfully reconnected to {host}:{port}',
'reconnect_count': conn['reconnect_count']
}
except Exception as e:
logger.error(f"Auto-reconnect failed for {username}@{host}:{port}: {e}")
conn['needs_reauth'] = True
return {
'success': False,
'error': f'Reconnection failed: {str(e)}',
'error_type': 'reconnect_failed'
}
except Exception as e:
logger.error(f"Auto-reconnect error for session {session_id}: {e}")
return {
'success': False,
'error': f'Auto-reconnect system error: {str(e)}',
'error_type': 'internal_error'
}
"""Get existing connection with health check"""
if session_id not in self.connections:
return None
conn = self.connections[session_id]
# Check if connection needs re-authentication
if conn.get('needs_reauth', False):
logger.warning(f"Connection {session_id} needs re-authentication")
return None
# Check if connection is still active
try:
transport = conn['ssh'].get_transport()
if not transport or not transport.is_active():
logger.warning(f"Connection {session_id} is inactive")
self._attempt_reconnection(session_id)
return None
except Exception as e:
logger.error(f"Connection health check failed for {session_id}: {e}")
return None
# Update last activity
conn['last_activity'] = datetime.now()
return conn