我们从Python开源项目中,提取了以下38个代码示例,用于说明如何使用fabric.api.prompt()。
def bootstrap(branch='master'): env.sudo_password = getpass('Initial value for env.sudo_password: ') env.domain_name = prompt('Enter your domain name:', default='meetup_facebook_bot') create_permanent_folder() create_log_folder() install_postgres() database_url = setup_postgres(username=env.user, database_name=env.user) renew_ini_file(database_url) install_python() fetch_sources_from_repo(branch, PROJECT_FOLDER) reinstall_venv() install_modules() install_nginx() configure_letsencrypt_if_necessary() add_nginx_reload_crontab_job() configure_nginx_if_necessary() setup_ufw() start_systemctl_service(UWSGI_SERVICE_NAME) start_systemctl_service('nginx') run_setup_scripts() status()
def install_uwsgi(self): if self.args.force or prompt(red(' * Install Uwsgi service (y/n)?'), default='y') == 'y': sudo('pip3 install uwsgi') # uwsgi config need real env path with cd(self.python_env_dir): real_env_path = run('pwd') # get user home_user = run('echo $USER') # uwsgi config string django_uwsgi_ini = self.django_uwsgi_ini.format(self.nginx_web_dir, self.project, real_env_path, home_user) # modify uwsgi config file with cd(self.project_dir): if not exists('{0}.ini'.format(self.project)): run('touch {0}.ini'.format(self.project)) put(StringIO(django_uwsgi_ini), '{0}.ini'.format(self.project), use_sudo=True) print(green(' * Installed Uwsgi service in the system.')) print(green(' * Done ')) print()
def common_config_nginx_ssl(self): """ Convert nginx server from http to https """ if prompt(red(' * Change url from http to https (y/n)?'), default='n') == 'y': if not exists(self.nginx_ssl_dir): sudo('mkdir -p {0}'.format(self.nginx_ssl_dir)) # generate ssh key sudo('openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout {0}/cert.key -out {0}/cert.pem'.format(self.nginx_ssl_dir)) # do nginx config config put(StringIO(self.nginx_web_ssl_config), '/etc/nginx/sites-available/default', use_sudo=True) sudo('service nginx restart') print(green(' * Make Nginx from http to https.')) print(green(' * Done')) print()
def install_php(self): if self.args.force or prompt(red(' * Install PHP (y/n)?'), default='y') == 'y': try: sudo('apt-get install php5 php5-cli php5-mysql php5-gd php5-curl libapache2-mod-php5 php5-mcrypt -y') # do apache config put(StringIO(self.apache_dir_index), '/etc/apache2/mods-enabled/dir.conf', use_sudo=True) sudo('service apache2 restart') print(green(' * Installed php5 and php5-mysql in the system.')) except: print(red(' * Install php5 and php5-mysql failed.')) # write phpinfo for test put(StringIO(self.phpinfo), '{0}/info.php'.format(self.apache_web_dir), use_sudo=True) print(green(' * Done')) print()
def demo(): answer = prompt('Are you sure you want to DELETE ALL DATA on "{0}" and replace it with demo data? (type "I am sure" to continue):'.format(env.host_string)) if answer != 'I am sure': abort('Aborted!') password = None while not password: password = prompt('Choose a password:') with temp(): put('radar.sql', 'radar.sql') run_db('drop') run_db('create') run_db('restore radar.sql') # Note: user must be a PostgreSQL superuser to run this run_fixtures('users --password {0}'.format(password)) run_fixtures('patients --patients 95 --no-data') run_fixtures('patients --patients 5 --data')
def create_user(): """Create Remote User.""" email = prompt("Email ") passw = getpass("Password: ") active = prompt("Activate (y/n): ") if len(passw) < 6: print(red("Password length greather than 6 catacters.")) return if active != "y" or active != "n": active = "y" with cd(remote_app_dir): sudo("source env-{{NAMEPROJECT}}/bin/activate && python {{NAMEPROJECT}}/manage.py create_user -n {} -p {} -a {}".format(email, passw, active )) print(green("Creted User."))
def prompt_for_environment_variables(env_vars): for env_var, value in env_vars.items(): if value is None or confirm('%s is set. Change it?' % env_var): env_vars[env_var] = prompt('Enter %s:' % env_var) return env_vars
def download_file(): print ("Checking local disk space...") local("df -h") remote_path = prompt("Enter the remote file path:") local_path = prompt("Enter the local file path:") get(remote_path=remote_path, local_path=local_path) local("ls %s" %local_path)
def upload_file(): print ("Checking remote disk space...") run("df -h") local_path = prompt("Enter the local file path:") remote_path = prompt("Enter the remote file path:") put(remote_path=remote_path, local_path=local_path) run("ls %s" %remote_path)
def remote_server(): env.hosts = ['127.0.0.1'] env.user = prompt('Enter user name: ') env.password = getpass('Enter password: ')
def remote_server(): env.hosts = ['127.0.0.1'] env.user = prompt('Enter your system username: ') env.password = getpass('Enter your system user password: ') env.mysqlhost = 'localhost' env.mysqluser = prompt('Enter your db username: ') env.mysqlpassword = getpass('Enter your db user password: ') env.db_name = ''
def ls_db(): """ List a dbs with size in MB """ if not env.db_name: db_name = prompt("Which DB to ls?") else: db_name = env.db_name query = """SELECT table_schema "DB Name", Round(Sum(data_length + index_length) / 1024 / 1024, 1) "DB Size in MB" FROM information_schema.tables WHERE table_schema = \"%s\" GROUP BY table_schema """ %db_name run_sql(db_name, query)
def empty_db(): """ Empty all tables of a given DB """ db_name = prompt("Enter DB name to empty:") cmd = """ (echo 'SET foreign_key_checks = 0;'; (mysqldump -u%s -p%s --add-drop-table --no-data %s | grep ^DROP); echo 'SET foreign_key_checks = 1;') | \ mysql -u%s -p%s -b %s """ %(env.mysqluser, env.mysqlpassword, db_name, env.mysqluser, env.mysqlpassword, db_name) run(cmd)
def confirm(message): """ Verify a users intentions. """ answer = prompt(message, default="Not at all") if answer.lower() not in ('y', 'yes', 'buzz off', 'screw you'): exit()
def deploy(): """ updates the chosen environment """ if not env.environment: while env.environment not in ("dev", "staging", "production"): env.environment = prompt(red('Please specify target environment ("dev", "staging", or "production"): ')) print globals()["_update_%s" % env.environment]()
def _update_dev(): """ updates development environment """ run("") # password request print if env.full or "y" == prompt(red('Get latest production database (y/n)?'), default="y"): print(green(" * creating production-database dump...")) run('cd ~/db_backups/ && ./backup_db.bsh --latest') print(green(" * downloading dump...")) get("~/db_backups/db_latest.sql", "tmp/db_latest.sql") print(green(" * importing the dump locally...")) local('python manage.py dbshell < tmp/db_latest.sql && rm tmp/db_latest.sql') print if env.full or "y" == prompt('Call prepare_dev command (y/n)?', default="y"): print(green(" * preparing data for development...")) local('python manage.py prepare_dev') print if env.full or "y" == prompt(red('Download media (y/n)?'), default="y"): print(green(" * creating an archive of media...")) run('cd ~/project/myproject/media/ ' '&& tar -cz -f ~/project/myproject/tmp/media.tar.gz *') print(green(" * downloading archive...")) get("~/project/myproject/tmp/media.tar.gz", "tmp/media.tar.gz") print(green(" * extracting and removing archive locally...")) for host in env.hosts: local('cd media/ ' '&& tar -xzf ../tmp/media.tar.gz ' '&& rm tmp/media.tar.gz') print(green(" * removing archive from the server...")) run("rm ~/project/myproject/tmp/media.tar.gz") print if env.full or "y" == prompt(red('Update code (y/n)?'), default="y"): print(green(" * updating code...")) local('git pull') print if env.full or "y" == prompt(red('Migrate database schema (y/n)?'), default="y"): print(green(" * migrating database schema...")) local("python manage.py migrate --no-initial-data") local("python manage.py syncdb") print
def install_nginx(self): if self.args.force or prompt(red(' * Install Nginx (y/n)?'), default='y') == 'y': self.common_install_nginx() # nginx configuration put(StringIO(self.django_uwsgi_with_nginx), '/etc/nginx/sites-enabled/default', use_sudo=True) # restart server sudo('service nginx restart')
def install_supervisor(self): if self.args.force or prompt(red(' * Install Supervisor controller for Uwsgi (y/n)?'), default='y') == 'y': sudo('apt-get install supervisor -y') # supervisor config string supervisor_uwsgi_ini = self.supervisor_uwsgi_ini.format(self.project, self.project_dir) # create supervisor control configruation with cd(self.supervisor_config_dir): if not exists('{0}_sysd.conf'.format(self.project)): sudo('touch {0}_sysd.conf'.format(self.project)) # supervisor control uwsgi config put(StringIO(supervisor_uwsgi_ini), '{0}_sysd.conf'.format(self.project), use_sudo=True) # create supervisor log and error file with cd('/var/log'): if not exists('{0}_out.log'.format(self.project)): sudo('touch {0}_out.log'.format(self.project)) if not exists('{0}_error.log'.format(self.project)): sudo('touch {0}_error.log'.format(self.project)) # enable and start supervisor try: # ubuntu 16 sudo('systemctl enable supervisor') sudo('systemctl start supervisor') except: # ubuntu 14 sudo('supervisorctl reread') sudo('supervisorctl update') sudo('update-rc.d supervisor enable') print(green(' * Installed Supervisor controller in the system.')) print(green(' * Done ')) print()
def prompt_check(self, message): message += ' (y/n)' p_signal = prompt(red(message), default='n') if p_signal == 'y': return True return False
def install_apache(self): if self.args.force or prompt(red(' * Install Apache2 (y/n)?'), default='y') == 'y': self.common_install_apache2()
def install_mysql(self): if self.args.force or prompt(red(' * Install MySql (y/n)?'), default='y') == 'y': self.common_install_mysql()
def update_sys(self): if self.args.force or prompt(red(' * Update system package (y/n)?'), default='y') == 'y': self.common_update_sys()
def install_php(self): if self.args.force or prompt(red(' * Install PHP (y/n)?'), default='y') == 'y': # try install php7 or php5 try: sudo('apt-get install php7.0-fpm php7.0-mysql php7.0-gd php7.0-curl -y') # Find the line, cgi.fix_pathinfo=1, and change the 1 to 0. sed('/etc/php/7.0/fpm/php.ini', ';cgi.fix_pathinfo=1', 'cgi.fix_pathinfo=0', use_sudo=True) # do nginx config put(StringIO(self.nginx_php7_web_config), '/etc/nginx/sites-available/default', use_sudo=True) sudo('service nginx restart') sudo('service php7.0-fpm restart') print(green(' * Installed php7.0 and php7-mysql in the system.')) except: sudo('apt-get install php5-fpm php5-mysql php5-gd php5-curl -y') # Find the line, cgi.fix_pathinfo=1, and change the 1 to 0. sed('/etc/php5/fpm/php.ini', ';cgi.fix_pathinfo=1', 'cgi.fix_pathinfo=0', use_sudo=True) # do nginx config put(StringIO(self.nginx_web_config), '/etc/nginx/sites-available/default', use_sudo=True) sudo('service nginx restart') sudo('service php5-fpm restart') print(green(' * Installed php5 and php5-mysql in the system.')) # write phpinfo for test put(StringIO(self.phpinfo), '{0}/info.php'.format(self.nginx_web_dir), use_sudo=True) print(green(' * Done')) print()
def vagrant_workspace(self): if prompt(red(' * Are you working on the vagrant server (y/n)?'), default='y') == 'y': sudo('mv /var/www/html/ /vagrant/') sudo('cd /var/www/ && ln -s /vagrant/html/ .')
def install_mysql(self): if self.args.force or prompt(red(' * Install MySql (y/n)?'), default='y') == 'y': # python pip mysqlclient dependency sudo('apt-get install python3-dev libmysqlclient-dev -y') self.common_install_mysql()
def install_packages(self): if self.args.force or prompt(red(' * Install Python3 packages into virtual environment (y/n)?'), default='y') == 'y': # go to virtualenv folder with cd(self.python_env_dir): run('./bin/pip install django djangorestframework django-filter markdown mysqlclient') run('./bin/pip freeze') print(green(' * Installed Python3 packages into virtual environment.')) print(green(' * Done ')) print()
def install_project(self): if self.args.force or prompt(red(' * Install Django project at /var/www/html (y/n)?'), default='y') == 'y': # check project folder if not exists(self.nginx_web_dir): sudo('mkdir -p {0}'.format(self.nginx_web_dir)) # go to project folder and create django project with cd(self.nginx_web_dir): sudo('{0}/bin/django-admin startproject {1}'.format(self.python_env_dir, self.project)) sudo('chmod -R 777 {0}/{1}'.format(self.nginx_web_dir, self.project)) print(green(' * Installed Django project at /var/www/html.')) print(green(' * Done ')) print()
def install_mysql(): with settings(hide('warnings', 'stderr'), warn_only=True): result = sudo('dpkg-query --show mysql-server') if result.failed is False: warn('MySQL is already installed') return mysql_password = prompt('Please enter MySQL root password:') sudo('echo "mysql-server-5.5 mysql-server/root_password password ' \ '%s" | debconf-set-selections' % mysql_password) sudo('echo "mysql-server-5.5 mysql-server/root_password_again password ' \ '%s" | debconf-set-selections' % mysql_password) apt_get_install('mysql-server')
def staging(): answer = prompt('Are you sure you want to DELETE ALL DATA on "{0}" and replace it with test data? (type "I am sure" to continue):'.format(env.host_string)) if answer != 'I am sure': abort('Aborted!') run_fixtures('all')
def remote_server(): # Edit this list to include remote hosts env.host = ['127.0.0.1'] env.user = prompt('Enter your system username: ') env.password = getpass('Enter your system user password: ') env.mysqlhost = 'localhost' env.mysqluser = prompt('Enter your db username: ') env.mysqlpassword = getpass('Enter your db user password: ') env.db_name = '' """ Wraps mysql show databases cmd """ q = "show databases" run("echo '%s' | mysql -u%s" %(q, env.mysqluser, env.mysqlpassword))
def run_sql(db_name, query): """ Generic function to run sql """ with cd('/tmp'): run("echo '%s' | mysql -u%s -p%s -D%s" %(query, env.mysqluser, env.mysqlpassword, db_name)) def create_db(): """ Create a MySQL DB for App version """ if not env.db_name: db_name = prompt("Enter the DB name:") else: db_name = env.db_name run('echo "CREATE DATABASE %s default character set utf8 collate utf8 collate utf8_unicode_ci;"|mysql --batch --user=%s --password=%s --host=%s'\ % (db_name, env.mysqluser, env.mysqlpassword, env.mysqlhost), pty=True) def ls_db(): """ List a dbs with size in MB """ if not env.db_name: db_name = prompt("Which DB to ls?") else: db_name = env.db_name query = """SELECT table_schema "DB Name", Round(Sum(data_length + index_length) / 1024 / 1024, 1) "DB Size in MB" FROM information_schema.tables WHERE table_schema = \"%s\" GROUP BY table_schema """ %db_name run_sql(db_name,query) def empty_db(): """ Empty all tables of a given DB """ db-name = prompt("Enter DB name to empty:") cmd = """ (echo 'SET foreign_key_checks = 0;'; (mysqldump -u%s -p%s --add-drop-table --no-data %s | grep ^DROP); echo 'SET foreign_key_checks = 1;') | \ mysql -u%s -p%s -b %s """ %(env.mysqluser, env.mysqlpassword, db_name, env.mysqluser, env.mysqlpassword, db_name) run(cmd)
def download_file(): print "Checking local disk space..." local("df -h") remote_path = prompt("Enter the remote file path:") local_path = prompt("Enter the local file path:") get(remote_path=remote_path, local_path=local_path) local("ls %s" %local_path)
def create_role(): """Create Remote Role.""" name_role = prompt("Unique name? ") with cd(remote_app_dir): sudo( "source env-{{NAMEPROJECT}}/bin/activate && python {{NAMEPROJECT}}/manage.py create_role -n {}".format(name_role))
def _update_production(): """ updates production environment """ if "y" != prompt(red('Are you sure you want to update ' + red('production', bold=True) + ' website (y/n)?'), default="n"): return run("") # password request print if env.full or "y" == prompt(red('Set maintenance screen (y/n)?'), default="y"): print(green(" * Setting maintenance screen")) run('cd ~/public_html/ ' '&& cp .htaccess_maintenance .htaccess') print if env.full or "y" == prompt(red('Stop cron jobs (y/n)?'), default="y"): print(green(" * Stopping cron jobs")) sudo('/etc/init.d/cron stop') print if env.full or "y" == prompt(red('Backup database (y/n)?'), default="y"): print(green(" * creating a database dump...")) run('cd ~/db_backups/ ' '&& ./backup_db.bsh') print if env.full or "y" == prompt(red('Update code (y/n)?'), default="y"): print(green(" * updating code...")) run('cd ~/project/myproject/ ' '&& git pull') print if env.full or "y" == prompt(red('Collect static files (y/n)?'), default="y"): print(green(" * collecting static files...")) run('cd ~/project/myproject ' '&& python manage.py collectstatic --noinput') print if env.full or "y" == prompt(red('Migrate database schema (y/n)?'), default="y"): print(green(" * migrating database schema...")) run('cd ~/project/myproject ' '&& python manage.py migrate --no-initial-data') run('cd ~/project/myproject ' '&& python manage.py syncdb') print if env.full or "y" == prompt(red('Restart webserver (y/n)?'), default="y"): print(green(" * Restarting Apache")) sudo('/etc/init.d/apache2 graceful') print if env.full or "y" == prompt(red('Start cron jobs (y/n)?'), default="y"): print(green(" * Starting cron jobs")) sudo('/etc/init.d/cron start') print if env.full or "y" == prompt(red('Unset maintenance screen (y/n)?'), default="y"): print(green(" * Unsetting maintenance screen")) run('cd ~/public_html/ ' '&& cp .htaccess_live .htaccess') print
def install_wordpress(self): if self.args.force or prompt(red(' * Install Wordpress (y/n)?'), default='y') == 'y': # create project web server config file if not exist with cd('/etc/nginx/sites-available'): if not exists(self.project): sudo('touch {0}'.format(self.project)) # check the php version is php5 or php7 try: sudo('php5-fpm -v') # save wordpress config put(StringIO(self.nginx_web_wordpress_config), self.project, use_sudo=True) except: sudo('php-fpm7.0 -v') # save wordpress config put(StringIO(self.nginx_php7_web_wordpress_config), self.project, use_sudo=True) # go to web root with cd(self.nginx_web_dir): # download latest wordpress, extract and change mode sudo('wget https://wordpress.org/latest.tar.gz') sudo('tar -zxvf latest.tar.gz') sudo('sudo chown -R www-data:www-data wordpress') # rename wordpress project sudo('mv wordpress {0}'.format(self.project)) # create uploads folder sudo('mkdir {0}/wp-content/uploads'.format(self.project)) sudo('chown -R www-data:www-data {0}/wp-content/uploads'.format(self.project)) # go to nginx enabled config with cd('/etc/nginx/sites-enabled'): if exists(self.project): sudo('rm {0}'.format(self.project)) # remove the default nginx config if exists('default'): sudo('rm default') # move project web server config file from avaiable to enable folder sudo('ln -s /etc/nginx/sites-available/{0} .'.format(self.project)) # restart server try: sudo('service php5-fpm restart') except: sudo('service php7.0-fpm restart') sudo('service nginx restart') print(green(' * Installed Wordpress project {0} in the system.'.format(self.project))) print(green(' * Done')) print()