Skip to content

Commit 34fda08

Browse files
committed
Added usernames
1 parent 19f85db commit 34fda08

File tree

3 files changed

+60
-35
lines changed

3 files changed

+60
-35
lines changed
1.13 KB
Binary file not shown.

main.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -31,21 +31,22 @@
3131
if digit == '1':
3232
private_key = ssh_connection.check_private_key(ssh)
3333
if private_key == "YOUR_PRIVATE_KEY":
34-
print("Generate keys first")
34+
print("Сначала сгенерируйте ключи")
3535
else:
36-
ssh_connection.add_user(ssh, server.ip)
36+
user = input("Введите имя пользователя: ")
37+
ssh_connection.add_user(ssh, server.ip, user)
3738

3839
elif digit == '2':
3940
while True:
40-
uuids = ssh_connection.find_users(ssh)
41+
users = ssh_connection.find_users(ssh)
4142
print("Введите номер пользователя или напишите exit, чтобы выйти в меню'")
4243
digit = input()
4344
if digit.lower() == 'exit':
4445
break
4546
try:
4647
digit_int = int(digit)
47-
if 1 <= digit_int <= len(uuids):
48-
ssh_connection.delete_user(ssh, digit_int, uuids)
48+
if 1 <= digit_int <= len(users):
49+
ssh_connection.delete_user(ssh, digit_int, users)
4950
else:
5051
print("Пользователя с таким номером не существует")
5152
except ValueError:

ssh_connection.py

Lines changed: 54 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import paramiko
22
import re
33
from colorama import init, Fore
4+
import json
45

56
@staticmethod
67
def connect_ssh(server):
@@ -39,13 +40,17 @@ def install_xray(ssh):
3940
print(output)
4041

4142

42-
tdin, stdout, stderr = ssh.exec_command("apt install curl -y")
43+
stdin, stdout, stderr = ssh.exec_command("apt install curl -y")
4344
output = stdout.read().decode().strip()
4445

4546

4647
stdin, stdout, stderr = ssh.exec_command("bash -c \"$(curl -L https://github.com/XTLS/Xray-install/raw/main/install-release.sh)\" @ install")
4748
output = stdout.read().decode().strip()
4849
print(output)
50+
51+
stdin, stdout, stderr = ssh.exec_command("touch /usr/local/etc/xray/users.json") # add users.json
52+
stdin, stdout, stderr = ssh.exec_command('echo "{}" > /usr/local/etc/xray/users.json')
53+
4954
except Exception as e:
5055
print(f"Ошибка при подключении или выполнении команды: {e}")
5156

@@ -79,34 +84,31 @@ def generate_keys(ssh):
7984

8085
with sftp.file('/usr/local/etc/xray/public_key.json', 'w') as remote_file:
8186
remote_file.write(public_key)
87+
88+
stdin, stdout, stderr = ssh.exec_command("rm /usr/local/etc/xray/users.json")
89+
stdin, stdout, stderr = ssh.exec_command("touch /usr/local/etc/xray/users.json") # add users.json
90+
stdin, stdout, stderr = ssh.exec_command('echo "{}" > /usr/local/etc/xray/users.json')
91+
8292
stdin, stdout, stderr = ssh.exec_command("systemctl restart xray")
8393
print("Ключи сгенерированы")
8494

8595
@staticmethod
8696
def find_users(ssh):
87-
try:
88-
stdin, stdout, stderr = ssh.exec_command("cat /usr/local/etc/xray/config.json")
89-
content = stdout.read().decode('utf-8')
90-
errors = stderr.read().decode('utf-8')
91-
92-
if errors:
93-
print(f"Ошибка: {errors}")
94-
return
95-
96-
97-
uuid_pattern = r'"id"\s*:\s*"([^"]+)"'
98-
matches = re.findall(uuid_pattern, content)
9997

100-
valid_uuids = [uuid for uuid in matches if len(uuid) == 36]
101-
102-
print(f"Всего пользователей: {len(valid_uuids)}")
103-
print("\nUUID:")
104-
for i, uuid in enumerate(valid_uuids, 1):
105-
print(f"{i}. {uuid}")
106-
107-
except Exception as e:
108-
print(f"Произошла ошибка: {str(e)}")
109-
return valid_uuids
98+
existing_data = json
99+
sftp = ssh.open_sftp()
100+
with sftp.file('/usr/local/etc/xray/users.json', 'r') as remote_file:
101+
existing_data = json.load(remote_file)
102+
users_count = len(existing_data)
103+
if users_count != 0:
104+
print(f"Всего пользователей: {users_count}")
105+
i = 1
106+
for uuid, username in existing_data.items():
107+
print(f"{i}. {username}")
108+
i = i + 1
109+
else:
110+
print("Всего пользователей: 0")
111+
return existing_data
110112

111113
@staticmethod
112114
def check_private_key(ssh):
@@ -122,9 +124,8 @@ def check_private_key(ssh):
122124
return None
123125

124126
@staticmethod
125-
def add_user(ssh, server_ip):
127+
def add_user(ssh, server_ip, user):
126128

127-
# Генерация UUID
128129
stdin, stdout, stderr = ssh.exec_command("xray uuid")
129130
uuid = stdout.read().decode('utf-8').strip()
130131

@@ -136,24 +137,47 @@ def add_user(ssh, server_ip):
136137
sftp = ssh.open_sftp()
137138
with sftp.file('/usr/local/etc/xray/config.json', 'w') as remote_file:
138139
remote_file.write(updated_config)
139-
print(f"Успешно добавлен пользователь с UUID: {uuid}")
140+
141+
user_dict = {uuid : user}
142+
with sftp.file('/usr/local/etc/xray/users.json', 'r') as remote_file:
143+
existing_data = json.load(remote_file)
144+
existing_data.update(user_dict)
145+
146+
with sftp.file('/usr/local/etc/xray/users.json', 'w') as remote_file: # changes in users.json
147+
json_str = json.dumps(existing_data, ensure_ascii=False, indent=2)
148+
remote_file.write(json_str)
149+
150+
151+
print(f"Успешно добавлен пользователь {user} с UUID: {uuid}")
140152

141153
stdin, stdout, stderr = ssh.exec_command("cat /usr/local/etc/xray/public_key.json")
142154
public_key = stdout.read().decode('utf-8')
143155

144156
print("Необходимо вставить ссылку в VLESS клиент:")
145-
print(Fore.GREEN + f"vless://{uuid}@{server_ip}:443?security=reality&sni=google.com&alpn=h2&fp=chrome&pbk={public_key}&pbk=su1LPoVoA44umUYDWskmuEwAvGvx9bg8nVfiSgK3Fiw&sid=aabbccdd&type=tcp&flow=xtls-rprx-vision&encryption=none#manul" + Fore.RESET)
157+
print(Fore.GREEN + f"vless://{uuid}@{server_ip}:443?security=reality&sni=google.com&alpn=h2&fp=chrome&pbk={public_key}&pbk=su1LPoVoA44umUYDWskmuEwAvGvx9bg8nVfiSgK3Fiw&sid=aabbccdd&type=tcp&flow=xtls-rprx-vision&encryption=none#{user}" + Fore.RESET)
146158

147159
stdin, stdout, stderr = ssh.exec_command("systemctl restart xray")
148160

149161
@staticmethod
150-
def delete_user(ssh, digit, uuids):
162+
def delete_user(ssh, digit, users):
151163
if digit != 0:
152164
digit = digit - 1
165+
166+
items_list = list(users.items())
167+
uuid, username = items_list[digit]
153168
stdin, stdout, stderr = ssh.exec_command("cat /usr/local/etc/xray/config.json")
154169
config = stdout.read().decode('utf-8')
155-
updated_config = config.replace(uuids[digit], "EMPTY", 1)
170+
updated_config = config.replace(uuid, "EMPTY", 1)
156171
sftp = ssh.open_sftp()
157172
with sftp.file('/usr/local/etc/xray/config.json', 'w') as remote_file:
158173
remote_file.write(updated_config)
159-
print(f"Пользователь {uuids[digit]} удален")
174+
175+
users.pop(uuid)
176+
177+
with sftp.file('/usr/local/etc/xray/users.json', 'w') as remote_file:
178+
json_str = json.dumps(users, ensure_ascii=False, indent=2)
179+
remote_file.write(json_str)
180+
181+
stdin, stdout, stderr = ssh.exec_command("systemctl restart xray")
182+
183+
print(f"Пользователь {username} удален")

0 commit comments

Comments
 (0)