python3 实现简单ftp服务功能(客户端)
转载请注明出处!
可执行的命令:
ls
pwd
cd
put
rm
get
mkdir
上传下载,显示进度百分比以及平均上传下载速度
客户端 main代码:
#Author by Andy
#_*_ coding:utf-8 _*_
'''
This program is used to create a ftp client '''
import socket,os,json,time,hashlib,sys
class Ftp_client(object):
def __init__(self):
self.client = socket.socket()
def help(self):
msg = '''useage:
ls
pwd
cd dir(example: / .. . /var)
put filename
rm filename
get filename
mkdir directory name
'''
print(msg)
def connect(self,addr,port):
self.client.connect((addr,port))
def auth(self):
m = hashlib.md5()
username = input("请输入用户名:").strip() m.update(input("请输入密码:").strip().encode())
password = m.hexdigest()
user_info = {
'action':'auth',
'username':username,
'password':password}
self.client.send(json.dumps(user_info).encode('utf-8'))
server_response = self.client.recv(1024).decode()
# print(server_response)
return server_response
def interactive(self):
while True:
msg = input(">>>:").strip()
if not msg:
print("不能发送空内容!")
continue
cmd = msg.split()[0]
if hasattr(self,cmd):
func = getattr(self,cmd)
func(msg)
else:
self.help()
continue
def put(self,*args):
cmd_split = args[0].split()
if len(cmd_split) > 1:
filename = cmd_split[1]
if os.path.isfile(filename):
filesize = os.stat(filename).st_size
file_info = {
"action":"put",
"filename":filename,
"size":filesize,
"overriding":'True'
}
self.client.send( json.dumps(file_info).encode('utf-8') )
#防止粘包,等待服务器确认。
request_code = {
'': 'Ready to recceive data!',
'': 'Not ready to received data!'
}
server_response = self.client.recv(1024).decode()
if server_response == '':
f = open(filename,"rb")
send_size = 0
start_time = time.time()
for line in f:
self.client.send(line)
send_size += len(line)
send_percentage = int((send_size / filesize) * 100)
while True:
progress = ('\r已上传%sMB(%s%%)' % (round(send_size / 102400, 2), send_percentage)).encode(
'utf-8')
os.write(1, progress)
sys.stdout.flush()
time.sleep(0.0001)
break
else:
end_time = time.time()
time_use = int(end_time - start_time)
print("\nFile %s has been sent successfully!" % filename)
print('\n平均下载速度%s MB/s' % (round(round(send_size / 102400, 2) / time_use, 2)))
f.close()
else:
print("Sever isn't ready to receive data!")
time.sleep(10)
start_time = time.time()
f = open(filename, "rb")
send_size = 0
for line in f:
self.client.send(line)
send_size += len(line)
# print(send_size)
while True:
send_percentage = int((send_size / filesize) * 100)
progress = ('\r已上传%sMB(%s%%)' % (round(send_size / 102400, 2), send_percentage)).encode(
'utf-8')
os.write(1, progress)
sys.stdout.flush()
# time.sleep(0.0001)
break
else:
end_time = time.time()
time_use = int(end_time - start_time)
print("File %s has been sent successfully!" % filename)
print('\n平均下载速度%s MB/s' % (round(round(send_size / 102400, 2) / time_use, 2)))
f.close()
else:
print("File %s is not exit!" %filename)
else:
self.help()
def ls(self,*args):
cmd_split = args[0].split()
# print(cmd_split)
if len(cmd_split) > 1:
path = cmd_split[1]
elif len(cmd_split) == 1:
path = '.'
request_info = {
'action': 'ls',
'path': path
}
self.client.send(json.dumps(request_info).encode('utf-8'))
sever_response = self.client.recv(1024).decode()
print(sever_response)
def pwd(self,*args):
cmd_split = args[0].split()
if len(cmd_split) == 1:
request_info = {
'action': 'pwd',
}
self.client.send(json.dumps(request_info).encode("utf-8"))
server_response = self.client.recv(1024).decode()
print(server_response)
else:
self.help()
def get(self,*args):
cmd_split = args[0].split()
print(cmd_split)
if len(cmd_split) > 1:
filename = cmd_split[1]
file_info = {
"action": "get",
"filename": filename,
"overriding": 'True'
}
self.client.send(json.dumps(file_info).encode('utf-8'))
server_response = self.client.recv(1024).decode() #服务器反馈文件是否存在
if server_response == '':
self.client.send(''.encode('utf-8'))
file_size = int(self.client.recv(1024).decode())
# print(file_size)
self.client.send(''.encode('utf-8')) #确认开始传输数据
if os.path.isfile(filename):
filename = filename+'.new'
f = open(filename,'wb')
receive_size = 0
m = hashlib.md5()
start_time = time.time()
while receive_size < file_size:
if file_size - receive_size > 1024: # 还需接收不止1次
size = 1024
else:
size = file_size - receive_size
data = self.client.recv(size)
m.update(data)
receive_size += len(data)
data_percent=int((receive_size / file_size) * 100)
f.write(data)
progress = ('\r已下载%sMB(%s%%)' %(round(receive_size/102400,2),data_percent)).encode('utf-8')
os.write(1,progress)
sys.stdout.flush()
time.sleep(0.0001) else:
end_time = time.time()
time_use = int(end_time - start_time)
print('\n平均下载速度%s MB/s'%(round(round(receive_size/102400,2)/time_use,2)))
Md5_server = self.client.recv(1024).decode()
Md5_client = m.hexdigest()
print('文件校验中,请稍候...')
time.sleep(0.3)
if Md5_server == Md5_client:
print('文件正常。')
else:
print('文件与服务器MD5值不符,请确认!')
else:
print('File not found!')
return self.interactive()
else:
self.help()
def rm(self,*args):
cmd_split = args[0].split()
if len(cmd_split) > 1:
filename = cmd_split[1]
request_info = {
'action':'rm',
'filename': filename,
'prompt':'Y'
}
self.client.send(json.dumps(request_info).encode("utf-8"))
server_response = self.client.recv(10240).decode()
request_code = {
'':'confirm to deleted',
'':'cancel to deleted'
} if server_response == '':
confirm = input("请确认是否真的删除该文件:")
if confirm == 'Y' or confirm == 'y':
self.client.send(''.encode("utf-8"))
print(self.client.recv(1024).decode())
else:
self.client.send(''.encode("utf-8"))
print(self.client.recv(1024).decode())
else:
print('File not found!')
self.interactive() else:
self.help()
def cd(self,*args):
cmd_split = args[0].split()
if len(cmd_split) > 1:
path = cmd_split[1]
elif len(cmd_split) == 1:
path = '.'
request_info = {
'action':'cd',
'path':path
}
self.client.send(json.dumps(request_info).encode("utf-8"))
server_response = self.client.recv(10240).decode()
print(server_response)
def mkdir(self,*args):
request_code = {
'': 'Directory has been made!',
'': 'Directory is aleady exist!'
}
cmd_split = args[0].split()
if len(cmd_split) > 1:
dir_name = cmd_split[1]
request_info = {
'action':'mkdir',
'dir_name': dir_name
}
self.client.send(json.dumps(request_info).encode("utf-8"))
server_response = self.client.recv(1024).decode()
if server_response == '':
print('Directory has been made!')
else:
print('Directory is aleady exist!')
else:
self.help()
# def touch(self,*args):
def run():
client = Ftp_client()
# client.connect('10.1.2.3',6969)
Addr = input("请输入服务器IP:").strip()
Port = int(input("请输入端口号:").strip())
client.connect(Addr,Port)
while True:
if client.auth() == '':
print("Welcome.....")
client.interactive()
break
else:
print("用户名或密码错误!")
continue
目录结构:
python3 实现简单ftp服务功能(客户端)的更多相关文章
- python3 实现简单ftp服务功能(服务端 For Linux)
转载请注明出处! 功能介绍: 可执行的命令: lspwdcd put rm get mkdir 1.用户加密认证 2.允许多用户同时登陆 3.每个用户有自己的家目录,且只可以访问自己的家目录 4.运行 ...
- Windows7里面怎么实现FTP服务功能
1.安装FTP服务 点击:计算机 -->属性 --> 控制面板主页 --> 程序 --> 打开或关闭Windows功能 2. 调出管理工具 操作: 鼠标点击工具栏,选择属性,选 ...
- AgileEAS.NET SOA 中间件平台.Net Socket通信框架-简单例子-实现简单的服务端客户端消息应答
一.AgileEAS.NET SOA中间件Socket/Tcp框架介绍 在文章AgileEAS.NET SOA 中间件平台Socket/Tcp通信框架介绍一文之中我们对AgileEAS.NET SOA ...
- 一个PHP写的简单webservice服务端+客户端
首先是服务端,服务端有一个主要的class组成:apiServer.php <?php /** * apiServer.php * * webservice主类 * * @filename ap ...
- Python3实现简单的爬虫功能
python3简单实现一个爬去网站图片的小功能: 有时候想要下载自己喜欢的多个图片时,不需要一个个点击来下载,使用python脚本批量拉取,并保存到本地. 1. 首先找到自己要下载图片的url 2. ...
- Python实现FTP服务功能
本文从以下三个方面, 阐述Python如何搭建FTP服务器 一. Python搭建FTP服务器 二. FTP函数释义 三. 查看目录结构 四. 上传下载程序 一. Python搭建FTP服务器 1. ...
- ROS学习笔记11-写一个简单的服务和客户端(C++版本)
本文主要来源于:http://wiki.ros.org/ROS/Tutorials/WritingServiceClient%28c%2B%2B%29 写一个服务节点.在创建消息和服务中,我们创建了一 ...
- node http模块搭建简单的服务和客户端
node-http Node.js提供了http模块,用于搭建HTTP服务端和客户端. 创建Web服务器 server.js /** * node-http 服务端 */ let http = req ...
- Windows7上开启ftp服务器功能
开启ftp服务功能 1 进入“控制面板”->“程序”->"打开或关闭Windows功能",找到“Internet信息服务”选项 2 将“Internet信息服务”选 ...
随机推荐
- Did you mean to run dotnet SDK commands
把所有的net core的sdk,runtime,hosting通通卸载重新安装了2.1.1版本,发现再运行dotnet命令就是下面信息: C:\Users\Administrator>dotn ...
- js中的回钓函数,C#中的委托
$(function(){ myfunction(sayHi); }); var sayHi=function(){ alter('你好'); } function myfunction(a){ a( ...
- 在Developerkit开发板上运行blink例程
本文将介绍怎么样在VScode环境下,将AliOS Tings提供的blink例程在Developerkit开发板上运行起来. DeveloperKit开发板 在例程中分别用到两个led和一个按钮 ...
- php strnatcmp()函数 语法
php strnatcmp()函数 语法 作用:自然顺序法比较字符串直线往复电机 语法:strnatcmp(string1,string2) 参数: 参数 描述 string1 必须,规定要比较的第一 ...
- php str_pad()函数 语法
php str_pad()函数 语法 str_pad()函数怎么用? php str_pad()函数用于把字符串填充到指定长度,语法是str_pad(string,length,pad_string, ...
- myeclipse svn重新定位 本地文件 svn 重新定位
我们在用工具myeclipse开发项目时,当资源库存储空间不够时,我们就需要添加资源库,涉及到我们切换项目资源库,下面就介绍一下svn资源库重新定位步骤 1,window到show view到othe ...
- BZOJ 3687: 简单题(dp+bitset)
传送门 解题思路 设\(f(i)\)表示和为\(i\)时的方案数,那么转移方程为\(f(i)+=f(i-x)\),\(x\)为当前枚举到的数字,这样做是\(O(n\sum a_i)\)的,考虑优化.发 ...
- express中 使用session与cookie
1.express如何使用session与cookie : https://www.jianshu.com/p/1839e482274e 或 https://www.cnblogs.com/chy ...
- poj-1021--2D-Nim--点阵图同构
2D-Nim Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 4136 Accepted: 1882 Descriptio ...
- PS操作
笔:B 橡皮:E 新建:C+N 选取套索:L 套索后按Alt,移动 放大:Ctrl + “+” 或 Z 缩小:Ctrl + “-” 或 Alt Z / Alt ,然后用滑轮控制大小 撤销:Ctrl + ...