import socket
import sys
import subprocess
import getopt
def server_connected(port):
info = sys.platform
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
server.bind(("0.0.0.0", port))
server.listen(5)
print(f"Listening to {port}")
conn, addr = server.accept()
with conn:
print(f"Connected by {addr}")
while True:
data = conn.recv(4096)
if not data:
break
try:
command = data.decode("utf-8")
if info.startswith("linux"):
command_output = subprocess.run(command, shell=True, executable="/bin/bash", capture_output=True)
output = command_output.stdout.decode("utf-8") + command_output.stderr.decode("utf-8")
elif info.startswith("win"):
command_output = subprocess.run(command, shell=True, capture_output=True)
output = command_output.stdout.decode("gbk") + command_output.stderr.decode("gbk")
except Exception as e:
output = str(e)
conn.sendall(output.encode("utf-8") if info.startswith("linux") else output.encode("gbk"))
conn.close()
server.close()
def client_connected(host, port):
info = sys.platform
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client:
client.connect((host, port))
print(f"Connected to {host}:{port}")
while True:
data = input(">>> ")
if data.lower() == "exit":
break
client.sendall(data.encode("gbk") if info.startswith("win") else data.encode("utf-8"))
response = client.recv(4096)
if not response:
break
print(response.decode("gbk") if info.startswith("win") else response.decode("utf-8"))
client.close()
def run_args():
host = ""
port = 0
listen = False
try:
opts, args = getopt.getopt(sys.argv[1:], "lh:p:", ["listen", "host", "port"])
except getopt.GetoptError as e:
print(f"Error: {e}")
sys.exit(1)
for o, a in opts:
if o in ("-l", "--listen"):
listen = True
if o in ("-h", "--host"):
host = a
if o in ("-p", "--port"):
port = int(a)
if listen and port > 0:
server_connected(port)
elif len(host) > 0 and port > 0:
client_connected(host, port)
if __name__ == "__main__":
run_args()
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交