1.远程控制
#利用subprocess 打开控制台
#cmd_client.py
import subprocess
import socket
sk=socket.socket()
address=('127.0.0.1',80000)
sk.bind(address)
sk.listen(3)
while 1:
conn,addr=sk.accept()
print(addr)
while 1:
try:
data=conn.recev(1024)
except Exception:
break
if not data:
break
data=str(data,'utf8')
obj=subprocess.Popen(data,shell=True,stdout=subprocess.PIPE)#开启子进程
ms=obj.stdout.read() #types gbk
ms_len=bytes( str(len(ms),'utf8') )
conn.sendall(ms_len) #两个send一起可能粘包现象
conn.recev(1024) #解决方案
conn.sendall(ms)
#cmd_client.py
sk=socket.socket()
ip='127.0.0.1'
port=8000
address=(ip,port)
sk.connect(address)
while True:
inp=input('<<<')
if inp=='exit':
break
sk.send(type(inp,'utf8'))
size=sk.recv(1024)
data_length=str(size,'utf8')
data_length=int(size)
sk.send(types('ok','utf8'))
data=bytes()
while (data_length-=1024)>0
data+=sk.recv(1024)
print(str(data,'gbk'))
sk.close()
2.编码
#python str types
str:unicode
types: 16进制
str>>>>types
a1=types('yanga11ang','utf8')
a2='yanga11ang'.encode('utf8')
a1==a2
types>>>>str
str(a1,'utf8')
a1.decode('utf8')
3.传输文件
#post_client.py
import socket
import os
sk=socket.socket()
address=('127.0.0.1',80000)
sk.bind(address)
sk.listen(3)
BASE_DIR=os.path.dirname(os.path.abspath(__file__))
while 1:
conn,addr=sk.accept()
data=conn.recv(1024)
cmd,filename,file_size=str(data,'utf8').split('|')
path=os.path.join(BASE_DIR,filename)
file_size=int(file_size)
f=open(path,'ab')
has_resv=0
while has_resv<file_size
data=conn.recv(1024)
f.write(data)
has_send+=1024
f.close()
conn.close()
break;
sk.close()
#post_client.py
import os
import socket
sk=socket.socket()
ip='127.0.0.1'
port=8000
address=(ip,port)
sk.connect(address)
BASE_DIR=os.path.dirname(os.path.abspath(__file__))
while True:
inp=input('<<<').strip()#post|ll.png
sk.send(type(inp,'utf8'))
cmd,path=inp.split('|')
path=os.path.join(BASE_DIR,path)
filename=os.path.basename(path)
file_size=os.stat(path).st_size
file_info='post|%s|%s'%(filename,str(file_size))
sk.sendall(bytes(file_info,'utf8'))
f=open(path,'rb')
has_send=0
while has_send!=file_size
data=f.read(1024)
sk.sendall(data)
has_send+=len(data)
f.close()
print('ok')
sk.close()