socket遠端命令

铿锵有力自信且坚定發表於2024-09-29

1. 服務端

import socket
import os
servers = socket.socket()
servers.bind(("localhost", 6969)) # 繫結埠
servers.listen()
while True:
  conn, addr = servers.accept() # 等待接受對方資訊 conn客戶端連過來的例項,用原來的線路連線
  while True:
    data = conn.recv(1024).decode()
    print("recv:", data)
    if not data:
      print("client has lost...")
    break
    res = os.popen(data).read()
    conn.send(res.encode())

servers.close()

2.客戶端

import socket
client = socket.socket() # 宣告socket型別,同時生成socket連線物件
client.connect(("localhost", 6969))

while True:
  msg = input(">>:").strip()
  if len(msg) == 0:continue
  client.send(msg.encode("utf-8"))
  data = client.recv(1024)
  print( data.decode())
client.close()

相關文章