python3 request 登录 ftp_Python3 实现FTP功能

1 importoptparse, socket2 importconfigparser3 importjson4 importos, sys5

6 STATUS_CODE ={7 250 : "Invalid cmd format, e.g: {'action':'get','filename':'test.py','size':344}",8 251 : "Invalid cmd",9 252 : "Invalid auth data",10 253 : "Wrong username or password",11 254 : "Passed authentication",12

13 800 : "the file exist,but not enough ,is continue?",14 801 : "the file exist !",15 802 : "ready to receive datas",16

17 900 : "md5 valdate success"

18

19 }20

21 classClientHandler():22

23 def __init__(self):24 #解析python FTP_client 后面接的参数

25 self.op =optparse.OptionParser()26

27 self.op.add_option('-s','--server',dest='server')28 self.op.add_option('-P','--port',dest='port')29 self.op.add_option('-u','--username',dest='username')30 self.op.add_option('-p','--password',dest='password')31 #options(定义的参数),args(未定义的参数)

32 self.options, self.args =self.op.parse_args()33 self.verify_args(self.options, self.args)34 self.make_connecton()35 self.mainPath = os.path.dirname(os.path.abspath(__file__))36 self.last =037

38 defverify_args(self, options, args):39 server =options.server40 port =options.port41 username =options.username42 password =options.password43 if int(port) > 0 and int(port) < 65535:44 returnTrue45 else:46 exit('The port is in 0-65535')47

48 defmake_connecton(self):49 self.sock =socket.socket()50 self.sock.connect((self.options.server, int(self.options.port)))51

52 def interaction(self): #登陆函数

53 print('begin to interaction....')54 #验证登陆信息

55 ifself.authenticate():56 while 1:57 cmd_info = input('[%s]' %self.current_dir).strip() #put 12.png images

58

59 cmd_list =cmd_info.split()60 ifhasattr(self, cmd_list[0]):61 func =getattr(self, cmd_list[0])62 func(*cmd_list)63 else:64 print('Commond is not found!')65

66 def authenticate(self): #账号密码输入

67 if self.options.username is None or self.options.password isNone:68 username = input('username:')69 password = input('password:')70 returnself.get_auth_result(username,password)71 returnself.get_auth_result(self.options.username, self.options.password)72

73 defresponse(self):74 data = self.sock.recv(1024).decode('utf8')75 data =json.loads(data)76 returndata77

78 defget_auth_result(self, user, pwd):79 data ={80 'action':'auth',81 'username':user,82 'password':pwd83 }84

85 self.sock.send(json.dumps(data).encode('utf8'))86 response =self.response()87 print('response:' ,response['status_code'])88 if response['status_code'] == 254:89 self.user =user90 self.current_dir =user91 print(STATUS_CODE[254])92 returnTrue93 else:94 print(STATUS_CODE[response['status_code']])95

96 def put(self, *cmd_list):97 #put file_name 路径

98 action, local_path, target_path=cmd_list99 local_path =os.path.join(self.mainPath, local_path )100

101 file_name =os.path.basename(local_path)102 file_size =os.stat(local_path).st_size103

104 data ={105 'action':'put',106 'file_name':file_name,107 'file_size':file_size,108 'target_path':target_path109 }110

111 self.sock.send(json.dumps(data).encode('utf8'))112 is_exist = self.sock.recv(1024).decode('utf8')113 ##########################

114 has_sent =0115 if is_exist == '800':116 #文件不完整

117 choice = input('The file exist,but not enouth,is continue? [Y/N]').strip()118 if choice.upper() == 'Y':119 self.sock.sendall('Y'.encode('utf8'))120 continue_position = self.sock.recv(1024).decode('utf8')121 has_sent +=int(continue_position)122 else:123 self.sock.sendall('N'.encode('utf8'))124

125 elif is_exist == '801':126 #文件完全存在

127 print('The file exist!')128 return

129 else:130 pass

131

132 f = open(local_path, 'rb')133 while has_sent <134 data="f.read(1024)135" self.sock.sendall has_sent self.show_progress file_size f.close print success>

141 defshow_progress(self, has, total):142 rate = float(has)/float(total)143 rate_num = int(rate * 100)144 if self.last !=rate_num:145 sys.stdout.write('%s%% %s\r' %(rate_num,'#'*rate_num))146 self.last =rate_num147

148 def ls(self, *cmd_list):149 data = {'action':'ls'}150 self.sock.sendall(json.dumps(data).encode('utf8'))151 data = self.sock.recv(1024).decode('utf8')152 print(data)153

154 def cd(self, *cmd_list):155 #cd images

156 data ={157 'action':'cd',158 'dirname':cmd_list[1]159 }160 self.sock.send(json.dumps(data).encode('utf8'))161 data = self.sock.recv(1024).decode('utf8')162 if data != 'Directory is not exist!':163 self.current_dir =os.path.basename(data)164 else:165 print(data)166

167 def mkdir(self, *cmd_list):168 data ={169 'action':'mkdir',170 'dirname':cmd_list[1]171 }172

173 self.sock.sendall(json.dumps(data).encode('utf8'))174 ret = self.sock.recv(1024).decode('utf8')175 print(ret)176

177 def rm(self, *cmd_list):178 data ={179 'action':'rm',180 'file_name':cmd_list[1]181 }182 self.sock.send(json.dumps(data).encode('utf8'))183 data = self.sock.recv(1024).decode('utf8')184 print(data)185

186 def pwd(self, *cmd_list):187 data = {'action':'pwd'}188 self.sock.sendall(json.dumps(data).encode('utf8'))189 data = self.sock.recv(1024).decode('utf8')190 print(data)191

192 def quit(self, *cmd_list):193 data = {'action':'quit'}194

195

196 ch =ClientHandler()197

198 ch.interaction()

134>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值