def test_gen_random_str(): times = 0 while True: a = gen_random_str(20) b = gen_random_str(20) assert a != b times += 1 if times >= 100: break
def addsite(cfgparser_obj): """ Add a site's configuration """ params = cfgparser_obj.has_dict() params['db']['password'] = gen_database() params['secret'] = gen_random_str(25) process_templates(params)
def create_new_session() -> SessionDto: """Создает новую запись в таблице 'sessions'""" token = gen_random_str(20) now = datetime.now() c = connection.cursor() c.execute( "INSERT INTO sessions (token, created_at, updated_at) VALUES (%s, %s, %s);", (token, now, now), ) connection.commit() return SessionsService.get_session_by_token(token)
def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) mobile = serializer.validated_data['mobile'] code = gen_random_str() sms_response = Tencent_SMS(mobile, code).send_code() if sms_response['errmsg'] != 'OK': return Response({'mobile': sms_response['errmsg']}, status=status.HTTP_400_BAD_REQUEST) else: code_record = VerifyCode(mobile=mobile, code=code) code_record.save() return Response({'mobile': mobile}, status=status.HTTP_201_CREATED)
def init_db(mysql_root_pass): import db import platform logging.info('download phpmyadmin and config') utils.exec_cmd('axel -q -n 10 -o /tmp/lamp/phpmyadmin.tar.xz http://softlayer-ams.dl.sourceforge.net/project/phpmyadmin/phpMyAdmin/4.1.8/phpMyAdmin-4.1.8-all-languages.tar.xz') utils.exec_cmd('tar xf /tmp/lamp/phpmyadmin.tar.xz -C /var/www') utils.exec_cmd('mv /var/www/phpMyAdmin* /var/www/phpmyadmin') data = db.Connection(host='localhost',database='mysql',user='******',password=mysql_root_pass) # Support centos change all root pass data.execute("SET PASSWORD FOR 'root'@'127.0.0.1' = PASSWORD('%s');" % (mysql_root_pass)) data.execute("SET PASSWORD FOR 'root'@'%s' = PASSWORD('%s');" % (platform.uname()[1], mysql_root_pass)) # Create lamp&phpmyadmin control user lamp_controluser_pass = utils.gen_random_str() logging.debug('generate control user password : %s', lamp_controluser_pass) data.execute('CREATE USER "lamp"@"localhost" IDENTIFIED BY \"%s\";CREATE DATABASE IF NOT EXISTS `lamp`;GRANT ALL PRIVILEGES ON *.* TO "lamp"@"localhost" WITH GRANT OPTION;' % (lamp_controluser_pass)) # Clean up default users data.execute('delete from mysql.user where user="";') data.execute("DROP USER ''@'%%';") #data.execute('delete from mysql.user where user = "******" and host != "localhost";flush privileges') data.execute("flush privileges;") del data utils.exec_cmd('mysql -uroot -p%s < %s/files/create_tables.sql' % (mysql_root_pass, os.path.dirname(os.path.abspath(__file__)))) utils.cp('<APPROOT>/files/phpmyadmin_config.inc.php', '/var/www/phpmyadmin/config.inc.php') utils.change_conf('/var/www/phpmyadmin/config.inc.php', [ {'old':'lamp_pass_value','new':lamp_controluser_pass}, {'old':'blowfish_secret_value','new':utils.gen_random_str(20)} ] ) return lamp_controluser_pass
def reset_mysql_pass(arg=None): m = check_mysql_id(arg) import db config = utils.load_config() data = db.Connection(host='127.0.0.1',database='lamp',user=config['lampuser'],password=config['lamppass']) user_pass = utils.gen_random_str() try: data.execute('UPDATE mysql.user SET password=PASSWORD(\'%s\') WHERE user=\'%s\'' % (user_pass, m[1])) data.execute('FLUSH PRIVILEGES') except Exception,e: logging.info('delete mysql and database has some errors : %s', str(e)) sys.exit(1)
def adduser(login="******", name="Majerti", firstname="Admin", primary_group="1"): """ Add a user to the database """ password = gen_random_str(10) md5_pass = md5(password).hexdigest() cmd = "echo \"INSERT INTO egw_accounts (account_lid, account_pwd, account_firstname, \ account_lastname, account_status, account_primary_group, \ account_email) VALUES ('{0}', '{1}', '{2}', '{3}', 'A', '{4}', \ '*****@*****.**');\" | mysql -uroot autonomie" .format(login, md5_pass, firstname, name, primary_group) launch_cmd(cmd) print "New password : {0}".format(password)
def adduser(login="******", name="Majerti", firstname="Admin", primary_group="1"): """ Add a user to the database """ password = gen_random_str(10) md5_pass = md5(password).hexdigest() cmd = "echo \"INSERT INTO egw_accounts (account_lid, account_pwd, account_firstname, \ account_lastname, account_status, account_primary_group, \ account_email) VALUES ('{0}', '{1}', '{2}', '{3}', 'A', '{4}', \ '*****@*****.**');\" | mysql -uroot autonomie".format( login, md5_pass, firstname, name, primary_group) launch_cmd(cmd) print "New password : {0}".format(password)
def gen_database(dbname="autonomie", user="******"): """ generates a database and a specific user and generates a random password """ password = gen_random_str() if os.path.isdir("/var/lib/mysql/{0}".format(dbname)): print "The database {0} already exists, only modifying password".format( dbname) sql_cmds = get_sql_grant_cmds(user, password, dbname) else: sql_cmds = get_sql_create_cmds(user, password, dbname) sql_cmds.extend(get_sql_grant_cmds(user, password, dbname)) for sql_cmd in sql_cmds: bash_cmd = get_bash_cmd(sql_cmd) launch_cmd(bash_cmd) return password
def save_book(category, file): filename = secure_filename(''.join(lazy_pinyin(file.filename))) to_save_file = EBOOKS_PATH + category + '/' + filename print(to_save_file) if os.path.exists(to_save_file): print(to_save_file, '已存在') filename = gen_random_str(6) + '_' + filename to_save_file = EBOOKS_PATH + category + '/' + filename file.save(to_save_file) # 存储好pdf文件之后,需要生成对应的封面图片 file_tuple = os.path.splitext(filename) nosuffix_name = file_tuple[0] # 把封面图片命名为'分类-书名.png'的格式 cover_image_name = f'{category}+{nosuffix_name}' gen_cover_image(to_save_file, cover_image_name)
def create_mysql_ftpuser(args): import db config = utils.load_config() data = db.Connection(host='127.0.0.1',database='lamp',user=config['lampuser'],password=config['lamppass']) #check exists site #FIXME: can create cross dir ftp site = data.get('SELECT domain, site_root FROM lamp.lamp__sites WHERE id = %i' % args['site_id']) if site == None: logging.info('input site is not exists...') return user_pass = utils.gen_random_str() logging.debug('generate ftp root password : %s, site domain: %s', user_pass, site['domain']) try: data.execute('INSERT INTO `lamp`.`lamp__ftp` (`id`, `site_id`, `username`, `password`, `local_root`) VALUES (NULL, %i, \'%s\', password(\'%s\'), \'%s\');' % (args['site_id'], args['username'], user_pass, args['path'])) except Exception,e: logging.info('insert ftpuser to mysql has some errors : %s', str(e)) user_pass = ''
def create_mysqluser(args): import db config = utils.load_config() data = db.Connection(host='127.0.0.1',database='lamp',user=config['lampuser'],password=config['lamppass']) if data.get('SELECT USER FROM mysql.user where user = \"%s\"' % args['username']): logging.info('mysql user already exists, exiting...') return None logging.debug('create mysql user and database: %s', args['username']) user_pass = utils.gen_random_str() try: # create user data.execute('CREATE USER \"%s\"@"localhost" IDENTIFIED BY \"%s\";' % (args['username'], user_pass)) data.execute('CREATE DATABASE IF NOT EXISTS `%s`' % (args['username'])) data.execute('GRANT ALL PRIVILEGES ON `%s`.* TO \"%s\"@"localhost";' % (args['username'], args['username'])) # create user info data.execute('INSERT INTO `lamp`.`lamp__mysql` (`id`, `site_id`, `login_name`) VALUES (NULL, %i, \"%s\");' % (args['site_id'], args['username'])) except Exception,e: logging.info('create mysql user has some errors : %s', e) user_pass = None
def pull_image(self, repository, tag=None, username=None, password=None): _, _, _, _tag = parse_image_name(repository) if not tag: tag = _tag auth_config = None if username and password: auth_config = dict(username=username, password=password) resp = self.pull(repository, tag, stream=True, insecure_registry=True, auth_config=auth_config) def iter_json(): for i in resp: i = i.strip() if not i: continue try: j = json.loads(i) yield j except ValueError: continue layers = {} for j in iter_json(): if j.get('status') == 'Pulling fs layer': layers[j.get('id')] = {} elif layers or j.get('status') == 'Downloading': break elif 'error' in j: if 'not found' in j['error']: raise NotFound(j) else: raise APIException(j) def iter_progress(): for _j in iter_json(): if _j.get('status') == 'Downloading': layers[_j.get('id')] = _j.get('progressDetail') total = None current = None if all(layers): total = sum( [i.get('total', 0) for i in layers.values()]) current = sum( [i.get('current', 0) for i in layers.values()]) yield dict(layer_count=len(layers), layers=layers, current=current, total=total, percent=current * 100 / total, finished=False) task_id = 'p_%s' % gen_random_str(8) def consume(): cache = Cache() for i in iter_progress(): cache.set(task_id, i) cache.set(task_id, {'finished': True, 'percent': 100}) gevent.spawn(consume) # consume() return task_id
def go_debian(): raw_input("LAMP Setup script is ready install it\nPress Enter key to continue, Press Ctrl+D to cancel the installation\n") #generate config file os.mkdir('/tmp/lamp') os.mkdir('/etc/lamp') os.mkdir('/root/lamp_bak') os.mkdir('/etc/lamp/ftp_users') config = {} global version config['version'] = version config['system'] = 'u' config['wwwroot'] = '/var/www' config['apache_etc'] = '/etc/apache2' config['apache'] = 'apache2' config['ftproot'] = '/var/www' config['vsftpd_conf_path'] = '/etc/vsftpd.conf' config['root_own'] = 'www-data:www-data' ''' logging.info('download files ...') utils.exec_cmd('wget http://s1b-static.yuki.ws/files/lamp/files.tar.xz -O /tmp/lamp/files.tar.xz') utils.exec_cmd('tar xvf /tmp/lamp/files.tar.xz -C /tmp/lamp') ''' #setting mysql passwotrd mysql_root_pass = utils.gen_random_str() config['mysqlrootpass'] = mysql_root_pass utils.save_config(config) logging.debug('generate mysql root password : %s', mysql_root_pass) debconf_tmp = open('/tmp/lamp/debconf.tmp', 'w+') debconf_tmp.write('mysql-server mysql-server/root_password password %s\nmysql-server mysql-server/root_password_again password %s\n' % (mysql_root_pass, mysql_root_pass)) debconf_tmp.write('iptables-persistent iptables-persistent/autosave_v4 boolean true\niptables-persistent iptables-persistent/autosave_v6 boolean true\n') debconf_tmp.close() utils.exec_cmd('debconf-set-selections /tmp/lamp/debconf.tmp') os.remove('/tmp/lamp/debconf.tmp') del debconf_tmp logging.info('update data packages info...') utils.exec_cmd('apt-get update') logging.info('update system, please wait...') #utils.exec_cmd('apt-get upgrade -y') logging.info('install and config packages, please wait...') utils.exec_cmd('apt-get install -y vim axel curl unzip build-essential python-mysqldb python-software-properties php5 apache2 libapache2-mod-php5 mysql-server php5-mysql php5-curl php5-gd php5-mcrypt php5-imagick php5-memcached php5-sqlite php5-xcache iptables-persistent libpam-mysql') logging.info('setting up web-server...') logging.debug('setting apache conf') httpd_conf = open('/etc/apache2/httpd.conf', 'w') httpd_conf.write('ServerName %s\n' % (platform.uname()[1])) httpd_conf.close() del httpd_conf utils.change_conf('/etc/apache2/apache2.conf', [ {'old':'Timeout 300','new':'Timeout 45'}, {'old':'MaxKeepAliveRequests 100','new':'MaxKeepAliveRequests 200'} ] ) utils.change_conf('/etc/apache2/conf.d/security', [ {'old':'ServerTokens OS','new':'ServerTokens Prod'}, {'old':'ServerSignature On','new':'ServerSignature Off'} ] ) # Enable mod-rewrite utils.exec_cmd('a2enmod rewrite') # Set apache php.ini logging.debug('Setting php.ini') utils.change_conf('/etc/php5/apache2/php.ini', [ {'old':'post_max_size = 8M','new':'post_max_size = 50M'}, {'old':'upload_max_filesize = 2M','new':'upload_max_filesize = 50M'}, {'old':'expose_php = On','new':'expose_php = Off'}, {'old':'display_errors = Off','new':'display_errors = On'}, {'old':';date.timezone =','new':'date.timezone = Asia/Chongqing'}, {'old':'request_order = "GP"','new':'request_order = "CGP"'} ] ) # Change default www dir utils.exec_cmd('mkdir -p /var/www/public_html') utils.exec_cmd('mv /var/www/index.html /var/www/public_html/') utils.change_conf('/etc/apache2/sites-enabled/000-default', [{'old':'/var/www','new':'/var/www/public_html'}]) # Init phpmyadmin and lamp user pass utils.exec_cmd('service mysql restart') lamp_controluser_pass = mysql.init_db(mysql_root_pass) utils.cp('<APPROOT>/files/phpmyadmin_host', '/etc/apache2/mods-available/phpmyadmin.conf') utils.exec_cmd('ln -s /etc/apache2/mods-available/phpmyadmin.conf /etc/apache2/mods-enabled/phpmyadmin.conf') config['lampuser'] = '******' config['lamppass'] = lamp_controluser_pass utils.save_config(config) # create test php script utils.exec_cmd(r'echo "<?php phpinfo() ?>" > /var/www/public_html/test.php') # Change wwwroot permissions utils.exec_cmd('chown -R www-data:www-data /var/www') utils.exec_cmd('chmod -R go-rwx /var/www') utils.exec_cmd('chmod -R g+rw /var/www') utils.exec_cmd('chmod -R o+r /var/www') utils.exec_cmd('service apache2 restart') logging.info('setting up ftp-server...') # Init ftp and create main account #ftp_pass = ftp.init_ftp() if platform.machine() == 'x86_64': utils.exec_cmd('axel -q -n 3 -o /tmp/lamp/vsftpd.deb http://ftp.jaist.ac.jp/pub/Linux/ubuntu/pool/main/v/vsftpd/vsftpd_3.0.2-1ubuntu1_amd64.deb') #add fix 12.04 pam.d-mysql bugs "libgcc_s.so.1 must be installed for pthread_cancel to work" utils.exec_cmd('DEBIAN_FRONTEND=noninteractive apt-get install -qq libpam-ldap') else: utils.exec_cmd('axel -q -n 3 -o /tmp/lamp/vsftpd.deb http://ftp.jaist.ac.jp/pub/Linux/ubuntu/pool/main/v/vsftpd/vsftpd_3.0.2-1ubuntu1_i386.deb') returncode = utils.exec_cmd('dpkg -i /tmp/lamp/vsftpd.deb') if returncode == 2: logging.debug('install vsftpd failed!') utils.change_conf('<APPROOT>/files/vsftpd_conf', [ {'old':'<ftpuser>','new':'ftp'}, {'old':'<guestuser>','new':'www-data'} ], '/etc/vsftpd.conf') #add fix 500 OOPS: priv_sock_get_cmd if platform.machine() == 'x86_64': utils.change_conf('/etc/vsftpd.conf', [{'old':'ftp_users','new':'ftp_users\nseccomp_sandbox=NO'}]) utils.change_conf('<APPROOT>/files/vsftpd_mysql', [{'old':'<passwd>','new':lamp_controluser_pass}], '/etc/pam.d/vsftpd-mysql') #set master ftp account args = {} args['username'] = '******' args['path'] = '/var/www' args['site_id'] = 1 ftp_pass = ftp.create_ftp(args) utils.exec_cmd('service vsftpd restart') logging.info('setting up system...') # Set iptables utils.cp('<APPROOT>/files/iptables_rules', '/etc/iptables/rules.v4') utils.exec_cmd('service iptables-persistent restart') #load kernel ip_nat_ftp utils.exec_cmd('modprobe nf_nat_ftp') utils.exec_cmd('echo "nf_nat_ftp" >> /etc/modules') # Add auto start at boot utils.exec_cmd('update-rc.d apache2 defaults') utils.exec_cmd('update-rc.d mysql defaults') utils.exec_cmd('update-rc.d vsftpd defaults') finish_install(mysql_root_pass, ftp_pass, 'apt-get upgrade -y')
def go_centos(): raw_input("LAMP Setup script is ready install it\nPress Enter key to continue, Press Ctrl+D to cancel progress\n") #generate config file os.mkdir('/tmp/lamp') os.mkdir('/etc/lamp') os.mkdir('/root/lamp_bak') os.mkdir('/etc/lamp/ftp_users') config = {} global version config['version'] = version config['system'] = 'c' config['wwwroot'] = '/var/www' config['apache_etc'] = '/etc/httpd' config['apache'] = 'httpd' config['ftproot'] = '/var/www' config['vsftpd_conf_path'] = '/etc/vsftpd/vsftpd.conf' config['root_own'] = 'apache:apache' #setting mysql passwotrd mysql_root_pass = utils.gen_random_str() config['mysqlrootpass'] = mysql_root_pass utils.save_config(config) logging.debug('generate mysql root password : %s', mysql_root_pass) logging.info('load yum repo...') utils.exec_cmd('yum install yum-priorities -y') utils.exec_cmd('wget http://s1b-static.yuki.ws/files/lamp/files.tar.xz -O /tmp/lamp/files.tar.xz') utils.exec_cmd('tar xvf /tmp/lamp/files.tar.xz -C /tmp/lamp') # Get system detail info machine = platform.machine() if machine == 'i686': machine = 'i386' ver = platform.dist()[1] if ver >= 6: ver = 6 utils.exec_cmd('wget http://ftp.riken.jp/Linux/fedora/epel/6/%s/epel-release-6-8.noarch.rpm -O /tmp/lamp/epel-release.rpm' % (machine)) utils.exec_cmd('wget http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.3-1.el6.rf.%s.rpm -O /tmp/lamp/rpmforge-release.rpm' % (platform.machine())) #download vsftpd utils.exec_cmd('wget http://centos.alt.ru/repository/centos/6/%s/vsftpd-3.0.2-2.el6.%s.rpm -O /tmp/lamp/vsftpd.rpm' %(machine, platform.machine())) else: ver = 5 utils.exec_cmd('wget http://ftp.riken.jp/Linux/fedora/epel/5/%s/epel-release-5-4.noarch.rpm -O /tmp/lamp/epel-release.rpm' % (machine)) utils.exec_cmd('wget http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.3-1.el5.rf.%s.rpm -O /tmp/lamp/rpmforge-release.rpm' % (machine)) utils.exec_cmd('wget http://centos.alt.ru/repository/centos/5/%s/vsftpd-3.0.2-1.el5.%s.rpm -O /tmp/lamp/vsftpd.rpm' %(platform.machine(), platform.machine())) utils.exec_cmd('yum localinstall /tmp/lamp/*-release.rpm -y') # Change yum priority utils.change_conf('/etc/yum.repos.d/CentOS-Base.repo', [{'old':'gpgcheck=1','new':'priority=1\ngpgcheck=1'}]) utils.change_conf('/etc/yum.repos.d/rpmforge.repo', [{'old':'enabled =','new':'priority = 10\nenabled ='}]) utils.change_conf('/etc/yum.repos.d/epel.repo', [{'old':'enabled=','new':'priority=11\nenabled='}]) logging.info('update system, please wait...') utils.exec_cmd('yum makecache') #utils.exec_cmd('yum update -y') logging.info('install and config packages, please wait...') utils.exec_cmd('yum install axel screen MySQL-python vim pam_mysql httpd mysql-server php php-mysql php-pdo php-mcrypt php-mbstring php-gd php-pecl-imagick php-pecl-memcached php-xcache -y') logging.info('setting up web-server...') utils.change_conf('/etc/httpd/conf/httpd.conf', [ {'old':'ple.com:80','new':'ple.com:80\nServerName %s' % (platform.uname()[1])}, {'old':'Timeout 60','new':'Timeout 45'}, {'old':'MaxKeepAliveRequests 100','new':'MaxKeepAliveRequests 200'}, {'old':'ServerTokens OS','new':'ServerTokens Prod'}, {'old':'ServerSignature On','new':'ServerSignature Off'}, {'old':'/var/www/html','new':'/var/www/public_html'}, {'old':'#NameVirtualHost \*:80','new':'NameVirtualHost *:80'}, {'old':'#</VirtualHost>','new':'#</VirtualHost>\nInclude sites-enabled/'} ] ) # Set apache php.ini logging.debug('Setting php.ini') utils.change_conf('/etc/php.ini', [ {'old':'post_max_size = 8M','new':'post_max_size = 50M'}, {'old':'upload_max_filesize = 2M','new':'upload_max_filesize = 50M'}, {'old':'expose_php = On','new':'expose_php = Off'}, {'old':';date.timezone =','new':'date.timezone = Asia/Chongqing'}, {'old':'request_order = "GP"','new':'request_order = "CGP"'} ] ) # Fix mcrypt.ini error utils.change_conf('/etc/php.d/mcrypt.ini', [ {'old':'module.so','new':'mcrypt.so'} ] ) os.mkdir('/etc/httpd/sites-available') os.mkdir('/etc/httpd/sites-enabled') utils.exec_cmd('mv /var/www/html /var/www/public_html') # Create a default site os.mkdir('/var/www/logs') utils.change_conf('<APPROOT>/files/vhost_template', [ {'old':'ServerName <ServerName>','new':''}, {'old':'<ServerName>','new':'default'}, {'old':'<siteroot>','new':'/var/www'} ], '/etc/httpd/sites-enabled/default') # Init phpmyadmin and lamp user pass utils.exec_cmd('service mysqld restart') utils.exec_cmd('mysqladmin -u root password \'%s\'' % (mysql_root_pass)) utils.cp('<APPROOT>/files/phpmyadmin_host', '/etc/httpd/conf.d/phpmyadmin.conf') lamp_controluser_pass = mysql.init_db(mysql_root_pass) config['lampuser'] = '******' config['lamppass'] = lamp_controluser_pass utils.save_config(config) utils.exec_cmd(r'echo "<?php phpinfo() ?>" > /var/www/public_html/test.php') # Change wwwroot permissions utils.exec_cmd('chown -R apache:apache /var/www') utils.exec_cmd('chmod -R go-rwx /var/www') utils.exec_cmd('chmod -R g+rw /var/www') utils.exec_cmd('chmod -R o+r /var/www') utils.exec_cmd('service httpd restart') logging.info('setting up ftp-server...') # Init ftp and create main account utils.exec_cmd('yum localinstall /tmp/lamp/vsftpd.rpm -y') utils.exec_cmd('mkdir -p /var/run/vsftpd') utils.change_conf('<APPROOT>/files/vsftpd_conf', [ {'old':'<ftpuser>','new':'ftp'}, {'old':'<guestuser>','new':'apache'} ], '/etc/vsftpd/vsftpd.conf') utils.change_conf('<APPROOT>/files/vsftpd_mysql', [{'old':'<passwd>','new':lamp_controluser_pass}], '/etc/pam.d/vsftpd-mysql') args = {} args['username'] = '******' args['path'] = '/var/www' args['site_id'] = 1 ftp_pass = ftp.create_ftp(args) utils.exec_cmd('service vsftpd restart') logging.info('setting up system...') # Set iptables utils.cp('<APPROOT>/files/iptables_rules', '/etc/sysconfig/iptables') utils.exec_cmd('service iptables restart') #load kernel ip_nat_ftp utils.exec_cmd('modprobe nf_nat_ftp') utils.exec_cmd('echo "modprobe nf_nat_ftp" >> /etc/sysconfig/modules/nf_nat_ftp.modules') utils.exec_cmd('chmod +x /etc/sysconfig/modules/nf_nat_ftp.modules') # Add auto start at boot utils.exec_cmd('chkconfig httpd on') utils.exec_cmd('chkconfig mysqld on') utils.exec_cmd('chkconfig vsftpd on') finish_install(mysql_root_pass, ftp_pass, 'yum update -y')