我们从Python开源项目中,提取了以下27个代码示例,用于说明如何使用fabric.api.env.password()。
def parse_args(): args = argparse.ArgumentParser("Setup ceph client to remote host") args.add_argument('node', help="Name or IP address of node to install to") args.add_argument('-C', '--ceph', help="Name of IP address of ceph admin node") args.add_argument('-u', '--user', default='root', help="Username") args.add_argument('-p', '--password', help="Password") args.add_argument('-d', '--deploy-dir', default='/var/opt/deploy', help="Directory to put deploy script to") args.add_argument('-D', '--deploy-script', default='ceph_install.sh', help="Deploy script") args.add_argument('-w', '--app-dir', default='/var/opt/kuberdock', help="Directory of web-application") args.add_argument('-c', '--conf-dir', default='/etc/ceph', help="Directory of ceph-configs") args.add_argument('-T', '--temp-dir', default=TMPDIR, help="Temp directory") return args.parse_args()
def deactivate_ssh_password(): """ Desactiva la conexión por medio de ssh password. """ sed('/etc/ssh/sshd_config', '^UsePAM yes', 'UsePAM no', use_sudo=True) sed('/etc/ssh/sshd_config', '^PermitRootLogin yes', 'PermitRootLogin no', use_sudo=True) sed('/etc/ssh/sshd_config', '^#PasswordAuthentication yes', 'PasswordAuthentication no', use_sudo=True) sudo('service sshd reload')
def set_host(host_index): """A helper task to change env.hosts from the command line. It will only "stick" for the duration of the fab command that called it. Args: host_index (int): 0, 1, 2, 3, etc. Example: fab set_host:4 fab_task_A fab_task_B will set env.hosts = [public_dns_names[4]] but only for doing fab_task_A and fab_task_B """ env.hosts = [public_hosts[int(host_index)]] env.password = [public_pwds[int(host_index)]] # Install base software
def set_allnodes(): #read by line f=open('blockchain-nodes') for line in f.readlines(): temp=line.strip('\r\n').split(" ") host=temp[0] password=temp[1] env['passwords'][host]=password # order env['hosts']=env['passwords'].keys() #set on node
def remote_server(): env.hosts = ['127.0.0.1'] env.password = getpass('Enter your system password: ') env.home_folder = '/tmp'
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 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_unicode_ci;"|mysql --batch --user=%s --password=%s --host=%s'\ % (db_name, env.mysqluser, env.mysqlpassword, env.mysqlhost), pty=True)
def set_server_config(json_data): env.host_string = json_data.get('server_ip', '127.0.0.1') env.user = json_data.get('user', getuser()) env.password = json_data.get('password', '')
def setup_db(db_name, db_user, password): psql('CREATE DATABASE {db}'.format(db=db_name)) psql('CREATE USER {u} WITH LOGIN ENCRYPTED PASSWORD \'{p}\' CREATEDB'.format(u=db_user, p=password)) psql('GRANT ALL PRIVILEGES ON DATABASE {db} TO {u}'.format( db=db_name, u=db_user)) set_connection_parameter(db_user=db_user)
def backup_db(db_name, db_user, password, db_server=env.host_string): with cd('/tmp'): local('pg_dump -U {user} -h {ip} {db} > {db}-bak.sql'.format( user=db_user, ip=db_server, pwd=password, db=db_name ))
def restore_db(db_name, db_user, password, db_server=env.host_string): local('psql -U {user} -h {ip} {db} < /tmp/{db}-bak.sql'.format( user=db_user, ip=db_server, pwd=password, db=db_name ))
def create_host_task(key, host_config): """ Generate host tasks dynamically from config """ # do validation *before* dynamic task function generation # allowing for hostname to avoid a breaking change if 'hostname' in host_config and 'hostnames' in host_config: raise ValueError(red('cannot specify both \'hostname\' and \'hostnames\'')) if 'hostname' not in host_config and 'hostnames' not in host_config: raise ValueError(red('must supply \'hostnames\' section')) hosts_key = 'hostname' if 'hostname' in host_config else 'hostnames' def f(): hosts = None if 'hostname' in host_config: warn('\'hostname\' is being deprecated in favor of \'hostnames\' so you can provide a csv-list\n') hostname = host_config['hostname'] hosts = [hostname] if 'hostnames' in host_config: hosts = [h.strip() for h in host_config['hostnames'].split(',')] env.hosts = hosts env.port = host_config.get('port', 22) # convenience for local deployment to Vagrantfile VM if hosts[0] in {'localhost', '127.0.0.1'}: hostname = '127.0.0.1' # sometimes fabric just fails with 'localhost' env.user = 'vagrant' env.password = 'vagrant' env.port = host_config.get('port', 2222) f.__name__ = key f.__doc__ = "[hosts] \tsets deploy hosts to %s" % green(host_config[hosts_key]) return WrappedCallableTask(f)
def rsyncd(self, local_dest, remote_dest): local( "rsync --progress --delete -avzq --rsh=\"sshpass -p {ssh_pass} ssh -p 22 \" " "--exclude='assets/sass' --exclude='assets/js/app' " "--exclude='scripts' --exclude='node-modules' --exclude='WEB-INF' " "{local_dest}/ {ssh_user}@{ssh_host}:{remote_dest}".format( local_dest=local_dest, remote_dest=remote_dest, ssh_user=env.user, ssh_host=env.hosts, ssh_pass=env.password))
def harden_sshd(): """Security harden sshd. """ # Disable password authentication sed('/etc/ssh/sshd_config', '#PasswordAuthentication yes', 'PasswordAuthentication no', use_sudo=True) # Deny root login sed('/etc/ssh/sshd_config', 'PermitRootLogin yes', 'PermitRootLogin no', use_sudo=True)
def set_node(host,password): env['passwords'][host]=password env['hosts']=env['passwords'].keys() ################### # Install Collectd
def init_host(self): """ Initial host """ env.host_string = self.host_string env.user = self.host_user env.password = self.host_passwd env.key_filename = self.host_keyfile
def common_install_mysql(self): """ Install mysql """ sudo("debconf-set-selections <<< 'mysql-server mysql-server/root_password password {0}'".format(self.mysql_password)) sudo("debconf-set-selections <<< 'mysql-server mysql-server/root_password_again password {0}'".format(self.mysql_password)) sudo('apt-get install mysql-server -y') print(green(' * Installed MySql server in the system.')) print(green(' * Done')) print()
def reset_server_env(self, server_name, configure): """ reset server env to server-name :param server_name: :param configure: :return: """ env.host_string = configure[server_name]['host'] env.user = configure[server_name]['user'] env.password = configure[server_name]['passwd']
def __init__(self, user, ssh_key, hosts, repository, password): if None in [user, ssh_key, hosts, repository]: # XXX: Charm should block instead. # https://bugs.launchpad.net/bugs/1638772 raise Exception('Missing configuration') self.user = user self.ssh_key = ssh_key self.hosts = hosts.split() self.repository = repository self.password = password self.key_filename = self._write_key() self._init_fabric()
def _init_fabric(self): env.warn_only = True env.connection_attempts = 10 env.timeout = 10 env.user = self.user env.key_filename = self.key_filename env.hosts = self.hosts env.password = self.password
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 action_restore(znappy, t): snapshots, _ = list_snapshots(znappy.cluster, t) # Sort by smallest amount of (absolute) "lag" to get closest snapshot master = sorted(snapshots.values(), key=lambda s: abs(int(t - s.time)))[0] print "Master host will be: {}".format(master.host.name) # get snapshots created before master snapshots, excluded = list_snapshots(znappy.cluster, master.time, before=True) snapshots = {h: snapshots[h] for h in snapshots if h != master.host.name} snapshots[master.host.name] = master master.host.name in excluded and excluded.pop(excluded.index(master.host.name)) print snapshot_table(snapshots, t, excluded=excluded).get_string(sortby='host') choice = raw_input("Are you sure? [y/N]: ").lower() if choice != 'y': return "Aborted!" env.user = raw_input('[ldap] username: ') env.password = getpass.getpass('[sudo] password for {}: '.format(env.user)) if not tsudo('localhost', '/bin/true').return_code == 0: return 'Failed to verify credentials' # lock the whole cluster while not znappy.cluster.lock(): time.sleep(0.5) # time to bork the sjit try: for host in snapshots: env.host_string = host sudo('znappy snapshot restore {0}'.format(snapshots[host].name)) # ye it should be that easy except Exception, e: print e.message return "Failed to restore cluster!" znappy.cluster.release() return "cluster restore complete"
def add_diff_env_to_controller(differentiated_environment): """Add a differentiated environment remotely and bounce services. This function is used in: * test/functional/test_environment_add.py Examine that example for further explanation. Given an appropriate host_string and password, this function: (0) halts services on a Neutron controller; (1) reconfigures the relevant files to add an "environment" service_provider; (2) restarts the services. (CRITICAL NOTE: The relevant credentials are hardcoded via the 'source keystonerc_testlab' line. NOT apropriate for use in a production environment.) """ env.host_string = ''.join( [pytest.symbols.tenant_name, '@', pytest.symbols.controller_ip, ':22']) @hosts(env.host_string) def setup_env_oncontroller(diff_env): env.password = pytest.symbols.tenant_password execute(lambda: run('sudo ls -la')) # Stop existing agent execute(lambda: run('sudo systemctl stop f5-openstack-agent')) # Stop neutron server / f5_plugin execute(lambda: run('sudo systemctl stop neutron-server')) # Edit agent configuration to use new environment sedtempl = '''sed -i "s/^\(environment_prefix = \)\(.*\)$/\\1%s/"''' +\ ''' /etc/neutron/services/f5/f5-openstack-agent.ini''' sedstring = 'sudo ' + sedtempl % diff_env execute(lambda: run(sedstring)) # Add diff env to neutron_lbaas.conf and installed Python package add_string = 'sudo add_f5agent_environment %s' % diff_env execute(lambda: run(add_string)) # Start neutron-server / f5_plugin execute(lambda: run('sudo systemctl start neutron-server')) # Start existing agent execute(lambda: run('source keystonerc_testlab && ' 'sudo systemctl start f5-openstack-agent')) setup_env_oncontroller(differentiated_environment)