一.服务端
#!/usr/bin/env python3
import socket
# 创建 socket 对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
# 设置一个端口
port = 12345
# 绑定端口
server_socket.bind((host, port))
# 设置最大连接数,超过后排队
server_socket.listen(5)
while True:
# 建立客户端连接
client_socket, addr = server_socket.accept()
print("连接地址: %s" % str(addr))
msg = '服务器响应!'
client_socket.send(msg.encode('utf-8'))
client_socket.close()
二.客户端
#!/usr/bin/env python3
import socket
# 创建 socket 对象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 获取本地主机名
host = socket.gethostname()
# 设置端口
port = 12345
# 连接服务,指定主机和端口
client_socket.connect((host, port))
# 接收小于 1024 字节的数据
msg = client_socket.recv(1024)
client_socket.close()
print(msg.decode('utf-8'))
三.服务端 去执行命令
#!/usr/bin/env python3
import socket
import subprocess
# 创建 socket 对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
# 设置一个端口
port = 12345
# 绑定端口
server_socket.bind((host, port))
# 设置最大连接数,超过后排队
server_socket.listen(5)
while True:
# 建立客户端连接
client_socket, addr = server_socket.accept()
print("连接地址: %s" % str(addr))
#msg = '服务器响应!'
msg = subprocess.run(['ss', '-ntlp'], stdout=subprocess.PIPE, universal_newlines=True).stdout
client_socket.send(msg.encode('utf-8'))
client_socket.close()
标签:socket,开端,server,host,client,msg,port From: https://www.cnblogs.com/circlecircle/p/18440821