Пример #1
0
 def switch(self):
     '''
     close/open socket,run when open ,service closed
     :return:
     '''
     self.sk.sendall("quit".encode()) # quit request
     self.sk.close()#close sk
     log.logger("services").info("User %s disconnect to socket." % self.username)
     self.service = not self.service
     return self.service
Пример #2
0
 def download(self,command,filename):
     '''
     :param command:
     :return:
     '''
     self.sk.sendall(command.encode())#send request
     self.sk.sendall(filename.encode())#send filname
     data = self.sk.recv(settings.MAXSIZE).decode()#receive file
     with open("%s/%s"%(self.path,filename),"w") as f:
         f.write(data)
         log.logger("clients").info("User %s upload." % self.username)
Пример #3
0
 def upload(self,command,filename):
     '''
     excute upload command
     :param command:
     :return:
     '''
     self.sk.sendall(command.encode())#send command
     self.sk.sendall(filename.encode())#send filename
     with open("%s/%s"%(self.path,filename),"r") as f:
         data = f.read()
     self.sk.sendall(data.encode())##send data
     log.logger("clients").info("User %s upload." % self.username)
Пример #4
0
def sign_up(name,psd,role):
    '''
    run when sign up
    :param name: username
    :param psd: passwd
    :param role: '1' or '0'
    :return:
    '''
    with open("%s/%s"%(settings.USER_DATA,name),'wb') as f:
        data =dict(name=name,passwd=psd,role=role)
        pickle.dump(data,f)
        log.logger("userEvents").info("Create user :" ,name)
Пример #5
0
    def __init__(self,username,passwd,role='0'):
        '''
        initialize ,include path,socket
        :param username:
        :param passwd:
        :param role:
        '''
        self.username=username
        self.passwd=passwd
        self.role=role
        self.service=True #turn on service
        self.sk = socket.socket()
        self.path =''
        self.initdir()# initialize dir

        ###connect to server
        ip_port = (settings.ADDR, settings.PORT)
        self.sk.connect(ip_port)
        data = self.sk.recv(settings.MAXSIZE)
        print("\033[1;34;1mConnected to socket!\033[0m",)
        log.logger("services").info("User %s connect to socket." % self.username)
Пример #6
0
def login():
    '''
    run when user login,return user data
    :return:
    '''
    all_users=os.listdir(settings.USER_DATA)
    while True:
        user=input("Input username:"******"Input password:"******"%s/%s"%(settings.USER_DATA,user),'rb') as f:
                data = pickle.load(f)
            if psd == data["passwd"]:
                log.logger("access").info("User %s login."%user)
                return data
            else:
                print("Incorrect passwd!")
                log.logger("access").info("User %s failed login." % user)
        else:
            print("No such user!")
            log.logger("access").info("Unknown user %s failed login." % user)
Пример #7
0
import socket, os, sys
from pathlib import Path
BASEDIR = Path(__file__).parent.parent
sys.path.append(str(BASEDIR))
from conf import settings
from modules import log

ip_port = (settings.ADDR, settings.PORT)
sk = socket.socket()
sk.bind(ip_port)
sk.listen(settings.MAXCONN)  # 最大等待人数
sk.settimeout(settings.TMOUT)
while True:
    conn, address = sk.accept()
    log.logger("server").info("Client [%s] connected ." % conn)
    conn.sendall('Service is on!.'.encode())  #test connect
    Flag = True
    while Flag:
        command = conn.recv(settings.MAXSIZE).decode()
        print("recv command:", command)
        if command == 'upload':  #received request
            filename = conn.recv(settings.MAXSIZE).decode()  # receive filename
            print("filename:", filename)
            data = conn.recv(settings.MAXSIZE).decode()  #receive data
            with open("%s/%s" % (settings.F_SERVER, filename), 'w') as f:
                f.write(data)
                log.logger("server").info("Recv data from [%s] ." % conn)
        elif command == 'download':  #received request
            filename = conn.recv(settings.MAXSIZE).decode()  # receive filename
            print("filename:", filename)
            with open("%s/%s" % (settings.F_SERVER, filename)) as f:
Пример #8
0
class Auth:
    logger = logger()

    def __init__(self, user, pwd):
        self.user = user
        self.pwd = pwd

    # @staticmethod
    # def input_user_info():
    #     print('\n1. 注册\n2. 登录')
    #     while True:
    #         choice = input('>>>').strip()
    #         if not choice: continue
    #         if choice == '1':
    #             pass
    #         elif choice == '2':
    #             pass
    #         else:
    #             print('\033[31;1m序号错误,请重新输入.\033[0m')
    #         user = input('\033[34;1musername:\033[0m').strip()
    #         pwd = input('\033[34;1mpassword:\033[0m').strip()

    def regist(self):
        user_list = self.file_oper(settings.user_file, 'r').split('\n')[:-1]
        print(user_list)
        if self.user not in user_list:
            self.file_oper(settings.user_file, 'a', self.user + '\n')
            user_home_path = os.path.join(settings.home_path, self.user)
            user_db = os.path.join(settings.db_path, self.user) + '.db'
            print('user_db', user_db)
            if not os.path.isdir(user_home_path):
                os.makedirs(user_home_path)
                user_info = {
                    'user': self.user,
                    'pwd': self.pwd,
                    'homepath': user_home_path,
                    'limitsize': 102400
                }
                user_inf_pk = pickle.dumps(user_info)
                self.file_oper(user_db, 'ab', user_inf_pk)
                print('\033[32;1m注册成功.\033[0m')
                logger.info('%s 注册成功.' % self.user)
            else:
                logger.warning('用户家目录已存在.')
        else:
            logger.warning('用户名已存在.')

    def login(self):
        user_list = self.file_oper(settings.user_file, 'r').split('\n')[:-1]
        if self.user in user_list:
            user_db = os.path.join(settings.db_path, self.user) + '.db'
            user_info_pk = self.file_oper(user_db, 'rb')
            user_info = pickle.loads(user_info_pk)
            user = user_info['user']
            pwd = user_info['pwd']
            if self.user == user and self.pwd == pwd:
                print('\033[32;1m登录成功.\033[0m')
                logger.info('用户%s登录成功.' % self.user)
                print(user_info)
                return user_info
            else:
                print('\033[31;1m登录失败.\033[0m')
                logger.warning('用户%s登录失败.' % self.user)
        else:
            print('\033[31;1m用户名不存在.\033[0m')
            logger.warning('用户%s不存在.' % self.user)

    def file_oper(self, file, mode, *args):
        if mode == 'a' or mode == 'ab':
            data = args[0]
            with open(file, mode) as f:
                f.write(data)
        elif mode == 'r' or mode == 'rb':
            with open(file, mode) as f:
                return f.read()

    def user_info(self):
        user_list = []
        with open(settings.user_file) as f:
            for i in f:
                user_list.append(i)
            return user_list