1 客户端输入命令,传输到服务端调用操作系统命令
客户端代码:
代码块
import socket
sk = socket.socket()
sk.connect_ex(('127.0.0.1',8080))
while 1:
cmd = input('请输入一个命令>>>')
sk.send(cmd.encode('utf-8'))
result = sk.recv(102400).decode('gbk')
print(result)
sk.close()
服务端代码:
代码块
import socket
import subprocess
sk = socket.socket()
sk.bind(('127.0.0.1',8080))
sk.listen()
conn,addr = sk.accept()
while 1:
cmd = conn.recv(1024).decode('utf-8')
r = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
stdout = r.stdout.read()
stderr = r.stderr.read()
if stderr:
conn.send(stderr)
else:
conn.send(stdout)
conn.close()
sk.close()
2 模拟ftp文件的上传下载
客户端:
代码块
import socket
import os
import json
sk = socket.socket()
sk.connect_ex(('127.0.0.1', 8080)) # 带返回值,如果出错,不会报错,会返回错误的编码
# sk.connect()# 会直接报错 两个都是连接服务器的功能
menu = {'1': 'upload', '2': 'download'}
for k, v in menu.items():
print(k, v)
num = input('请输入功能选项:')
if num == '1':
file_path = input('请输入一个文件的绝对路径>>>')
# D:/sylar/python_workspace/day31/文件上传下载/__init__.py
filename = os.path.basename(file_path)
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
dic = {'opt': menu.get(num), 'filename': filename, 'content': content}
str_dic = json.dumps(dic) # 把字典序列化,用来传输
sk.send(str_dic.encode('utf-8')) # 发射给服务器
sk.close()
服务端:
代码块
import socket
import json
sk = socket.socket()
sk.bind(('127.0.0.1',8080))
sk.listen()
conn,addr = sk.accept()
str_dic = conn.recv(9090).decode('utf-8') #接收客户端传输的数据
dic = json.loads(str_dic) #解析数据,还原字典
# dic = {'opt':menu.get(num),'filename':filename,'content':content}
if dic['opt'] == 'upload': #判断客户端手否输入的是upload
# 上传
filename = 'new' + dic['filename'] #写入新文件的名字
with open(filename,'w',encoding='utf-8') as f:
f.write(dic['content'])
conn.close()
sk.close()
别跑,点个赞再走
网友评论