Python Socke
回射
SERVER
#!/usr/bin/python3
#_*_ coding:utf- _*_ import socket,os,time
import socketserver
import time
import threading
import random
import sys
import socket
import getopt
import os
import re
import shutil
import platform class ServerHandle(socketserver.BaseRequestHandler): def handle(self): conn = self.request
conn.sendall(bytes("Hello I'm robot!",encoding="utf-8"))
while True:
ret_bytes = conn.recv()
ret_str = str(ret_bytes,encoding="utf-8")
if ret_str == "q":
break
conn.sendall(bytes("You Send:" + ret_str,encoding="utf-8")) def daemonize(stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
pid = os.fork()
if pid > :
sys.exit() os.chdir("/")
os.umask()
os.setsid() pid = os.fork()
if pid > :
sys.exit() for f in sys.stdout, sys.stderr: f.flush()
si = open(stdin, 'r')
so = open(stdout, 'a+')
#se = open(stderr, 'a+', )
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
#os.dup2(se.fileno(), sys.stderr.fileno()) if __name__ == "__main__":
daemonize('/dev/null', '/home/share/kitking/stdout.log', '/home/share/kitking/error.log')
server = socketserver.ThreadingTCPServer(("192.168.199.XXX",),ServerHandle)
server.serve_forever()
CLIENT
#!/usr/bin/python3
#_*_ coding:utf- _*_ import socket,os,time
import socketserver host = "XXX.eicp.net"
ip = socket.gethostbyname(host)
port = obj = socket.socket()
obj.connect((ip,port)) ret_bytes = obj.recv()
ret_str = str(ret_bytes,encoding="utf-8")
print(ret_str) while True:
inp = input(">>")
if inp == "q":
obj.sendall(bytes(inp,encoding="utf-8"))
break
else:
obj.sendall(bytes(inp, encoding="utf-8"))
ret_bytes = obj.recv()
ret_str = str(ret_bytes,encoding="utf-8")
print(ret_str)
SSH模拟
SERVER
import socket,os,time
server = socket.socket()
server.bind(('localhost',)) server.listen() while True:
print("beging waiting request...")
conn,addr = server.accept()
print("new conn:",addr)
while True:
print("request comming!",addr)
data = conn.recv()
if not data:
print("客户端已断开")
break
print("执行指令:",data)
cmd = data.decode()
cmd_res = os.popen(cmd).read()
print("before send",len(cmd_res.encode('utf-8')))
if len(cmd_res) == :
com_res = "cmd has no output..."
conn.send(str(len(cmd_res.encode('utf-8'))).encode('utf-8'))
#time.sleep(0.5)
client_ack = conn.recv() #wait client confirm
conn.send(cmd_res.encode("utf-8"))
print("send done")
server.close()
CLIENT
import socket
client = socket.socket()
client.connect(('localhost',)) while True:
cmd = input(">>").strip()
if len(cmd) == :continue
client.send(cmd.encode("utf-8"))
cmd_res_size = client.recv()
client.send(b"start_trans")
sev_file_size = int(cmd_res_size.decode())
#print('sev_file_size',sev_file_size,type(sev_file_size))
received_size =
received_data = b'' while received_size < sev_file_size:
data = client.recv()
#print("收到数据!")
received_size += len(data)
received_data += data
#print('cli_file_size',received_data)
else:
#print("receive done...",received_size)
print(received_data.decode()) client.close()
文件传送
SERVER
import socket,os,time,hashlib
server = socket.socket()
server.bind(('localhost',)) server.listen() while True:
print("beging waiting request...")
conn,addr = server.accept()
print("new conn:",addr)
while True:
print("request comming!",addr)
data = conn.recv()
if not data:
print("客户端已断开")
break
cmd,filename = data.decode().split()
if os.path.isfile(filename):
f = open(filename,'rb')
m = hashlib.md5()
file_size = os.stat(filename).st_size
conn.send(str(file_size).encode('utf-8')) #send file size
conn.recv() #wait for ack
for line in f:
m.update(line)
conn.send(line)
print("file md5",m.hexdigest())
f.close()
conn.send(m.hexdigest().encode()) print("send done")
server.close()
CLIENT
import socket,hashlib
client = socket.socket()
client.connect(('localhost',)) while True:
cmd = input(">>").strip()
if len(cmd) == :continue
if cmd.startswith('get'):
client.send(cmd.encode('utf-8'))
server_response = client.recv()
print('server response:',server_response)
client.send(b'start to trans')
file_total_size = int(server_response.decode())
received_size =
file_name = cmd.split()[]
f = open(file_name+".new",'wb')
m = hashlib.md5()
while received_size < file_total_size:
if file_total_size - received_size >= :
size =
else:
size = file_total_size - received_size
data = client.recv(size)
received_size += len(data)
m.update(data)
f.write(data)
#print(file_total_size,received_size)
else:
new_file_md5 = m.hexdigest()
print("file recv done",received_size,file_total_size)
f.close()
server_file_md5 = client.recv()
print("server file md5:",server_file_md5)
print('client file md5:',new_file_md5) client.close()
FTP模式
SERVER
import socket,hashlib
import socketserver,json,os class MyTCPHandler(socketserver.BaseRequestHandler): def put(self,*args):
cmd_dic = args[]
filename = cmd_dic['filename']
filesize = cmd_dic['filesize']
if os.path.isfile(filename):
f = open(filename + ".new",'wb')
else:
f = open(filename,'wb')
self.request.send(b'200,ok')
recived_size =
m = hashlib.md5()
while recived_size < filesize:
data = self.request.recv()
m.update(data)
f.write(data)
recived_size += len(data)
else:
f.close()
print("file [%s] has uploaded..."%filename)
recived_md5 = m.hexdigest()
source_md5 = self.request.recv().decode()
if recived_md5 == source_md5:
self.request.send('MD5校验成功'.encode('utf-8'))
else:
self.request.send('MD5校验失败'.encode('utf-8')) def handle(self):
while True:
try:
print("开始监听!")
self.data = self.request.recv().strip()
print("{} wrote:".format(self.client_address[]))
print(self.data)
if not self.data:
print(self.client_address,"断开了!")
break
cmd_dic = json.loads(self.data.decode())
action = cmd_dic['action']
if hasattr(self,action):
func = getattr(self,action)
func(cmd_dic) except ConnectionRefusedError as e:
print(e)
break if __name__ == "__main__":
HOST,PORT="localhost",
server = socketserver.ThreadingTCPServer((HOST,PORT),MyTCPHandler)
server.serve_forever()
CLIENT
import socket
import os,json
import hashlib class FtpClient(object):
def __init__(self):
self.client = socket.socket() def cmd_help(self,args):
msg = '''
ls
pwd
cd
get filename
put filename
'''
print(msg) def connect(self,ip,port):
self.client.connect((ip,port)) def interactive(self):
self.auth()
while True:
cmd = input(">>").strip()
if len(cmd) == :continue
cmd_str = cmd.split()[]
if hasattr(self,'cmd_%s'%cmd_str):
func = getattr(self,'cmd_%s'%cmd_str)
func(cmd)
else:
self.help() def cmd_put(self,*args):
cmd_split = args[].split()
if len(cmd_split) > :
filename = cmd_split[]
os.path.isfile(filename)
filesize = os.stat(filename).st_size
msg_dic = {
'action': 'put',
'filename': filename,
'filesize': filesize,
'overridden': True
}
self.client.send(json.dumps(msg_dic).encode('utf-8'))
server_response = self.client.recv()
f = open(filename,'rb')
m = hashlib.md5()
for line in f:
m.update(line)
self.client.send(line)
else:
print("file upload success...")
f.close()
self.client.send(m.hexdigest().encode())
sev_md5_check = self.client.recv()
print(sev_md5_check.decode())
else:
print('file is not exist') def cmd_get(self):
pass def auth(self):
pass class Account(object):
def __init__(self):
pass ftp = FtpClient()
ftp.connect('localhost',)
ftp.interactive()
上传文件
import socket sk = socket.socket() sk.bind(("127.0.0.1",))
sk.listen() while True:
conn,address = sk.accept()
conn.sendall(bytes("欢迎光临我爱我家",encoding="utf-8")) size = conn.recv()
size_str = str(size,encoding="utf-8")
file_size = int(size_str) conn.sendall(bytes("开始传送", encoding="utf-8")) has_size =
f = open("db_new.jpg","wb")
while True:
if file_size == has_size:
break
date = conn.recv()
f.write(date)
has_size += len(date) f.close() 客户端 import socket
import os obj = socket.socket() obj.connect(("127.0.0.1",)) ret_bytes = obj.recv()
ret_str = str(ret_bytes,encoding="utf-8")
print(ret_str) size = os.stat("yan.jpg").st_size
obj.sendall(bytes(str(size),encoding="utf-8")) obj.recv() with open("yan.jpg","rb") as f:
for line in f:
obj.sendall(line)
Python Socke的更多相关文章
- python的socke编程
python的sock编程分为TCP编程和UDP编程,两者不同在于,TCP需要首先建立连接才能发送接收数据,而UDP则可以直接发送接收不需要预先建立连接. tcp编程,我总结为4步 TCP的serve ...
- python之路(十一)-socke开发
socket简介 socket通常也称作"套接字",用于描述IP地址和端口,是一个通信链的句柄,应用程序通常通过"套接字"向网络发出请求或者应答网络请求. so ...
- python sokct 包详解
1. getaddrinfo简介getaddrinfo可解析得到IPv6地址,而gethostbyname仅能得到IPv4地址.getaddrinfo在Python的socket包中,以下为pytho ...
- python学习笔记11 ----网络编程
网络编程 网络编程需要知道的概念 网络体系结构就是使用这些用不同媒介连接起来的不同设备和网络系统在不同的应用环境下实现互操作性,并满足各种业务需求的一种粘合剂.网络体系结构解决互质性问题彩是分层方法. ...
- python高级之网络编程
python高级之网络编程 本节内容 网络通信概念 socket编程 socket模块一些方法 聊天socket实现 远程执行命令及上传文件 socketserver及其源码分析 1.网络通信概念 说 ...
- python学习笔记七 初识socket(进阶篇)
socket socket通常也称作"套接字",用于描述IP地址和端口,是一个通信链的句柄,应用程序通常通过"套接字"向网络发出请求或者应答网络请求. sock ...
- [python]逆水行舟不进则退(1)
工作后迎来的第一个长假期,打算在家休息一下,看看书之类的.但是不写点东西,不做点东西,感觉有些浪费时间.同时也想通过做点东西检验下自己这段时间的收获.其实在我开始写这篇文章的时候心里还是很没底的-交代 ...
- python学习笔记 - 初识socket
socket socket通常也称作"套接字",用于描述IP地址和端口,是一个通信链的句柄,应用程序通常通过"套接字"向网络发出请求或者应答网络请求. sock ...
- 第六篇:python高级之网络编程
python高级之网络编程 python高级之网络编程 本节内容 网络通信概念 socket编程 socket模块一些方法 聊天socket实现 远程执行命令及上传文件 socketserver及 ...
随机推荐
- label技巧
问题描述: 一般都用label的for属性指定label的点击范围: <label for="male"><input type="radio" ...
- 安装Fedora 21工作站后要做的10件事情
教程]安装Fedora 21工作站后要做的10件事情 2015-01-07 13:32 CSDN CODE 作者CSDN CODE 1 755 FedoraGNOMELinux Fedora 21已经 ...
- MySQL Block Nested-Loop Join(BNL)
5.5 版本之前,MySQL本身只支持一种表间关联方式,就是嵌套循环(Nested Loop).如果关联表的数据量很大,则join关联的执行时间会非常长.在5.5以后的版本中,MySQL通过引入BNL ...
- js的 style.width 取不到元素的宽度值
以前一直用jquery的.width()方法来获取一个元素的当前的宽度.不管该元素是否设置了宽度,CSS样式是内联.外联or内嵌,都可用此方式获得元素当前的宽度. 今天想用原生JS想获取一个元素宽度时 ...
- certbot以standalone方式新建密钥
下载:wget https://dl.eff.org/certbot-auto 授权:chmod a+x ./certbot-auto 快捷命令 ./certbot-auto certonly --t ...
- ajaxFileUpload的data数据带pre标签
解决办法: var ret = jQuery.parseJSON(jQuery(data).text());
- css移动元素的几种方法
一.当然是元素设定为postion: absolute, 然后控制 left, top 位置 二.元素增加overflow属性,然后设置元素的scrollLeft, scrollRight当做滚动条来 ...
- Shell 命令行批量处理图片文件名
Shell 命令行批量处理图片文件名 从网上下载了一堆图片,有的是*.jpg的,有的是*.jpeg的.并且文件名有长有短,很是糟心.因此,我想把这些文件给全部整理好,当然是用shell来处理啦! 说干 ...
- strip()函数和 split()函数
一:python strip()函数介绍 函数原型:strip可以删除字符串的某些字符 声明:s为字符串,rm为要删除的字符序列 s.strip(rm) 删除s字符串中开头.结尾处,位于 ...
- Mac终端建立替身 并置于桌面或Finder中
前情 Xcode存放log的文件夹路径忒长了,且需要用终端才能查看.所以就想制作个替身,放在Finder中便于查看. going on command+space打开terminal 一直cd...进 ...