Created
May 27, 2024 13:52
-
-
Save shijiezhou1/3685572d80687bd4413c5a3ff76743ad to your computer and use it in GitHub Desktop.
listen on command server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import socket | |
import subprocess | |
HOST = '127.0.0.1' | |
PORT = 65432 | |
def handle_client(conn): | |
try: | |
while True: | |
# 接收数据 | |
data = conn.recv(1024) | |
if not data: | |
break | |
# 将接收到的数据解码为字符串 | |
command = data.decode().strip() | |
print(f"收到命令:{command}") | |
# 执行命令并获取输出 | |
try: | |
output = subprocess.check_output(command, shell=True) | |
except Exception as e: | |
output = str(e).encode() | |
# 发送命令输出结果 | |
conn.sendall(output) | |
finally: | |
conn.close() | |
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: | |
# 绑定地址和端口 | |
s.bind((HOST, PORT)) | |
# 开始监听 | |
s.listen() | |
print(f"服务器正在监听{HOST}:{PORT}") | |
# 接受客户端连接 | |
while True: | |
conn, addr = s.accept() | |
print(f"连接来自:{addr}") | |
# 处理客户端连接 | |
handle_client(conn) | |
print(f"连接已关闭:{addr}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment