转载请注明出处!

可执行的命令:

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服务功能(客户端)的更多相关文章

  1. python3 实现简单ftp服务功能(服务端 For Linux)

    转载请注明出处! 功能介绍: 可执行的命令: lspwdcd put rm get mkdir 1.用户加密认证 2.允许多用户同时登陆 3.每个用户有自己的家目录,且只可以访问自己的家目录 4.运行 ...

  2. Windows7里面怎么实现FTP服务功能

    1.安装FTP服务 点击:计算机 -->属性 --> 控制面板主页 --> 程序 --> 打开或关闭Windows功能 2. 调出管理工具 操作: 鼠标点击工具栏,选择属性,选 ...

  3. AgileEAS.NET SOA 中间件平台.Net Socket通信框架-简单例子-实现简单的服务端客户端消息应答

    一.AgileEAS.NET SOA中间件Socket/Tcp框架介绍 在文章AgileEAS.NET SOA 中间件平台Socket/Tcp通信框架介绍一文之中我们对AgileEAS.NET SOA ...

  4. 一个PHP写的简单webservice服务端+客户端

    首先是服务端,服务端有一个主要的class组成:apiServer.php <?php /** * apiServer.php * * webservice主类 * * @filename ap ...

  5. Python3实现简单的爬虫功能

    python3简单实现一个爬去网站图片的小功能: 有时候想要下载自己喜欢的多个图片时,不需要一个个点击来下载,使用python脚本批量拉取,并保存到本地. 1. 首先找到自己要下载图片的url 2. ...

  6. Python实现FTP服务功能

    本文从以下三个方面, 阐述Python如何搭建FTP服务器 一. Python搭建FTP服务器 二. FTP函数释义 三. 查看目录结构 四. 上传下载程序 一. Python搭建FTP服务器 1. ...

  7. ROS学习笔记11-写一个简单的服务和客户端(C++版本)

    本文主要来源于:http://wiki.ros.org/ROS/Tutorials/WritingServiceClient%28c%2B%2B%29 写一个服务节点.在创建消息和服务中,我们创建了一 ...

  8. node http模块搭建简单的服务和客户端

    node-http Node.js提供了http模块,用于搭建HTTP服务端和客户端. 创建Web服务器 server.js /** * node-http 服务端 */ let http = req ...

  9. Windows7上开启ftp服务器功能

    开启ftp服务功能   1 进入“控制面板”->“程序”->"打开或关闭Windows功能",找到“Internet信息服务”选项 2 将“Internet信息服务”选 ...

随机推荐

  1. Linux中的uniq命令(去掉重复项,输出重复项)

    ls /bin /usr/bin | sort | uniq | less 上面这条命令的实际效果是: 获得 ls /bin /usr/bin 的 output 将上述 output 进行 sort ...

  2. Spring Transaction Propagation

    原创转载请注明出处:https://www.cnblogs.com/agilestyle/p/11530611.html REQUIRED behavior Spring REQUIRED behav ...

  3. Delphi 窗体函数GetWindow

    Delphi 窗体函数GetWindowGetWindow是计算机的函数,该函数返回与指定窗口有特定关系(如Z序或所有者)的窗口句柄,函数原型是HWND GetWindow(HWND hWnd,UIN ...

  4. UITextfield 允许和禁止编辑

    1.enabled属性 2.resignFirstResponder,设置的时候,如果不起作用,可以延时一会儿,因为键盘升起需要时间. dispatch_after(dispatch_time(DIS ...

  5. Windows系统启动iis方法详解

    很多网友一般都用Windows 系统自带的iis服务器来配置web网站,在本地进行调试和修改后才正式上线.虽说操作不难,但是小白来说却无从下手,很多人根本不知道iss在哪,怎么启动,更谈不上配置或者其 ...

  6. linux0.11内核源码——用户级线程及内核级线程

    参考资料:哈工大操作系统mooc 用户级线程 1.每个进程执行时会有一套自己的内存映射表,即我们所谓的资源,当执行多进程时切换要切换这套内存映射表,即所谓的资源切换 2.但是如果在这个进程中创建线程, ...

  7. textarea 根据光标位置添加内容

    // 获取焦点 let txt = document.getElementById("countRule"); let temp = txt.value; txt.focus(); ...

  8. Hive date_add 和 date_diff 函数

    date_add 函数 例子:date_add('day',-1,current_date) date_diff 函数 例子:date_diff('day',cast(a.dt1 as timesta ...

  9. 软件-Axure:Axure RP

    ylbtech-软件-Axure:Axure RP Axure RP是一款专业的快速原型设计工具.Axure(发音:Ack-sure),代表美国Axure公司:RP则是Rapid Prototypin ...

  10. Linux启动详细过程(开机启动顺序)

    启动第一步--加载BIOS当你打开计算机电源,计算机会首先加载BIOS信息,BIOS信息是如此的重要,以至于计算机必须在最开始就找到它.这是因为BIOS中包含了CPU的相关信息.设备启动顺序信息.硬盘 ...