qingku
1 # -*- coding:utf-8 -*- 2 list1=[] 3 list2=[] 4 list3 = [] 5 list4 = [] 6 while True: 7 inputs = raw_input("按 a 查询节点: 按 b 添加节点: 按c删除节点:") 8 if inputs =="a": 9 while True: 10 inputs1 = raw_input("请输入要查询的节点名称: 按b返回上一级: 按q退出") 11 if inputs1 =="b": 12 break 13 elif inputs1 =="q": 14 exit() 15 elif inputs1 =="www.oldboy.org": 16 f = open("haproxy") 17 ha_list = [] 18 for i in f: 19 ha_list.append(i.strip()) 20 b = int(ha_list.index("backend www.oldboy.org"))+1 21 while True: 22 title = "\033[32;1m服务器节点列表\033[0m" 23 print title.center(60, "*") 24 for i in ha_list[b:]: 25 print i 26 print "\033[32;1mend\033[0m".center(50,"*") 27 choice = raw_input("按b返回上一级: 按q退出程序:") 28 if choice =="b": 29 break 30 elif choice =="q": 31 exit() 32 else: 33 print "输入错误,没有该节点,请重新输入节点名称:" 34 elif inputs =="b": 35 data = raw_input("请输入要增加的节点:") 36 c = eval(data) 37 a = c["record"] 38 print a 39 for key in a.item: 40 print key , a.get(key) 41 #list.append(key) 42 #list2.append(a.get(key)) 43 print list ,list2 44 # list.insert(2, list2[2]) 45 # list.insert(1, str(list2[1])) 46 # list.insert(0, str(list2[0])) 47 # list.reverse() 48 # # print list 49 # strs = ' '.join(list) 50 # print strs 51 # f = open("test.txt", "a+") 52 # f.write(strs) 53 # f.close()
{'backend':'www.oldboy.org','record':{'server':'10.10.99.3','weight':20,'maxconn':30}}
data = raw_input("input:")
a = eval(data)
# print a["backend"]
# print a["record"]
list = []
list2= []
a = {'maxconn': 30, 'weight': 20, 'server': '100.2.1.1'}
for key in a.iterkeys():
#print key , a.get(key)
list.append(key)
list2.append(a.get(key))
#print list ,list2
list.insert(2,list2[2])
list.insert(1,str(list2[1]))
list.insert(0,str(list2[0]))
list.reverse()
#print list
strs = ' '.join(list)
print strs
f = open("test.txt","a+")
f.write(strs)
f.close()
1 # -*- coding:utf-8 -*- 2 import paramiko,os,sys,time 3 #-----------------------更新svn------------------------------------------------- 4 msg = "正在更新本地svn" 5 msg1 = "更新完成" 6 print msg.center(50,"*") 7 os.system("cd /data/yunweisvn/sh/clearscript && svn update") 8 print msg1.center(50,"*") 9 #--------------------拷贝清库脚本到目标机器------------------------------------- 10 11 host_name = sys.argv[1] 12 password = "B^Dc%4LSBvhZZK3B" 13 port = 22 14 local_sunif = "/data/yunweisvn/sh/clearscript/sunif/cleartable.sql" 15 remote_sunif = "/data/cleardb/sunif/initscrpit/cleartable.sql" 16 17 def ssh_scp_put(ip,port,user,password,local_file,remote_file): 18 ssh = paramiko.SSHClient() 19 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 20 ssh.connect(ip, 22, 'root', password) 21 a = ssh.exec_command('date') 22 stdin, stdout, stderr = a 23 print stdout.read() 24 sftp = paramiko.SFTPClient.from_transport(ssh.get_transport()) 25 sftp = ssh.open_sftp() 26 sftp.put(local_file, remote_file) 27 if host_name == "s3": 28 ip = "10.10.123.96" 29 ssh_scp_put(ip,port,"root",password,local_sunif,remote_sunif)
2
1 # -*- coding:utf-8 -*- 2 import time,os 3 4 5 shop_car2 =[] 6 user_list = [] 7 count = 0 8 user = "liruixin" 9 password = "123456" 10 raw_user = raw_input("username:") 11 f=open("user.txt",'a+') 12 lines=[] 13 for lines in f.readlines(): 14 lines=lines.replace("\n","").split(",") 15 f.close() 16 for i in lines: 17 if i == raw_user: 18 print "this user is locked, please request to root" 19 exit() 20 else: 21 pass 22 while count <3: 23 if raw_user == user: 24 raw_password = raw_input("password:") 25 count = count+1 26 if count == 3: 27 user_list.append(raw_user) 28 user = open('user.txt','a') 29 for raw_user in user_list: 30 user.write(raw_user + ',') 31 user.close() 32 else: 33 pass 34 if raw_password == password: 35 print "success" 36 a = time.localtime() 37 b = time.strftime("%Y-%m-%d %H:%M:%S", a) 38 title = "welcome to shopping" 39 print b.center(40, "*") 40 print title.center(40, "*") 41 shop_car = [] 42 goods_list = [ 43 ["iphone 7", 5888], 44 ["coffe", 30], 45 ["computer", 3999], 46 ["mac pro", 12000] 47 ] 48 filename = r'salary.txt' 49 if os.path.exists(filename): 50 temp = open("salary.txt", "r") 51 for i in temp: 52 salary = i 53 print "您的卡上余额为", salary 54 else: 55 salary = raw_input("请输入充值金额:") 56 57 if salary.isdigit(): 58 salary = int(salary) 59 while True: 60 print "******* good list **********" 61 for i in enumerate(goods_list): 62 print i[0] + 1, i[1][0], i[1][1] 63 choice = raw_input("choice goods __ quit to exit:") 64 if choice.isdigit(): 65 choice = int(choice) 66 if choice <= 4 and choice >= 1: 67 if salary >= goods_list[choice - 1][1]: 68 salary = salary - goods_list[choice - 1][1] 69 price = (goods_list[choice - 1][1]) 70 item = (goods_list[choice - 1][0]) 71 print "你购买了 [\033[32;1m%s\033[0m] 花费了 [\033[31;1m%d\033[0m] , 你的余额为 [\033[31;1m%d\033[0m]" % ( 72 item, price, salary) 73 shop_car.append(goods_list[choice - 1]) 74 else: 75 print "你的余额不足,请选择其他商品" 76 continue 77 elif choice == "quit": 78 print "你购买的商品如下" 79 print shop_car 80 for i in shop_car: 81 82 print a 83 # for i in a: 84 # print i, shop_car.count(i) 85 86 87 print "你的余额为\033[31;1m%d\033[0m" % salary 88 salary_file = open("salary.txt", "w") 89 salary_file.write("%d" % salary) 90 salary_file.close() 91 exit() 92 93 else: 94 print "没有该商品,请重新输入" 95 continue 96 else: 97 print "this password error" 98 else: 99 print "no this user" 100 exit()
3333
1 # -*- coding:utf-8 -*- 2 import os,sys,paramiko,time 3 #*******判断所有测试环境是否有某个文件*********** 4 s7 = "10.10.123.96" 5 s3 = "10.10.39.70" 6 host_dic = {"10.10.154.77":"s1", 7 "10.10.83.96":"s2", 8 "10.10.39.70":"s3", 9 "10.10.46.120":"s4", 10 "10.10.15.128":"s5", 11 "10.10.84.48":"s6", 12 "10.10.123.96":"s7", 13 "10.10.105.91":"qa1", 14 "10.10.92.48":"qa2", 15 "10.10.50.30":"qa3", 16 "10.10.40.136":"qa4", 17 "10.10.189.139":"qa5" 18 } 19 not_exist ={} 20 port =22 21 user = "root" 22 passwd = "B^Dc%4LSBvhZZK3B" 23 print "\033[32;1m****使用说明:该脚本可以判断文件,不能判断目录。****\033[0m" 24 while True: 25 choice = raw_input("请输入要查询远端服务器上文件的绝对路径:") 26 v = "ls" 27 c = v + " " +choice 28 print c 29 for i in host_dic: 30 ssh = paramiko.SSHClient() 31 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 32 ssh.connect(i,port,user,passwd) 33 stdin, stdout, stderr = ssh.exec_command(c) 34 result = stdout.read() 35 #print result 36 if result != "": 37 print host_dic.get(i),"\033[31;1m上存在该文件\033[0m" 38 39 #print host_dic.get(i),"\033[33;1m上存在该文件\033[0m" 40 ssh.close() 41 #print not_exist 42 # choice1 = raw_input("按任意键继续查询,按t拷贝本地一个文件到不存在该文件的机器上,按q退出:") 43 # if choice1 =="q": 44 # print "感谢使用,再见" 45 # print exit() 46 # elif choice == "t": 47 # local_file = raw_input("请输入要同步的文件的绝对路径:") 48 # remote_file = raw_input("请输入要复制到远端机器的绝对路径:") 49 # for j in not_exist: 50 # scp = paramiko.SSHClient() 51 # scp.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 52 # scp.connect(j,port,user,passwd) 53 # sftp = paramiko.SFTPClient.from_transport(scp.get_transport()) 54 # sftp = scp.open_sftp() 55 # sftp.put(local_file,remote_file) 56 # print "已复制到",j 57 # 58 # 59 # # def ssh_scp_get(ip, port, user, password, remote_file, local_file): 60 # # ssh = paramiko.SSHClient() 61 # # ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 62 # # ssh.connect(ip, 22, 'root', password) 63 # # a = ssh.exec_command('date') 64 # # stdin, stdout, stderr = a 65 # # print stdout.read() 66 # # sftp = paramiko.SFTPClient.from_transport(ssh.get_transport()) 67 # # sftp = ssh.open_sftp() 68 # # sftp.get(remote_file, local_file) 69 # 70 # 71 # 72 # 73 #
sql
1 # -*- coding:utf-8 -*- 2 import paramiko,os,sys,time,json 3 4 def ssh_scp_put(ip,port,user,password,local_file,remote_file): 5 ssh = paramiko.SSHClient() 6 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 7 ssh.connect(ip, 22, 'root', password) 8 a = ssh.exec_command('date') 9 stdin, stdout, stderr = a 10 print stdout.read() 11 sftp = paramiko.SFTPClient.from_transport(ssh.get_transport()) 12 sftp = ssh.open_sftp() 13 sftp.put(local_file, remote_file) 14 15 def ssh_scp_get(ip, port, user, password, remote_file, local_file): 16 ssh = paramiko.SSHClient() 17 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 18 ssh.connect(ip, 22, 'root', password) 19 a = ssh.exec_command('date') 20 stdin, stdout, stderr = a 21 print stdout.read() 22 sftp = paramiko.SFTPClient.from_transport(ssh.get_transport()) 23 sftp = ssh.open_sftp() 24 sftp.get(remote_file, local_file) 25 26 def ssh_cmd(ip,port,cmd,user,passwd): 27 result = "" 28 try: 29 ssh = paramiko.SSHClient() 30 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 31 ssh.connect(ip,port,user,passwd) 32 stdin, stdout, stderr = ssh.exec_command(cmd) 33 result = stdout.read() 34 print result 35 ssh.close() 36 except: 37 print "ssh_cmd err." 38 return result 39 40 41 host_dic = { 42 # "10.10.83.96":"s2", 43 # "10.10.39.70":"s3", 44 # "10.10.46.120":"s4", 45 # "10.10.15.128":"s5", 46 # "10.10.84.48":"s6", 47 "s7":"10.10.123.96", 48 # "10.10.105.91":"qa1", 49 # "10.10.92.48":"qa2", 50 # "10.10.50.30":"qa3", 51 # "10.10.40.136":"qa4", 52 # "10.10.189.139":"qa5" 53 } 54 55 db_info = { 56 "sunif":'''sunif/"sun123jfdbc$"''', 57 "sunfcbp":'''sunfcbp/"fcbp2016$a"''', 58 "ltts":'''cbmain_user/"cbmuser123~"''', 59 "sump":'''sump/"smp123~ab"''' 60 61 } 62 63 64 port = 22 65 user = "root" 66 user1 = "oracle" 67 pwd = "B^Dc%4LSBvhZZK3B" 68 pwd1= "Qaoracle" 69 #cmd = "sh /mnt/clear.sh %s" 70 choice_host = raw_input("请输入要执行sql的机器名称:") 71 local_file = raw_input("请输入要执行sql文件的绝对路径:") 72 remote_file = "/mnt/tmp.sql" 73 remote_file2 = "/mnt/sql-log.txt" 74 local_file2 = "C:/Users/Administrator/PycharmProjects/learn/work/tmp-log.txt" 75 #复制本地的sql文件到指定机器 76 ssh_scp_put(host_dic[choice_host],port,user,pwd,local_file,remote_file) 77 print "\033[32;1m已复制到 %s\033[0m"%host_dic.get(choice_host) 78 choice_user = raw_input("请输入要登录的用户:") 79 if choice_user in db_info: 80 a = db_info.get(choice_user) 81 cmd = "sh /mnt/clear.sh %s"%a 82 # #执行这个sql文件 83 ssh_cmd(host_dic[choice_host],port,cmd,user1,pwd1) 84 # #把日志传回 85 ssh_scp_get(host_dic[choice_host],port,user,pwd,remote_file2,local_file2)
作业加强版
1 import os 2 def open_file(filename): 3 with open(filename,"r",encoding="utf-8") as r_file: 4 tag = False 5 for r_line in r_file: 6 tmp = r_line.strip() 7 tmp2 = tmp.split 8 print (tmp2) 9 return open_file 10 11 def fetch(): 12 pass 13 14 def add(): 15 pass 16 17 def remove(): 18 pass 19 20 def update(): 21 pass 22 23 24 if __name__ == '__main__': 25 msg='''\033[32;1m 26 1:查询 27 2:添加 28 3:删除 29 4:修改 30 5:退出 31 \033[0m''' 32 menu_dic={ 33 '1':"fetch", 34 '2':"add", 35 '3':"remove", 36 '4':"update", 37 '5':exit, 38 } 39 print("\033[32;1m***********************欢迎来到员工管理系统**************************\033[0m") 40 while True: 41 print(msg) 42 choice = input("操作>>:").strip() 43 if len(choice) == 0 or choice not in menu_dic: 44 continue 45 elif choice =="5":exit() 46 elif choice =="1": 47 data = input("请输入查询语句>>:") 48 if "where age" in data: 49 f = fetch() 50 print (f[1])
1 import paramiko 2 import os 3 4 user = "root" 5 ips = "10.10.123.96" 6 password = "B^Dc%4LSBvhZZK3B" 7 port = 22 8 9 10 class Tools(object): 11 '''远程执行命令,文件上传,文件下载''' 12 def __init__(self,user,password,port,ips): 13 self.user = user 14 self.password = password 15 self.port = port 16 self.ip = ips 17 18 def connect(self): 19 ssh = paramiko.SSHClient() 20 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 21 ssh.connect(self.ip, self.port, self.user, self.password) 22 23 def cmd(self): 24 cmd = input("请输入要执行的命令:>>") 25 ssh.exec_command(cmd) 26 #result = stdout.read() 27 28 #return result 29 30 def put(self): 31 '''上传''' 32 local_file_abs = input("本地文件的绝对路径:>>") 33 remote_file_abs = input("远程文件的绝对路径:>>") 34 transport = paramiko.Transport(self.ip,self.port) 35 transport.connect(self.user,self.password) 36 sftp = paramiko.SFTPClient.from_transport(transport) 37 sftp.put(local_file_abs,remote_file_abs) 38 transport.close() 39 def get(self): 40 '''下载''' 41 remote_file_abs = input("远程文件的绝对路径:>>") 42 local_file_abs = input("本地文件的绝对路径:>>") 43 transport = paramiko.Transport(self.ip,self.port) 44 transport.connect(self.user, self.password) 45 sftp = paramiko.SFTPClient.from_transport(transport) 46 sftp.get(remote_file_abs,local_file_abs) 47 transport.close() 48 obj = Tools(user,password,port,ips) 49 50 if __name__ == "__main__": 51 msg = ''' 52 执行命令 >>输入cmd 53 上传文件 >>输入put 54 下载文件 >>输入get 55 退出 >>输入q 56 ''' 57 while True: 58 print(msg) 59 inp = input("请输入:>>") 60 if len(inp) == 0:continue 61 elif inp == "q":exit() 62 if hasattr(obj,inp): 63 getattr(obj,inp)() 64 else: 65 print("输入有误,请重新输入") 66 continue
FTPclient
1 import optparse 2 import socket 3 import json 4 5 STATUS_CODE = { 6 250 : "Invalid cmd format, e.g: {'action':'get','filename':'test.py','size':344}", 7 251 : "Invalid cmd ", 8 252 : "Invalid auth data", 9 253 : "Wrong username or password", 10 254 : "Passed authentication", 11 } 12 class FTPClient(object): 13 def __init__(self): 14 parser = optparse.OptionParser() 15 parser.add_option("-s","--server",dest="server",help="ftp server ip address") 16 parser.add_option("-P","--port",dest = "port" ,help="port") 17 parser.add_option("-u","--username", dest="username",help = "username") 18 parser.add_option("-p","--password",dest="password",help="password") 19 self.option,self.args = parser.parse_args() 20 self.verify_args(self.option,self.args) 21 self.make_connection() 22 def make_connection(self): 23 self.sock = socket.socket() 24 self.sock.connect((self.option.server,int(self.option.port))) 25 26 def verify_args(self,options,args): 27 if options.username is not None and options.password is not None: 28 pass 29 elif options.username is None and options.password is None: 30 pass 31 else: 32 exit("Err: username and password must be provided together..") 33 34 if int(options.port) > 0 and int(options.port) < 65535: 35 return True 36 else: 37 exit("Err:host port must in 0-65535") 38 39 def authenticate(self): 40 if self.option.username: 41 print(self.option.username,self.option.password) 42 return self.get_auth_result(self.option.username,self.option.password) 43 else: 44 retry_count = 0 45 while retry_count <3: 46 username = input("username:").strip() 47 password = input("password:").strip() 48 return self.get_auth_result(username,password) 49 50 def get_auth_result(self,username,password): 51 data = {"action":"auth", 52 "username":username, 53 "password":password} 54 self.sock.send((json.dumps(data)).encode()) 55 print("信息已发送,等待返回") 56 response = self.get_response() 57 print("recv:",response) 58 if response.get("status_code") == 254: 59 print("Passed authentication!") 60 self.user = username 61 return True 62 else: 63 print(response.get("status_msg")) 64 65 66 67 68 def get_response(self): 69 data = self.sock.recv(1024) 70 print("server res",data) 71 data = json.loads(data.decode()) 72 return data 73 def _get(self): 74 pass 75 76 def _put(self,cmd_list): 77 file_name = cmd_list[1] 78 79 80 81 82 83 def interactive(self): 84 if self.authenticate(): 85 print("---start interactive with %s---" % self.user) 86 while True: 87 choice = input("[%s]:"%self.user).strip() 88 if len(choice) == 0:continue 89 cmd_list = choice.split() 90 if hasattr(self,"_%s"%cmd_list[0]): 91 func = getattr(self,"_%s"%cmd_list[0]) 92 func(cmd_list) 93 else: 94 print("Invalid cmd") 95 96 97 98 99 if __name__ =="__main__": 100 ftp = FTPClient() 101 ftp.interactive()
FTPserver
1 import socketserver 2 import configparser 3 from conf import settings 4 import os 5 import hashlib 6 7 STATUS_CODE = { 8 250 : "Invalid cmd format, e.g: {'action':'get','filename':'test.py','size':344}", 9 251 : "Invalid cmd ", 10 252 : "Invalid auth data", 11 253 : "Wrong username or password", 12 254 : "Passed authentication", 13 255 : "Filename doesn't provided", 14 256 : "File doesn't exist on server", 15 257 : "ready to send file", 16 258 : "md5 verification", 17 259:"Authentication failure" 18 } 19 20 import json 21 class FTPHandler(socketserver.BaseRequestHandler): 22 23 def handle(self): 24 while True: 25 self.data = self.request.recv(1024).strip() 26 print("recv:",self.data) 27 print("client addr:-->",self.client_address[0]) 28 print(self.data) 29 if not self.data: 30 print("client closed......") 31 break 32 data = json.loads(self.data.decode()) 33 if data.get('action') is not None: 34 print("---->",hasattr(self,"_auth")) 35 if hasattr(self,"_%s"%data.get("action")): 36 func = getattr(self,"_%s"%data.get("action")) 37 func(data) 38 else: 39 print("Invalid cmd format, e.g: {'action':'get','filename':'test.py','size':344}") 40 self.send_response(250) 41 else: 42 print("Invalid cmd") 43 self.send_response(251) 44 45 def send_response(self,status_code,data = None): 46 response = {"status_code":status_code,"status_msg":STATUS_CODE[status_code]} 47 if data: 48 response.update(data) 49 self.request.send(json.dumps(response).encode()) 50 51 def _auth(self,*args,**kwargs): 52 data = args[0] 53 user = self.authenticate(data.get("username"),data.get("password")) 54 if user is None: 55 print("Authentication failure") 56 self.send_response(259) 57 else: 58 print("%s Passed authentication"%user["User"]) 59 self.user = user 60 self.send_response(254) 61 62 def authenticate(self,username,password): 63 config = configparser.ConfigParser() 64 config.read(settings.ACCOUNT_FILE) 65 if username in config.sections(): 66 if password == config[username]["Password"]: 67 config[username]["User"] = username 68 return config[username] 69 70 def _get(self): 71 pass 72 73 def _put(self): 74 pass 75 76 def _ls(self): 77 pass
ftpcli
1 import optparse 2 import socket 3 import json 4 import hashlib 5 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 class FTPClient(object): 14 def __init__(self): 15 parser = optparse.OptionParser() 16 parser.add_option("-s","--server",dest="server",help="ftp server ip address") 17 parser.add_option("-P","--port",dest = "port" ,help="port") 18 parser.add_option("-u","--username", dest="username",help = "username") 19 parser.add_option("-p","--password",dest="password",help="password") 20 self.option,self.args = parser.parse_args() 21 print(self.option,self.args) 22 self.verify_args(self.option,self.args) 23 self.make_connection() 24 def make_connection(self): 25 self.sock = socket.socket() 26 self.sock.connect((self.option.server,int(self.option.port))) 27 28 def verify_args(self,options,args): 29 if options.username is not None and options.password is not None: 30 pass 31 elif options.username is None and options.password is None: 32 pass 33 else: 34 exit("Err: username and password must be provided together..") 35 36 if int(options.port) > 0 and int(options.port) < 65535: 37 return True 38 else: 39 exit("Err:host port must in 0-65535") 40 41 def authenticate(self): 42 if self.option.username: 43 print(self.option.username,self.option.password) 44 return self.get_auth_result(self.option.username,self.option.password) 45 else: 46 retry_count = 0 47 while retry_count <3: 48 username = input("username:").strip() 49 password = input("password:").strip() 50 return self.get_auth_result(username,password) 51 52 def get_auth_result(self,username,password): 53 data = {"action":"auth", 54 "username":username, 55 "password":password} 56 self.sock.send((json.dumps(data)).encode()) 57 print("信息已发送,等待返回") 58 response = self.get_response() 59 print("recv:",response) 60 if response.get("status_code") == 254: 61 print("Passed authentication!") 62 self.user = username 63 return True 64 else: 65 print(response.get("status_msg")) 66 67 68 69 70 def get_response(self): 71 data = self.sock.recv(1024) 72 print("server res",data) 73 data = json.loads(data.decode()) 74 return data 75 def _get(self,cmd_list): 76 print("get-->",cmd_list) 77 if len(cmd_list) == 1: 78 print("没有输入要下载的文件名") 79 return 80 data_header = {"action":"get","filename":cmd_list[1]} 81 self.sock.send(json.dumps(data_header).encode()) 82 response = self.get_response() 83 if response.get("status_code") == 257: 84 self.sock.send(b"a") 85 remote_file_size = response.get("file_size") 86 received_size = 0 87 base_file_name = cmd_list[1].split()[-1] 88 f = open(base_file_name,"wb") 89 m = hashlib.md5() 90 while received_size < remote_file_size: 91 data = self.sock.recv(1024) 92 received_size += len(data) 93 f.write(data) 94 m.update(data) 95 96 else: 97 print("file is received done!") 98 local_md5 = m.hexdigest() 99 remote_md5 = self.sock.recv(1024).decode() 100 print(local_md5,remote_md5) 101 if local_md5 == remote_md5:print("文件一致性校验成功!") 102 else:print("文件一致性校验失败,数据可能不完整!") 103 else: 104 print(response.get("status_msg")) 105 106 107 108 109 110 111 112 113 def _put(self,cmd_list): 114 pass 115 116 def _ls(self,cmd_list): 117 data = cmd_list 118 msg={"action":data[0],"dir":data[1]} 119 self.sock.send(json.dumps(msg).encode()) 120 data = self.get_response() 121 file_list = data.get("file_list") 122 print( file_list) 123 return file_list 124 125 126 127 def interactive(self): 128 if self.authenticate(): 129 print("---start interactive with %s---" % self.user) 130 while True: 131 choice = input("[%s]:"%self.user).strip() 132 if len(choice) == 0:continue 133 cmd_list = choice.split() 134 if hasattr(self,"_%s"%cmd_list[0]): 135 func = getattr(self,"_%s"%cmd_list[0]) 136 func(cmd_list) 137 else: 138 print("Invalid cmd") 139 140 141 142 143 if __name__ =="__main__": 144 ftp = FTPClient() 145 ftp.interactive()
ftpser
1 import socketserver 2 import configparser 3 from conf import settings 4 import os 5 import hashlib 6 7 STATUS_CODE = { 8 250 : "Invalid cmd format, e.g: {'action':'get','filename':'test.py','size':344}", 9 251 : "Invalid cmd ", 10 252 : "Invalid auth data", 11 253 : "Wrong username or password", 12 254 : "Passed authentication", 13 255 : "Filename doesn't provided", 14 256 : "File doesn't exist on server", 15 257 : "ready to send file", 16 258 : "md5 verification", 17 259:"Authentication failure", 18 200:"OK" 19 } 20 21 import json 22 class FTPHandler(socketserver.BaseRequestHandler): 23 24 def handle(self): 25 while True: 26 self.data = self.request.recv(1024).strip() 27 print("recv:",self.data) 28 print("client addr:-->",self.client_address[0]) 29 print(self.data) 30 if not self.data: 31 print("client closed......") 32 break 33 data = json.loads(self.data.decode()) 34 if data.get('action') is not None: 35 print("---->",hasattr(self,"_auth")) 36 if hasattr(self,"_%s"%data.get("action")): 37 func = getattr(self,"_%s"%data.get("action")) 38 func(data) 39 else: 40 print("Invalid cmd format, e.g: {'action':'get','filename':'test.py','size':344}") 41 self.send_response(250) 42 else: 43 print("Invalid cmd") 44 self.send_response(251) 45 46 def send_response(self,status_code,data = None): 47 response = {"status_code":status_code,"status_msg":STATUS_CODE[status_code]} 48 if data: 49 response.update(data) 50 self.request.send(json.dumps(response).encode()) 51 52 def _auth(self,*args,**kwargs): 53 data = args[0] 54 user = self.authenticate(data.get("username"),data.get("password")) 55 if user is None: 56 print("Authentication failure") 57 self.send_response(259) 58 else: 59 print("%s Passed authentication"%user["User"]) 60 self.user = user 61 self.send_response(254) 62 63 def authenticate(self,username,password): 64 config = configparser.ConfigParser() 65 config.read(settings.ACCOUNT_FILE) 66 if username in config.sections(): 67 if password == config[username]["Password"]: 68 config[username]["User"] = username 69 return config[username] 70 71 def _get(self,*args,**kwargs): 72 print("-->get") 73 data = args[0] 74 file_name = data.get("filename") 75 print("获取的文件名:",file_name) 76 self.user_home_dir = "%s/%s"%(settings.USER_HOME,self.user["User"]) 77 self.file_abs_dir = "%s/%s"%(self.user_home_dir,file_name) 78 print("file abs path:",self.file_abs_dir) 79 if os.path.isfile(self.file_abs_dir): 80 file_size = os.path.getsize(self.file_abs_dir) 81 datas = {"file_size":file_size} 82 self.send_response(257,datas) 83 print("ready to send file") 84 self.request.recv(1024) 85 file_obj = open(self.file_abs_dir,"rb") 86 m = hashlib.md5() 87 for line in file_obj: 88 self.request.send(line) 89 m.update(line) 90 else: 91 file_obj.close() 92 md5 = m.hexdigest() 93 print("file send finish") 94 print("MD5值:",md5) 95 self.request.send(md5.encode()) 96 97 else: 98 print("remote file not found") 99 self.send_response(256) 100 101 102 def _put(self): 103 pass 104 105 def _ls(self,*args): 106 data = args[0] 107 cmd = data.get("action") 108 dir = data.get("dir") 109 if dir == "." or dir =="": 110 pass 111 elif dir == "/": 112 user_home_files = "%s/%s" % (settings.USER_HOME, self.user["User"]) 113 file_list = os.listdir(user_home_files) 114 self.send_response(200,data ={"file_list":file_list})

浙公网安备 33010602011771号