我们从Python开源项目中,提取了以下32个代码示例,用于说明如何使用fabric.api.env.host()。
def deployMultiClient(num): local('rm -f testMap.csv') for i in range(int(num)): dirc = 'client%s' % i with cd(dirc): with cd('loopix'): run("git pull") run("git checkout %s" % BRANCH) with cd('loopix/loopix'): N = hexlify(os.urandom(8)) providers = getProvidersNames() prvName = random.choice(providers) port = int(9999 - i) print "CLIENT: Client%s" % N run("python setup_client.py %d %s Client%s %s" % (port, str(env.host), N, prvName)) get('publicClient.bin', 'publicClient-%d-%s.bin'%(port, env.host)) with open('testMap.csv', 'a') as outfile: csvW = csv.writer(outfile) csvW.writerow(['Client%s'%N, dirc])
def deploy(clients): execute(deployMulti, clients) # # @roles("providers") # def checkHost(): # print env.host # # # @runs_once # def takeNamesDb(): # database = "example.db" # db = sqlite3.connect(database) # c = db.cursor() # c.execute("SELECT * FROM Providers") # providers = c.fetchall() # for p in providers: # print p # #
def virtualbox_host(): '''Install a VirtualBox host system. More Infos: * overview: https://wiki.ubuntuusers.de/VirtualBox/ * installation: https://wiki.ubuntuusers.de/VirtualBox/Installation/ ''' if query_yes_no(question='Uninstall virtualbox-dkms?', default='yes'): run('sudo apt-get remove virtualbox-dkms') install_packages([ 'virtualbox', 'virtualbox-qt', 'virtualbox-dkms', 'virtualbox-guest-dkms', 'virtualbox-guest-additions-iso', ]) users = [env.user] for username in users: run(flo('sudo adduser {username} vboxusers')) #run('newgrp - vboxusers')
def deploy(): site_folder = f'/home/{env.user}/sites/{env.host}/source' source_folder = site_folder _get_latest_source(source_folder) _create_directory_structure_if_necessary(site_folder) source_folder = source_folder + '/eloworld' _update_settings(source_folder, env.host) _update_virtualenv(source_folder) _update_static_files(source_folder) _update_database(source_folder)
def deploy(): site_folder = '/home/{}/sites/{}'.format(env.user, env.host) source_folder = site_folder + '/source' _create_directory_structure_if_necessary(site_folder) _get_latest_source(source_folder) _update_settings(source_folder, env.host) _update_virtualenv(source_folder) _update_static_files(source_folder) _update_database(source_folder)
def get_effective_role(): """Acquire the role definition according to current host """ for role in env.roles: if env.host in env.roledefs[role]['hosts']: return role, env.roledefs[role] raise ValueError('Role undefined by {}'.format(env.host))
def deploy(): site_folder = '/home/%s/sites/%s' % (env.user, env.host) source_folder = site_folder + '/source' _create_directory_structure_if_necessary(site_folder) _get_latest_source(source_folder) _update_settings(source_folder, env.host) _update_virtualenv(source_folder) _update_static_files(source_folder) _update_database(source_folder)
def deploy(): site_folder = '/home/%s/sites/%s' % (env.user, env.host) source_folder = site_folder + '/brynweb' local_source_folder = '../brynweb' _get_latest_source(site_folder) _create_directory_structure(site_folder) _update_settings(source_folder, env.host) _copy_local_settings(local_source_folder, source_folder) _update_virtualenv(site_folder) _update_static_files(source_folder) _update_database(source_folder) _restart_gunicorn(env.host) _restart_nginx()
def start_mixnode(): with cd("loopix/loopix"): run("git checkout %s" % BRANCH) run("git pull") #run("twistd -p profiler_output.dat -y run_mixnode.py") run("twistd -y run_mixnode.py") pid = run("cat twistd.pid") print "Run on %s with PID %s" % (env.host, pid)
def kill_mixnode(): with cd("loopix/loopix"): pid = run("cat twistd.pid", warn_only=True) print "Kill %s with PID %s" % (env.host, pid) sudo("kill `cat twistd.pid`", warn_only=True) run("rm -f *.csv")
def start_client(): with cd("loopix/loopix"): run("git pull") run("twistd -y run_client.py") pid = run("cat twistd.pid") print "Run Client on %s with PID %s" % (env.host, pid) run("rm -f *.csv")
def kill_client(): with cd("loopix/loopix"): pid = run("cat twistd.pid", warn_only=True) print "Kill %s with PID %s" % (env.host, pid) run("kill `cat twistd.pid`", warn_only=True)
def start_multi_client(num): for i in range(int(num)): dirc = 'client%s' % i with cd(dirc+'/loopix/loopix'): run("git checkout %s" % BRANCH) run('git pull') run('twistd -y run_client.py') pid = run('cat twistd.pid') print "Run Client on %s with PID %s" % (env.host, pid)
def start_provider(): with cd("loopix/loopix"): run("git checkout %s" % BRANCH) run("git pull") #run("twistd -p profiler_output.dat -y run_provider.py") run("twistd -y run_provider.py") pid = run("cat twistd.pid") print "Run on %s with PID %s" % (env.host, pid)
def kill_provider(): with cd("loopix/loopix"): pid = run("cat twistd.pid", warn_only=True) print "Kill %s with PID %s" % (env.host, pid) run("kill `cat twistd.pid`", warn_only=True) run("rm -f *.csv")
def deployMixnode(): global c with cd('loopix'): run("git pull") run("git checkout %s" % BRANCH) N = hexlify(os.urandom(8)) with cd('loopix'): run("python setup_mixnode.py 9999 %s Mix%s %s" % (str(env.host), N, 0)) get('publicMixnode.bin', 'publicMixnode-%s.bin'%env.host) c += 1
def deployClient(): with cd("loopix"): run("git pull") run("git checkout %s" % BRANCH) N = hexlify(os.urandom(8)) providers = getProvidersNames() prvName = random.choice(providers) with cd('loopix'): run("python setup_client.py 9999 %s Client%s %s" % (str(env.host), N, prvName)) get('publicClient.bin', 'publicClient-%s.bin'%env.host)
def run_mixnode(): with cd('loopix/loopix'): run("git checkout %s" % BRANCH) run("twistd -y run_mixnode.py") pid = run("cat twistd.pid") print "Run on %s with PID %s" % (env.host, pid)
def run_provider(): with cd('loopix/loopix'): run("git checkout %s" % BRANCH) run("twistd -y run_provider.py") pid = run("cat twistd.pid") print "Run on %s with PID %s" % (env.host, pid)
def enable_nvm(): '''add to ~/.bashrc: Export of $NVM env variable and load nvm command.''' bash_snippet = '~/.bashrc_nvm' install_file(path=bash_snippet) prefix = flo('if [ -f {bash_snippet} ]; ') enabler = flo('if [ -f {bash_snippet} ]; then source {bash_snippet}; fi') if env.host == 'localhost': uncomment_or_update_or_append_line(filename='~/.bashrc', prefix=prefix, new_line=enabler) else: print(cyan('\nappend to ~/.bashrc:\n\n ') + enabler)
def server_customizations(): '''Customize the server (user, authorized_keys, ...).''' username = env.user env.user = 'root' # create user all_users = run('cut -d: -f1 /etc/passwd').split() if username not in all_users: host = env.host run(flo('adduser {username}')) # add user to the sudo group, cf. http://askubuntu.com/a/7484 #run('sudo adduser {username} sudo'.format(**locals())) # http://jeromejaglale.com/doc/unix/ubuntu_sudo_without_password append('/etc/sudoers', flo('{username} ALL=(ALL) NOPASSWD: ALL'), use_sudo=True) # set up password-less login local(flo('ssh-copy-id -i ~/.ssh/id_rsa.pub {username}@{host}')) env.user = username # Disable service apache2 httpd, cf. http://askubuntu.com/a/355102 sudo('update-rc.d apache2 disable') else: print(magenta(flo(' nothing to do, user {username} already exists'))) env.user = username
def lms(): '''Install and start a Logitech Media Server (lms). More infos: * http://wiki.slimdevices.com/index.php/Logitech_Media_Server * http://wiki.slimdevices.com/index.php/DebianPackage * http://www.mysqueezebox.com/download * XSqueeze on Kodi: * http://kodi.wiki/view/Add-on:XSqueeze * http://forum.kodi.tv/showthread.php?tid=122199 ''' # cf. http://wiki.slimdevices.com/index.php/DebianPackage#installing_7.9.0 cmds = '''\ url="http://www.mysqueezebox.com/update/?version=7.9.0&revision=1&geturl=1&os=deb" latest_lms=$(wget -q -O - "$url") mkdir -p ~/.logitech_media_server_sources cd ~/.logitech_media_server_sources wget $latest_lms lms_deb=${latest_lms##*/} sudo dpkg -i $lms_deb ''' run(cmds) run('sudo usermod -aG audio squeezeboxserver') with warn_only(): run('sudo addgroup lms') run('sudo usermod -aG lms squeezeboxserver') username = env.user run(flo('sudo usermod -aG audio {username}')) print('\n Set correct folder permissions manually, eg:') print(' > ' + cyan(flo('chown -R {username}.lms <path/to/your/media>'))) hostname = env.host print(flo('\n lms frontend available at http://{hostname}:9000'))
def current_ec2_node_id(): """Assumes it is called inside the 'workfn' of a 'stack_all_ec2_nodes'. Sticking to the 'node' terminology because 'instance' is too overloaded. Sample value: 'i-0553487b4b6916bc9'""" ensure(env.host is not None, "This is supposed to be called with settings for connecting to an EC2 instance") current_public_ip = env.host ensure('public_ips' in env, "This is supposed to be called by stack_all_ec2_nodes, which provides the correct configuration") matching_instance_ids = [instance_id for (instance_id, public_ip) in env.public_ips.items() if current_public_ip == public_ip] ensure(len(matching_instance_ids) == 1, "Too many instance ids (%s) pointing to this ip (%s)" % (matching_instance_ids, current_public_ip)) return matching_instance_ids[0]
def current_ip(): """Assumes it is called inside the 'workfn' of a 'stack_all_ec2_nodes'. Returns the ip address used to access the current host, e.g. '54.243.19.153'""" return env.host
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 capture_packets(): try: put(local_capture_packets_script, remote_capture_packets_script, mode=0755) sudo(remote_capture_packets_script) get('/tmp/captured-packets.dat', '{}/host-{}.dat'.format(env.DATDIR, env.host)) except NetworkError as ex: print(str(ex))
def get_lsb_release(): try: get('/etc/lsb-release', '{}/lsb-release-{}.dat'.format(env.DATDIR, env.host)) except NetworkError as ex: print(str(ex))
def get_uptime_load(): try: get('/proc/uptime', '{}/uptime-{}.dat'.format(env.DATDIR, env.host)) get('/proc/loadavg', '{}/loadavg-{}.dat'.format(env.DATDIR, env.host)) get('/proc/meminfo', '{}/meminfo-{}.dat'.format(env.DATDIR, env.host)) except NetworkError as ex: print(str(ex))
def run_clients(num): for i in range(int(num)): dirc = 'client%s' % i with cd(dirc+'/loopix/loopix'): run("git checkout %s" % BRANCH) run('twistd -y run_client.py') pid = run('cat twistd.pid') print "Run Client on %s with PID %s" % (env.host, pid) # # @roles("mixnodes", "providers") # @parallel # def reset_config_servers(branch): # with cd("loopix/loopix"): # run("git checkout %s" % branch) # run('git reset --hard') # # @roles("clients") # @parallel # def reset_config_clients(num, branch): # for i in range(int(num)): # dirc = 'client%s' % i # with cd(dirc+'/loopix/loopix'): # #sudo('rm -f config.json') # run("git checkout %s" % branch) # run('git reset --hard') # # # @roles("mixnodes", "providers") # @parallel # def update_git_servers(branch): # with cd("loopix/loopix"): # run("git checkout %s" % branch) # run("git pull") # # @roles("clients") # @parallel # def update_git_clients(num, branch): # for i in range(int(num)): # dirc = 'client%s' % i # with cd(dirc+'/loopix/loopix'): # run("git checkout %s" % branch) # run('git pull') # # def update_git(numClients, branch): # execute(update_git_servers, branch) # execute(update_git_clients, int(numClients), branch) # # #
def pyenv(): '''Install or update the pyenv python environment. Checkout or update the pyenv repo at ~/.pyenv and enable the pyenv. Pyenv wird also als Github-Repo "installiert" unter ~/.pyenv More info: * https://github.com/yyuu/pyenv * https://github.com/yyuu/pyenv/wiki/Common-build-problems#requirements Tutorial: * http://amaral-lab.org/resources/guides/pyenv-tutorial ''' install_packages([ 'make', 'build-essential', 'libssl-dev', 'zlib1g-dev', 'libbz2-dev', 'libreadline-dev', 'libsqlite3-dev', 'wget', 'curl', 'llvm', 'libncurses5-dev', 'libncursesw5-dev', ]) if exists('~/.pyenv'): run('cd ~/.pyenv && git pull') run('~/.pyenv/bin/pyenv update') else: run('curl -L https://raw.githubusercontent.com/yyuu/pyenv-installer/' 'master/bin/pyenv-installer | bash') # add pyenv to $PATH and set up pyenv init bash_snippet = '~/.bashrc_pyenv' install_file(path=bash_snippet) prefix = flo('if [ -f {bash_snippet} ]; ') enabler = flo('if [ -f {bash_snippet} ]; then source {bash_snippet}; fi') if env.host == 'localhost': # FIXME: next function currently only works for localhost uncomment_or_update_or_append_line(filename='~/.bashrc', prefix=prefix, new_line=enabler) else: print(cyan('\nappend to ~/.bashrc:\n\n ') + enabler)
def powerline_shell(): '''Install and set up powerline-shell prompt. More infos: * https://github.com/banga/powerline-shell * https://github.com/ohnonot/powerline-shell * https://askubuntu.com/questions/283908/how-can-i-install-and-use-powerline-plugin ''' assert env.host == 'localhost', 'This task cannot run on a remote host' # set up fonts for powerline checkup_git_repo('https://github.com/powerline/fonts.git', name='powerline-fonts') run('cd ~/repos/powerline-fonts && ./install.sh') # run('fc-cache -vf ~/.local/share/fonts') prefix = 'URxvt*font: ' from config import fontlist line = prefix + fontlist update_or_append_line(filename='~/.Xresources', prefix=prefix, new_line=line) if env.host_string == 'localhost': run('xrdb ~/.Xresources') # set up powerline-shell checkup_git_repo('https://github.com/banga/powerline-shell.git') # checkup_git_repo('https://github.com/ohnonot/powerline-shell.git') install_file(path='~/repos/powerline-shell/config.py') run('cd ~/repos/powerline-shell && ./install.py') question = 'Use normal question mark (u003F) for untracked files instead '\ 'of fancy "black question mark ornament" (u2753, which may not work)?' if query_yes_no(question, default='yes'): filename = '~/repos/powerline-shell/powerline-shell.py' update_or_append_line(filename, keep_backup=False, prefix=" 'untracked': u'\u2753',", new_line=" 'untracked': u'\u003F',") run(flo('chmod u+x {filename}')) bash_snippet = '~/.bashrc_powerline_shell' install_file(path=bash_snippet) prefix = flo('if [ -f {bash_snippet} ]; ') enabler = flo('if [ -f {bash_snippet} ]; then source {bash_snippet}; fi') uncomment_or_update_or_append_line(filename='~/.bashrc', prefix=prefix, new_line=enabler)