Python网络编程2018-01-26更新
前言:使用python3.x写的socket编程,本人wechat:YWNlODAyMzU5MTEzMTQ=。
如果内容有错,请指出来。
ssh服务端
# 1.接收一个连接实例
# 2.接收数据
# 3.判断数据是否为空
# 4.执行命令
# 5.判断命令执行结果
# 6.发送命令结果长度
# 7.发送命令执行结果
import socket,os
server=socket.socket()
server.bind(("localhost",22)) #绑定要监听的端口
server.listen() #开始监听
while True:
conn,addr=server.accept() #接收一个客户端实例conn,addr为其地址
print("new conn:",addr)
while True:
data=conn.recv(1024)
if not data:
print("客户端断开")
break
print("执行命令:",data.decode())
cmd_res=os.popen(data.decode()).read()
if len(cmd_res)==0:
cmd_res="wrong"
conn.send(str(len(cmd_res.encode())).encode())
client_ack=conn.recv(1024) #等待客户端响应,防止粘包
conn.send(cmd_res.encode())
print("等待新指令")
server.close()
ssh客户端
import socket
client=socket.socket()
client.connect(("localhost",22))
while True:
cmd=input(">>:").strip()
if len(cmd)==0:continue
client.send(cmd.encode())
cmd_res_size=client.recv(1024) #接收命令结果的长度
client.send("准备好了".encode())
recv_size=0
while recv_size<int(cmd_res_size.decode()):
cmd_res=client.recv(1024)
recv_size+=len(cmd_res)
print(cmd_res.decode())
print("命令结果大小:",cmd_res_size.decode())
print("已接受结果大小:",recv_size)
client.close()
ftp服务端
# 1.检测文件是否存在
# 2.发送文件大小给客户端
# 3.打开文件,开始边读边发数据
# 4.发送md5
import socket,os,hashlib
server=socket.socket()
server.bind(("0.0.0.0",2121))
server.listen()
while True:
conn,addr=server.accept()
print("new conn:",addr)
while True:
data=conn.recv(1024)
if not data:
print("client lost")
break
cmd,filename=data.decode().split()
if os.path.isfile(filename):
with open(filename,"rb") as f:
file_size=os.stat(filename).st_size
print(file_size)
conn.send(str(file_size).encode())
conn.recv(1024)
m=hashlib.md5()
for line in f:
m.update(line)
conn.send(line)
print("file md5:",m.hexdigest())
conn.recv(1024)
conn.send((m.hexdigest()).encode())
print("send done")
server.close()
ftp客户端
import socket
client=socket.socket()
client.connect(("0.0.0.0",2121))
while True:
cmd=input(">>:").strip()
if len(cmd)==0:continue
if cmd.startswith("get"):
client.send(cmd.encode())
file_size=client.recv(1024)
client.send(b"ready to recv data")
recv_size=0
filename=cmd.split()[1]
with open(filename+".new","wb") as f:
while recv_size<int(file_size.decode()):
data=client.recv(1024)
recv_size+=len(data)
f.write(data)
client.send(b"over")
print(recv_size)
print(file_size.decode())
file_md5=client.recv(1024)
print("file md5:",file_md5.decode())
print("recv done")
client.close()