-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathsshx.py
More file actions
3502 lines (3262 loc) · 154 KB
/
Copy pathsshx.py
File metadata and controls
3502 lines (3262 loc) · 154 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
import requests, pickle
import json
import os
import re
import ast
import paramiko
import ipaddress
import jdatetime
import traceback
from pathlib import Path
from bs4 import BeautifulSoup
from selectolax.parser import HTMLParser
from datetime import datetime
from time import time, sleep
from uuid import uuid4
user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36"
node1 = "ir1.node.check-host.net"
node2 = "ir3.node.check-host.net"
node3 = "ir5.node.check-host.net"
node4 = "de1.node.check-host.net"
node5 = "fr2.node.check-host.net"
node6 = "us1.node.check-host.net"
headers = {
'accept': 'application/json',
'user-agent': user_agent
}
http_panels = ['shahan', 'xpanel', 'rocket', 'sanaie']
ssh_panels = ['dragon']
v2ray_panels = ['sanaie']
supported_protocols = ['vless']
shortcut_isp_json = {
"Mobile Communication Company of Iran PLC": "همراه اول",
"Information Technology Company (ITC)": "مخابرات",
"Iran Cell Service and Communication Company": "ایرانسل",
'"Rightel Communication Service Company PJS"': "رایتل",
'Rightel Communication Service Company PJS': "رایتل",
"Iran Telecommunication Company PJS": "مخابرات",
"Aria Shatel Company Ltd": "شاتل",
"Shiraz Hamyar Co.": "همیارنت",
"Pars Online PJS": "پارس آنلاین",
"Pishgaman Toseeh Ertebatat Company (Private Joint Stock)": "پیشگامان",
"Asiatech Data Transmission company": "آسیاتک",
"Sefroyek Pardaz Engineering PJSC": "صفرویک",
"Datak Company LLC": "رهام داتک",
"Parvaresh Dadeha Co. Private Joint Stock": "صبانت",
"ANDISHE SABZ KHAZAR CO. P.J.S.": "اندیشه سبز",
"Dade Samane Fanava Company (PJS)": "فن آوا",
"Rayaneh Danesh Golestan Complex P.J.S. Co.": "های وب",
"Mobin Net Communication Company (Private Joint Stock)": "مبین نت",
"Noyan Abr Arvan Co. ( Private Joint Stock)": "آروان",
"Afranet": "افرانت",
"Sepanta Communication Development Co. Ltd": "سپنتا",
"Fanava Group": "فن آوا"
}
def Shortcut_isp(isp):
if shortcut_isp_json.get(isp, None) is not None:
return shortcut_isp_json[isp]
else:
return isp
def ISP(target):
with open("ir.csv", "r", encoding="utf-8") as f:
for i in f.readlines():
if i != "\n":
data = i.replace("\n", "").split(",")
from_range = data[0]
to_range = data[1]
isp = data[4]
start_ip = ipaddress.IPv4Address(from_range)
end_ip = ipaddress.IPv4Address(to_range)
num_addresses = int(end_ip) - int(start_ip)
subnet_bits = 32 - num_addresses.bit_length()
ip_network = from_range + "/" + str(subnet_bits)
try:
if ipaddress.ip_address(target) in ipaddress.ip_network(ip_network):
return Shortcut_isp(isp)
except:
pass
return ""
def IP_INFO(query):
url = f"http://ip-api.com/json/{query}?fields=status,message,continent,continentCode,country,countryCode,region,regionName,city,timezone,isp,org,as"
try:
r = requests.get(url, headers=headers)
data = json.loads(r.text)
if data['status'] == "success":
text = f"🌎Continent: {data['continent']} ({data['continentCode']})\n🏳️Country: {data['country']} ({data['countryCode']})\n📍Region: {data['region']} ({data['regionName']})\n🗺City: {data['city']}\n⌚️Time zone: {data['timezone']}\n🌐ISP: {data['isp']}\n🏢Organization: {data['org']}\n🛜AS: {data['as']}"
return text
else:
return data['message']
except Exception as e:
return "Error: " + str(e)
def check_host_json_results(results):
for result in results[node1][0]:
if result[0] == "OK":
return False
for result in results[node2][0]:
if result[0] == "OK":
return False
try:
for result in results[node3][0]:
if result[0] == "OK":
return False
except:
pass
for result in results[node4][0]:
if result[0] == "OK":
return True
for result in results[node5][0]:
if result[0] == "OK":
return True
for result in results[node6][0]:
if result[0] == "OK":
return True
def check_host_api(host):
try:
url = f"https://check-host.net/check-ping?host={host}&node={node1}&node={node2}&node={node3}&node={node4}&node={node5}&node={node6}"
r = requests.get(url, headers=headers)
if r.status_code == 200:
request_id = json.loads(r.text)['request_id']
sleep(7)
data = requests.get("https://check-host.net/check-result/" + request_id, headers=headers)
if data.status_code == 200:
results = json.loads(data.text)
return check_host_json_results(results)
else:
return False
else:
return False
except:
return False
def open_session(host, port):
r = requests.session()
session = "ssh/" + host + ".session"
with open(session, 'rb') as f:
r.cookies.update(pickle.load(f))
troubleshooting(host)
protocol = get_protocol_cache(host)
if (port == "80") and (protocol == "https"):
port = "443"
url = protocol + "://" + host + ":" + port
return url, r
def get_token(req):
html = HTMLParser(req)
for data in html.css('meta'):
if data.attributes.get("name", None) is not None:
if data.attributes['name'] == "csrf-token":
return data.attributes['content']
def ssh_status(host, port, username, password):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(host, int(port), username, password, banner_timeout=200)
return "🟢 Online"
except Exception as e:
return "🔴 Offline: Please check the username or password or port : " + str(e)
def Force_string(stdout):
timeout = 1.5
endtime = time() + timeout
while not stdout.channel.eof_received:
sleep(0.2)
if time() > endtime:
stdout.channel.close()
break
return stdout
def Clean_string(dirty):
cleaned = re.sub('\[[0-9;]+[a-zA-Z]',' ', dirty)
cleaned = cleaned.replace('\x1b', "")
return cleaned
def get_ips_of_users_dragon(ssh, usernames):
cmd = "ps -ef | grep ssh"
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(cmd)
datas = ssh_stdout.read().decode()
datas = datas.split("\n")
pids = []
gotted = []
for data in datas:
cache = data.split(" ")
cache = list(filter(None, cache))
if cache != []:
if cache[0] in usernames:
if cache[0] not in gotted:
pids.append(cache[1])
gotted.append(cache[0])
elif cache[0][-1] == "+":
if len(cache) == 9:
if cache[8] in usernames:
if cache[8] not in gotted:
pids.append(cache[1])
gotted.append(cache[8])
ips = []
users = []
for pid in pids:
cmd = f"lsof -p {pid} | grep TCP"
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(cmd)
datas = ssh_stdout.read().decode()
ip = re.findall(r'[0-9]+(?:\.[0-9]+){3}', datas)
if ip == []:
break
elif len(ip) == 1:
ips.append(ip[0])
users.append(gotted[pids.index(pid)])
else:
ips.append(ip[1])
users.append(gotted[pids.index(pid)])
return ips, users
def check_lang_details(html):
for span in html.css('span.pc-mtext'):
if "داشبورد" in span.text():
return "Fa"
elif "Dashboard" in span.text():
return "En"
return "Fa"
def check_panel_protocol(host):
url = 'https://' + host
try:
response = requests.head(url, allow_redirects=True)
if response.status_code == 200:
if response.url.startswith("https://"):
return "https"
elif response.url.startswith("http://"):
return "http"
else:
#Unknown
return "http"
else:
return "http"
except:
return "http"
def troubleshooting(host):
if (Path("protocol-cache.txt").is_file() is False) or (get_protocol_cache(host) is None):
protocol = check_panel_protocol(host)
add_protocol_cache(host, protocol)
def add_protocol_cache(host, protocol):
with open("protocol-cache.txt", 'a+') as f:
if host not in f.read():
f.writelines(f"{host}:{protocol}\n")
def remove_protocol_cache(host):
with open("protocol-cache.txt", "r") as f:
lines = f.readlines()
for line in lines:
if host in line:
Line = line.replace("\n", "")
break
try:
with open("protocol-cache.txt", "w") as f:
for line in lines:
if line.strip("\n") != Line:
f.write(line)
except Exception as e:
os.remove("protocol-cache.txt")
with open("protocol-cache.txt", "a+") as f:
for line in lines:
f.writelines(line)
def get_protocol_cache(host):
with open("protocol-cache.txt", 'r') as f:
for data in f.readlines():
if host in data:
return data.split(':')[1].replace('\n', '')
return None
def Test(r, host, port, panel, status):
if panel == "shahan":
protocol = check_panel_protocol(host)
s = r.get(f"{protocol}://{host}:{port}/p/index.php").text
html = HTMLParser(s)
for button in html.css('button'):
if button.attributes.get("name", None) is not None:
if "login" in button.attributes['name']:
return False
return True
elif panel == "rocket":
if status == 'updater':
protocol = check_panel_protocol(host + ':' + port)
s = r.get(f"{protocol}://{host}:{port}/settings").text
html = HTMLParser(s)
for form in html.css('form'):
if form.attributes.get("action", None) is not None:
if "/login" in form.attributes['action']:
return False
return True
elif panel == "xpanel":
protocol = check_panel_protocol(host + ':' + port)
s = r.get(f"{protocol}://{host}:{port}/cp/users").text
html = HTMLParser(s)
for form in html.css('form'):
if form.attributes.get("action", None) is not None:
if "/login" in form.attributes['action']:
return False
try:
if check_lang_details(html) != "en":
r.get(f"{protocol}://{host}:{port}/cp/settings/lang/en")
except:
pass
return True
elif panel == "sanaie":
protocol = check_panel_protocol(host + ':' + port)
try:
s = r.post(f"{protocol}://{host}:{port}/server/status", allow_redirects=False)
if s.status_code == 200:
return True
elif s.status_code == 301:
return False
else:
return False
except Exception as e:
print(e, "sanaie test")
return False
return True
def Login(username, password, host, port, panel):
if panel in http_panels:
r = requests.session()
if panel == "shahan":
protocol = check_panel_protocol(host)
login_path = f"{protocol}://{host}:{port}/p/login.php"
data = {'username': username, 'password': password, "loginsubmit": ""}
elif panel == "xpanel":
protocol = check_panel_protocol(host + ':' + port)
login_path = f"{protocol}://{host}:{port}/login"
data = {'_token': get_token(r.get(login_path).text), 'username': username, 'password': password}
elif panel == "rocket":
protocol = check_panel_protocol(host + ':' + port)
login_path = f"{protocol}://{host}:{port}/ajax/login"
data = {'username': username, 'password': password, "remember": ""}
elif panel == "sanaie":
protocol = check_panel_protocol(host + ':' + port)
data = {'username': username, 'password': password}
login_path = f"{protocol}://{host}:{port}/login"
session = "ssh/" + host + ".session"
try:
with open(session, 'wb') as f:
responde = r.post(login_path, data=data)
pickle.dump(r.cookies, f)
if responde.status_code <= 302:
if Test(r, host, port, panel, 'login') is True:
print(f"Login and saved session at {host} | Code: ", responde.status_code)
if Path("protocol-cache.txt").is_file() is False:
add_protocol_cache(host, protocol)
else:
if get_protocol_cache(host) is not None:
remove_protocol_cache(host)
add_protocol_cache(host, protocol)
return True
else:
print("Error : Test")
return False
else:
print("Error : ", responde.status_code)
return False
except Exception as e:
print("Login Error: ", e)
return False
r.close()
elif panel in ssh_panels:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
if panel == "dragon":
ssh.connect(host, port, username, password, banner_timeout=200)
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command("menu")
ssh_stdin.flush()
dirty = Force_string(ssh_stdout).read().decode()
cleaned = Clean_string(dirty)
if "DRAGON VPS MANAGER" in cleaned:
return True
else:
return False
except Exception as e:
print("Login Error: ", e)
return False
ssh.close()
#>> Domain:Panelport @ User:Password ? Panel:path & sshport:udgpw & remark
#>> Domain:Panelport @ User:Password ? Panel:default & default:default & remark
def HOSTS():
hosts = []
remarks = []
with open("Pannels.txt", "r", encoding="utf-8") as f:
for data in f.readlines():
data = data.replace("\n", "")
hosts.append(data.split(":")[0])
remarks.append(data.split("&")[2])
return hosts, remarks
def HOST_INFO(target):
with open("Pannels.txt", "r", encoding="utf-8") as f:
for data in f.readlines():
data = data.replace("\n", "")
host = data.split(":")[0]
if target == host:
port = data.split("@")[0].split(":")[1]
username = data.split("@")[1].split(":")[0]
password = data.split("?")[0].split("@")[1].split(":")[1]
panel = data.split("?")[1].split(":")[0]
route_path = data.split("&")[0].split("?")[1].split(":")[1]
sshport = data.split("&")[1].split(":")[0]
udgpw = data.split("&")[1].split(":")[1]
remark = data.split("&")[2]
return port, username, password, panel, route_path, sshport, udgpw, remark
return None, None, None, None, None, None, None, None
def get_port_xpanel(host):
port, username, password, panel, route_path, sshport, udgpw, remark = HOST_INFO(host)
return sshport, udgpw
def get_port_dragon(host):
port, username, password, panel, route_path, sshport, udgpw, remark = HOST_INFO(host)
return sshport, udgpw
def Remove_Host(host, full):
text = "Done:\n"
if full is True:
try:
session = "ssh/" + host + ".session"
os.remove(session)
text += "Session has been removed\n"
except Exception as e:
text += f"Error Session removing: {str(e)}\n"
with open("Pannels.txt", "r", encoding="utf-8") as f:
lines = f.readlines()
Line = None
for line in lines:
if host in line:
Line = line.replace("\n", "")
break
if Line is not None:
try:
with open("Pannels.txt", "w", encoding="utf-8") as f:
for line in lines:
if line.strip("\n") != Line:
f.write(line)
text += "host has been removed from the list"
except Exception as e:
os.remove("Pannels.txt")
with open("Pannels.txt", "a+", encoding="utf-8") as f:
for line in lines:
f.writelines(line)
text += f"Error host list removing: {str(e)}"
else:
text += f"Error: host not found in List"
return text
def Add_Host(host, port, username, password, panel, route_path, sshport, udgpw, remark):
with open("Pannels.txt", 'a+', encoding="utf-8") as txt:
data = f"{host}:{port}@{username}:{password}?{panel}:{route_path}&{sshport}:{udgpw}&{remark}"
txt.writelines(data + "\n")
def host_to_end(host):
port, username, password, panel, route_path, sshport, udgpw, remark = HOST_INFO(host)
if "host has been removed from the list" in Remove_Host(host, False):
Add_Host(host, port, username, password, panel, route_path, sshport, udgpw, remark)
return "Done✔️"
else:
return "Error"
def Update_host(old_host, new_host):
port, username, password, panel, route_path, sshport, udgpw, remark = HOST_INFO(old_host)
if "host has been removed from the list" in Remove_Host(old_host, True):
Add_Host(new_host, port, username, password, panel, route_path, sshport, udgpw, remark)
return "Done✔️"
else:
return "Error"
def Update_user_pass_port(host, new_port, new_username, new_password):
port, username, password, panel, route_path, sshport, udgpw, remark = HOST_INFO(host)
if "host has been removed from the list" in Remove_Host(host, True):
Add_Host(host, new_port, new_username, new_password, panel, route_path, sshport, udgpw, remark)
return "Done✔️"
else:
return "Error"
def Update_Host_All_info(old_host, host, port, username, password, panel, route_path, sshport, udgpw, remark):
if "host has been removed from the list" in Remove_Host(old_host, True):
Add_Host(host, port, username, password, panel, route_path, sshport, udgpw, remark)
return "Done✔️"
else:
return "Error"
def Change_udp_port(host, udgpw):
port, username, password, panel, route_path, sshport, old_udgpw, remark = HOST_INFO(host)
if "host has been removed from the list" in Remove_Host(host, False):
Add_Host(host, port, username, password, panel, route_path, sshport, udgpw, remark)
return "Done✔️"
else:
return "Error"
def Change_ssh_port(host, sshport):
port, username, password, panel, route_path, old_sshport, udgpw, remark = HOST_INFO(host)
if "host has been removed from the list" in Remove_Host(host, False):
Add_Host(host, port, username, password, panel, route_path, sshport, udgpw, remark)
return "Done✔️"
else:
return "Error"
def Change_remark(host, remark):
port, username, password, panel, route_path, sshport, udgpw, old_remark = HOST_INFO(host)
if "host has been removed from the list" in Remove_Host(host, False):
Add_Host(host, port, username, password, panel, route_path, sshport, udgpw, remark)
return "Done✔️"
else:
return "Error"
def ASCII_Check(text):
for c in text:
if 0 <= ord(c) <= 127:
pass
else:
return False
return True
def Contains(text):
if text.isdigit() is True:
return True
elif text.isalpha() is True:
return True
else:
if bool(re.match("^(?=.*[a-zA-Z])(?=.*[\d])[a-zA-Z\d]+$", text)) is False:
return False
else:
return True
def TXT_FILTER(text):
special_characters = ['?', '@', '&', ':']
for char in special_characters:
if char in text:
return False
return True
def OTX_Check(text):
return bool(re.match("^[A-Za-z0-9_-]*$", text))
def get_cache_xpanel(html):
def get_usage(tdx):
if "MB" in tdx:
Usage = ('{:.2f}'.format(float(tdx.split("MB")[0]) / 1024)) + " " + " گیگابایت"
elif "GB" in tdx:
Usage = tdx.split("GB")[0] + " " + " گیگابایت"
return Usage
cache = []
for td in html.css('td'):
if td.attributes.get('style', None) is not None:
cache.append(td.text().replace("\n", "").replace(" ", "").replace(' ', ""))
elif "Unlimited" in td.text():
cache.append("Unlimited")
tdx = td.text().split("Unlimited")[1].replace(" ", '').replace("\n", '')
cache.append(((get_usage(tdx)).split(" گیگابایت")[0]).replace(" ", ""))
elif "Unlimit" in td.text():
cache.append("Unlimit")
elif "-" in td.text():
tdx = td.text().replace(" ", "").replace("\n", "")
cache.append(tdx)
elif "Expired" in td.text():
cache.append("Deactive")
elif "فعال" == td.text():
cache.append("Active")
elif "غیرفعال" == td.text():
cache.append("Deactive")
elif "GB" in td.text():
tdx = td.text().replace(" ", "").replace("\n", "")
if tdx.count('GB') == 2:
f1 = tdx.split("GB")[0] + "GB"
f2 = tdx.split("GB")[1] + "GB"
else:
f1 = tdx.split("GB")[0] + "GB"
f2 = tdx.split("GB")[1]
cache.append(get_usage(f1))
cache.append(((get_usage(f2)).split(" گیگابایت")[0]).replace(" ", ""))
elif "MB" in td.text():
tdx = td.text().replace(" ", "").replace("\n", "")
f1 = tdx.split("MB")[0] + "MB"
f2 = tdx.split("MB")[1] + "MB"
cache.append(get_usage(f1))
cache.append(((get_usage(f2)).split(" گیگابایت")[0]).replace(" ", ""))
elif "\n" not in td.text():
tdx = td.text().replace(" ", "")
if (ASCII_Check(tdx) is True):
cache.append(tdx)
elif "\n" in td.text():
tdx = td.text().replace(" ", "").replace("\n", "")
if (ASCII_Check(tdx) is True) and (Contains(tdx) is True):
if (len(tdx) <= 5) and (tdx != ""):
cache.append(tdx)
return cache
def get_users_data_sanaie(s):
inbounds, uids, remarks, connection_limits, traffics, usages, expires, days_left, status = ([] for i in range(9))
obj = json.loads(s)['obj']
for i in range(len(obj)):
if (obj[i]['protocol'] in supported_protocols):
if len(obj[i]['clientStats']) >= 1:
data_list = obj[i]
inbound_id = str(obj[i]['id'])
clients = json.loads(data_list['settings'].replace('\\', ''))["clients"]
for n in range(len(clients)):
inbounds.append(inbound_id)
uids.append(clients[n]['id'])
remarks.append(clients[n]['email'])
usage = (data_list['clientStats'][n]['up'] + data_list['clientStats'][n]['down'])
usages.append(str("{:.2f}".format(float(usage / 1024 / 1024 / 1024))))
if clients[n]['totalGB'] == 0:
traffics.append("نامحدود")
else:
tr = str("{:.2f}".format(float(clients[n]['totalGB'] / 1024 / 1024 / 1024))) + " گیگابایت"
traffics.append(tr)
if clients[n]['expiryTime'] == 0:
days_left.append("0")
expires.append("♾Unlimited")
else:
expirytime = int(str(clients[n]['expiryTime'])[:-3])
expiry = datetime.fromtimestamp(expirytime)
now = datetime.fromtimestamp(time())
remain_time = (str(expiry - now)).split(' ')
remaining_days = '0'
if len(remain_time) > 2:
remaining_days = remain_time[0]
days_left.append(remaining_days)
expires.append(str(expiry).split(" ")[0])
if clients[n]['enable'] is False:
status.append("غیرفعال")
else:
if clients[n]['expiryTime'] != 0:
if int(str(clients[n]['expiryTime'])[:-3]) - int(time()) < -1:
status.append("منقضی")
else:
status.append("فعال")
else:
status.append("فعال")
if clients[n].get(['limitIp'], None) is not None:
connection_limits.append(clients[n]['limitIp'])
else:
connection_limits.append("0")
return inbounds, uids, remarks, connection_limits, traffics, usages, expires, days_left, status
def get_users_data_dragon(ssh):
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command("menu")
dirty = Force_string(ssh_stdout).read().decode()
cleaned = Clean_string(dirty)
cleaned = cleaned.split('◇ㅤOnline: ')[1].split('\n')[0]
counter = int(cleaned.split("Total: ")[1])
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command("menu")
ssh_stdin.write('9\n')
ssh_stdin.flush()
if counter >= 20:
sleep(counter // 20)
dirty = Force_string(ssh_stdout).read().decode()
cleaned = Clean_string(dirty)
cleaned = cleaned.split('◇User ◇Password ◇limit ◇validity')[1].split('◇ TOTAL USERS')[0]
usernames, passwords, connection_limits, days, status = ([] for i in range(5))
datas = cleaned.split("\n")
for data in datas:
cache = data.split(" ")
cache = list(filter(None, cache))
if 4 <= len(cache) <= 5:
if (cache[1] != "Null"):
usernames.append(cache[0])
passwords.append(cache[1])
connection_limits.append(cache[2])
if cache[3] in ["Nunca", "Venceu"]:
status.append('غیرفعال')
days.append("0")
else:
status.append('فعال')
days.append(cache[3])
return usernames, passwords, connection_limits, days, status
def Get_user_info_shahan(html, uname, host):
ips, ports, udgpws, usernames, passwords, connection_limits, traffics, usages, expires, days_left, days_left_trubleshoots, descriptions, tuics, dropbears, status = ([] for i in range(15))
for data in html.css('td'):
if data.attributes.get("name", None) is None:
if 'روز' in data.text():
if 'گذشته' in data.text():
days_left.append('-' + (data.text()).split("روز")[0])
else:
days_left.append((data.text()).split("روز")[0])
elif "نامحدود" == data.text():
if '<td>نامحدود</td>' == data.html:
days_left.append("9999")
elif "فعال نشده" in data.text():
days_left.append("inactive")
else:
if 'expire' in data.attributes['name']:
expires.append(data.text())
if 'multilogin' in data.attributes['name']:
connection_limits.append(data.text())
if 'username' in data.attributes['name']:
usernames.append(data.text())
if 'password' in data.attributes['name']:
passwords.append(data.text())
if 'traffic' in data.attributes['name']:
if ("گیگابایت" in data.text()) or ("نامحدود" in data.text()):
traffic = data.text()
else:
traffic = data.text().replace("گیگ", "گیگابایت")
traffics.append(traffic)
if 'ip' in data.attributes['name']:
ips.append(data.text())
if 'drop' in data.attributes['name']:
dropbears.append(data.text())
if 'tuic' in data.attributes['name']:
tuics.append(data.text())
if 'port' in data.attributes['name']:
if ((data.attributes['name']).split("port")[0] != "udp") and ((data.attributes['name']).split("port")[0] != "panel"):
if "badvpn" in data.text():
udgpw = (data.text()).split("badvpn")[0]
elif "localhost" in data.text():
udgpw = (data.text()).split("localhost")[0]
elif "127.0.0.1" in data.text():
udgpw = (data.text()).split("127.0.0.1")[0]
else:
try:
udgpw = data.text()
except:
udgpw = ""
udgpws.append(udgpw)
else:
ports.append(data.text())
for a in html.css('a'):
href = a.attributes.get("href", None)
if href is not None:
if "index.php?sortby=" in href:
if "active" in href:
status.append('فعال')
else:
status.append('غیرفعال')
del status[:4]
if len(usernames) != len(status):
del status[:2]
for button in html.css('button'):
if button.attributes.get("type", None) is not None:
if button.attributes['type'] == "button":
if "/" in button.text():
usages.append((button.text()).split(" /")[0])
elif ("گیگابایت" in button.text()) or ("نامحدود" in button.text()) or ("گیگ" in button.text()):
usages.append('0.0')
for inp in html.css("input.form-control"):
if inp.attributes.get("placeholder", None) is not None:
if inp.attributes['placeholder'] == "روز اعتبار":
if inp.attributes.get("name", None) is not None:
if "edituserfinishdate" in inp.attributes['name']:
if inp.attributes.get("value", None) is not None:
days_left_trubleshoots.append(inp.attributes['value'])
else:
days_left_trubleshoots.append('9999')
for textarea in html.css("textarea"):
if textarea.attributes.get("name", None) is not None:
if "edituserinfo" in textarea.attributes['name']:
descriptions.append(textarea.text())
if len(days_left_trubleshoots) == len(usernames):
days_left = days_left_trubleshoots
if len(expires) == 0:
for data in html.css('p'):
if data.attributes.get("name", None) is not None:
if 'expire' in data.attributes['name']:
expires.append(data.text())
if 'multilogin' in data.attributes['name']:
connection_limits.append(data.text())
if 'port' in data.attributes['name']:
if ((data.attributes['name']).split("port")[0] != "udp") and ((data.attributes['name']).split("port")[0] != "panel"):
ports.append(data.text())
elif ((data.attributes['name']).split("port")[0] == "udp"):
udgpws.append(data.text())
if 'traffic' in data.attributes['name']:
if ("گیگابایت" in data.text()) or ("نامحدود" in data.text()):
traffic = data.text()
else:
traffic = data.text().replace("گیگ", "گیگابایت")
traffics.append(traffic)
if len(usages) == 0:
for data in html.css('p.btn-warning'):
if "/" in data.text():
usages.append((data.text()).split(" /")[0])
elif ("گیگابایت" in data.text()) or ("نامحدود" in data.text()) or ("گیگ" in data.text()):
usages.append('0.0')
if len(status) == 0:
for p in html.css('p.btn'):
if p.text() in ["فعال", "منقضی شده", "اتمام ترافیک", "ترافیک", "غیرفعال"]:
status.append(p.text())
if len(ips) == 0:
for i in range(len(usernames)):
ips.append(host)
for username in usernames:
if username == uname:
n = usernames.index(uname)
days = days_left[n]
if len(ports) == len(dropbears):
dropbear = dropbears[n]
else:
dropbear = ""
if len(ports) == len(tuics):
tuic = tuics[n]
else:
tuic = ""
return passwords[n], traffics[n], int(connection_limits[n]), ips[n], days, status[n], usages[n], expires[n], descriptions[n], ports[n], udgpws[n], dropbear, tuic
def Get_user_info_rocket(datas, uname, r, url):
for data in datas['data']:
if uname == data['username']:
if "GB" in data['traffic_format']:
traffic = data['traffic_format'].replace("GB", "گیگابایت")
elif "MB" in data['traffic_format']:
traffic = ('{:.2f}'.format(float(data['traffic_format'].split(" ")[0]) / 1024)) + " گیگابایت"
else:
traffic = data['traffic_format']
usage = str('{:.2f}'.format(float(int(data['consumer_traffic'])) / 1024))
Date = data['end_date']
if str(Date) == '0':
kind = "days"
else:
kind = "expiry"
days = data['remaining_days']
s = r.get(f"{url}/ajax-views/users/{str(data['id'])}/edit?_={str(int(time()))}").text
s = json.loads(s)['html']
html = HTMLParser(s)
description = ''
for textarea in html.css("textarea"):
if textarea.attributes.get("name", None) is not None:
if "desc" in textarea.attributes['name']:
description = textarea.text()
break
if data['end_date'] == 0:
for inp in html.css('input'):
if inp.attributes.get("name", None) is not None:
if inp.attributes['name'] == "exp_days":
days = inp.attributes['value']
break
s = r.get(f"{url}/ajax-views/users/{str(data['id'])}/info?_={str(int(time()))}").text
s = json.loads(s)['html']
html = HTMLParser(s)
public_link = ""
for a in html.css('a'):
if a.attributes.get("href", None) is not None:
if "/account/" in a.attributes['href']:
public_link = a.attributes['href']
port = ""
udgpw = ""
for button in html.css('button'):
if button.attributes.get("data-config", None) is not None:
try:
data_config = json.loads(button.attributes['data-config'].replace("\\", ""))
port = data_config['ssh_port']
udgpw = data_config['udp_port']
break
except:
pass
return data['password'], traffic.replace(",", ""), int(data['limit_users']), int(days), data['status_label'], usage, data['id'], kind, Date, description, public_link, port, udgpw
def Get_user_info_xpanel(html, uname):
expires = []
connection_limits = []
usernames = []
passwords = []
traffics = []
usages = []
days_left = []
status = []
descriptions = []
cache = get_cache_xpanel(html)
for i in range(0, len(cache), 10):
usernames.append(cache[i + 2])
passwords.append(cache[i + 3])
traffic = cache[i + 4]
if traffic == "Unlimited":
traffic = "نامحدود"
traffics.append(traffic)
usages.append(cache[i + 5])
connection_limits.append(cache[i + 6])
days = cache[i + 7]
if days == 'Unlimit':
days_left.append("9999")
expires.append("?")
elif days.isdigit() is True:
expires.append(str(datetime.fromtimestamp(time() + (int(days) * 86400))).split(" ")[0])
days_left.append(days)
elif "ExpiredDate:" in days:
end = days.split("ExpiredDate:")[-1]
if end.count("-") == 2:
start = str(datetime.now()).split(" ")[0]
expires.append(end)
date_format = "%Y-%m-%d"
a = datetime.strptime(start, date_format)
b = datetime.strptime(end, date_format)
delta = b - a
days_left.append(str(delta.days))
else:
expires.append("?")
days_left.append("0")
else:
expires.append("?")
days_left.append("0")
if cache[i + 8] == "Active":
status.append('فعال')
else:
status.append('غیرفعال')
descriptions.append(cache[i + 9])
dropbear = ""
for a in html.css('a'):
if a.attributes.get('data-drop', None) is not None:
URI = a.attributes['data-drop']
dropbear = URI.split('@')[1].split(':')[1].split("/")[0]
break
for i in range(len(usernames)):
if uname == usernames[i]:
if expires[i] == "?":
kind = "days"
else:
kind = "expiry"
return passwords[i], traffics[i], int(connection_limits[i]), int(days_left[i]), status[i], usages[i], kind, expires[i], descriptions[i], dropbear
def Get_user_info_sanaie(s, uid):
inbounds, uids, remarks, connection_limits, traffics, usages, expires, days_left, status = get_users_data_sanaie(s)
for i in range(len(uids)):
if uid == uids[i]:
return inbounds[i], uids[i], remarks[i], connection_limits[i], traffics[i], usages[i], expires[i], days_left[i], status[i]
def Get_user_info_dragon(ssh, uname):
usernames, passwords, connection_limits, days, status = get_users_data_dragon(ssh)
for i in range(len(usernames)):
if uname == usernames[i]:
return passwords[i], connection_limits[i], days[i], status[i]
def Get_list_users_only_shahan(html):