本文整理汇总了Python中utils.ssh.SSHClient.run_command方法的典型用法代码示例。如果您正苦于以下问题:Python SSHClient.run_command方法的具体用法?Python SSHClient.run_command怎么用?Python SSHClient.run_command使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类utils.ssh.SSHClient
的用法示例。
在下文中一共展示了SSHClient.run_command方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: setup_external_auth_openldap
# 需要导入模块: from utils.ssh import SSHClient [as 别名]
# 或者: from utils.ssh.SSHClient import run_command [as 别名]
def setup_external_auth_openldap(**data):
"""Sets up the appliance for an external authentication with OpenLdap.
Keywords:
get_groups: Get User Groups from External Authentication (httpd).
ipaserver: IPA server address.
iparealm: Realm.
credentials: Key of the credential in credentials.yaml
"""
connect_kwargs = {
'username': credentials['host_default']['username'],
'password': credentials['host_default']['password'],
'hostname': data['ipaddress'],
}
appliance_obj = appliance.IPAppliance()
appliance_name = 'cfmeappliance{}'.format(fauxfactory.gen_alpha(7).lower())
appliance_address = appliance_obj.address
appliance_fqdn = '{}.{}'.format(appliance_name, data['domain_name'])
ldapserver_ssh = SSHClient(**connect_kwargs)
# updating the /etc/hosts is a workaround due to the
# https://bugzilla.redhat.com/show_bug.cgi?id=1360928
command = 'echo "{}\t{}" >> /etc/hosts'.format(appliance_address, appliance_fqdn)
ldapserver_ssh.run_command(command)
ldapserver_ssh.get_file(remote_file=data['cert_filepath'],
local_path=conf_path.strpath)
ldapserver_ssh.close()
ensure_browser_open()
login_admin()
auth = ExternalAuthSetting(get_groups=data.pop("get_groups", True))
auth.setup()
appliance_obj.configure_appliance_for_openldap_ext_auth(appliance_fqdn)
logout()
示例2: main
# 需要导入模块: from utils.ssh import SSHClient [as 别名]
# 或者: from utils.ssh.SSHClient import run_command [as 别名]
def main():
parser = argparse.ArgumentParser(epilog=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("address", help="hostname or ip address of target appliance")
parser.add_argument("sdk_url", help="url to download sdk pkg")
parser.add_argument(
"--restart",
help="restart evmserverd after installation " + "(required for proper operation)",
action="store_true",
)
args = parser.parse_args()
ssh_kwargs = {
"username": credentials["ssh"]["username"],
"password": credentials["ssh"]["password"],
"hostname": args.address,
}
# Init SSH client
client = SSHClient(**ssh_kwargs)
# start
filename = args.sdk_url.split("/")[-1]
foldername = os.path.splitext(filename)[0]
# download
print "Downloading sdk"
status, out = client.run_command(
"curl %(url)s -o %(file)s > /root/unzip.out 2>&1" % {"url": args.sdk_url, "file": filename}
)
# extract
print "Extracting sdk (" + filename + ")"
status, out = client.run_command("unzip -o -f -d /var/www/miq/vmdb/lib/ %s" % filename)
if status != 0:
print out
sys.exit(1)
# install
print "Installing sdk (" + foldername + ")"
status, out = client.run_command(
'echo "export LD_LIBRARY_PATH=\$LD_LIBRARY_PATH:'
+ "/var/www/miq/vmdb/lib/"
+ foldername
+ '/lib/linux-64" >> /etc/default/evm'
)
if status != 0:
print "SDK installation failure (rc:" + out + ")"
print out
sys.exit(1)
# service evmserverd restart
if args.restart:
print "Appliance restart"
status, out = client.run_command("service evmserverd restart")
print "evmserverd restarted, the UI should start shortly."
else:
print "evmserverd must be restarted before netapp sdk can be used"
示例3: fix_merkyl_workaround
# 需要导入模块: from utils.ssh import SSHClient [as 别名]
# 或者: from utils.ssh.SSHClient import run_command [as 别名]
def fix_merkyl_workaround():
"""Workaround around merkyl not opening an iptables port for communication"""
ssh_client = SSHClient()
if ssh_client.run_command('test -f /etc/init.d/merkyl').rc == 0:
logger.info('Rudely overwriting merkyl init.d on appliance;')
local_file = data_path.join("bundles").join("merkyl").join("merkyl")
remote_file = "/etc/init.d/merkyl"
ssh_client.put_file(local_file.strpath, remote_file)
ssh_client.run_command("service merkyl restart")
示例4: main
# 需要导入模块: from utils.ssh import SSHClient [as 别名]
# 或者: from utils.ssh.SSHClient import run_command [as 别名]
def main():
parser = argparse.ArgumentParser(epilog=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('address',
help='hostname or ip address of target appliance')
parser.add_argument('db_address',
help='hostname or ip address of external database')
parser.add_argument('--database', default='vmdb_production',
help='name of the external database')
parser.add_argument('--region', default=0, type=int,
help='region to assign to the new DB')
parser.add_argument('--username', default=credentials['database']['username'],
help='username for external database')
parser.add_argument('--password', default=credentials['database']['password'],
help='password for external database')
args = parser.parse_args()
ssh_kwargs = {
'username': credentials['ssh']['username'],
'password': credentials['ssh']['password'],
'hostname': args.address
}
rbt_repl = {
'miq_lib': '/var/www/miq/lib',
'host': args.db_address,
'database': args.database,
'region': args.region,
'username': args.username,
'password': args.password
}
# Find and load our rb template with replacements
base_path = os.path.dirname(__file__)
rbt = datafile.data_path_for_filename(
'enable-external-db.rbt', base_path)
rb = datafile.load_data_file(rbt, rbt_repl)
# Init SSH client and sent rb file over to /tmp
remote_file = '/tmp/%s' % generate_random_string()
client = SSHClient(**ssh_kwargs)
client.put_file(rb.name, remote_file)
# Run the rb script, clean it up when done
print 'Initializing Appliance External DB'
status, out = client.run_command('ruby %s' % remote_file)
client.run_command('rm %s' % remote_file)
if status != 0:
print 'Enabling DB failed with error:'
print out
sys.exit(1)
else:
print 'DB Enabled, evm watchdog should start the UI shortly.'
示例5: disable_external_auth_openldap
# 需要导入模块: from utils.ssh import SSHClient [as 别名]
# 或者: from utils.ssh.SSHClient import run_command [as 别名]
def disable_external_auth_openldap():
auth = DatabaseAuthSetting()
auth.update()
sssd_conf = '/etc/sssd/sssd.conf'
httpd_auth = '/etc/pam.d/httpd-auth'
manageiq_remoteuser = '/etc/httpd/conf.d/manageiq-remote-user.conf'
manageiq_ext_auth = '/etc/httpd/conf.d/manageiq-external-auth.conf'
command = 'rm -rf {} && rm -rf {} && rm -rf {} && rm -rf {}'.format(
sssd_conf, httpd_auth, manageiq_ext_auth, manageiq_remoteuser)
ssh = SSHClient()
assert ssh.run_command(command)
ssh.run_command('systemctl restart evmserverd')
appliance.IPAppliance().wait_for_web_ui()
logout()
示例6: disable_forgery_protection
# 需要导入模块: from utils.ssh import SSHClient [as 别名]
# 或者: from utils.ssh.SSHClient import run_command [as 别名]
def disable_forgery_protection():
starttime = time.time()
ssh_client = SSHClient()
logger.info('Turning off "allow_forgery_protection"')
ssh_client.run_command(
"sed -i \'s/allow_forgery_protection = true/allow_forgery_protection = false/\' "
"/var/www/miq/vmdb/config/environments/production.rb")
ssh_client.run_command("service evmserverd restart")
ssh_client.close()
timediff = time.time() - starttime
logger.info('Turned off "allow_forgery_protection" in: {}'.format(timediff))
yield
starttime = time.time()
ssh_client = SSHClient()
logger.info('Turning on "allow_forgery_protection"')
ssh_client.run_command(
"sed -i \'s/allow_forgery_protection = false/allow_forgery_protection = true/\' "
"/var/www/miq/vmdb/config/environments/production.rb")
ssh_client.run_command("service evmserverd restart")
ssh_client.close()
timediff = time.time() - starttime
logger.info('Turned on "allow_forgery_protection" in: {}'.format(timediff))
示例7: main
# 需要导入模块: from utils.ssh import SSHClient [as 别名]
# 或者: from utils.ssh.SSHClient import run_command [as 别名]
def main():
parser = argparse.ArgumentParser(epilog=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('address', help='hostname or ip address of target appliance')
args = parser.parse_args()
ssh_kwargs = {
'username': credentials['ssh']['username'],
'password': credentials['ssh']['password'],
'hostname': args.address
}
# Init SSH client
client = SSHClient(**ssh_kwargs)
snmp_path = scripts_data_path.join("snmp")
# Copy
print("Copying files")
client.put_file(snmp_path.join("snmp_listen.rb").strpath, "/root/snmp_listen.rb")
client.put_file(snmp_path.join("snmp_listen.sh").strpath, "/root/snmp_listen.sh")
# Enable after startup
print("Enabling after startup")
status = client.run_command("grep 'snmp_listen[.]sh' /etc/rc.local")[0]
if status != 0:
client.run_command("echo 'cd /root/ && ./snmp_listen.sh start' >> /etc/rc.local")
assert client.run_command("grep 'snmp_listen[.]sh' /etc/rc.local")[0] == 0, "Could not enable!"
# Run!
print("Starting listener")
assert client.run_command("cd /root/ && ./snmp_listen.sh start")[0] == 0, "Could not start!"
# Open the port if not opened
print("Opening the port in iptables")
status = client.run_command("grep '--dport 8765' /etc/sysconfig/iptables")[0]
if status != 0:
# append after the 5432 entry
client.run_command(
"sed -i '/--dport 5432/a -A INPUT -p tcp -m tcp --dport 8765 -j ACCEPT' "
"/etc/sysconfig/iptables"
)
client.run_command("service iptables restart")
# Check if accessible
try:
requests.get("http://{}:8765/".format(args.address))
except requests.exceptions.ConnectionError:
print("Could not detect running listener!")
exit(2)
示例8: setup_external_auth_ipa
# 需要导入模块: from utils.ssh import SSHClient [as 别名]
# 或者: from utils.ssh.SSHClient import run_command [as 别名]
def setup_external_auth_ipa(**data):
"""Sets up the appliance for an external authentication with IPA.
Keywords:
get_groups: Get User Groups from External Authentication (httpd).
ipaserver: IPA server address.
iparealm: Realm.
credentials: Key of the credential in credentials.yaml
"""
ssh = SSHClient()
ensure_browser_open()
login_admin()
if data["ipaserver"] not in get_ntp_servers():
set_ntp_servers(data["ipaserver"])
sleep(120)
auth = ExternalAuthSetting(get_groups=data.pop("get_groups", False))
auth.setup()
logout()
creds = credentials.get(data.pop("credentials"), {})
data.update(**creds)
rc, out = ssh.run_command(
"appliance_console_cli --ipaserver {ipaserver} --iparealm {iparealm} "
"--ipaprincipal {principal} --ipapassword {password}".format(**data)
)
assert rc == 0, out
assert "failed" not in out.lower(), "External auth setup failed:\n{}".format(out)
login_admin()
示例9: main
# 需要导入模块: from utils.ssh import SSHClient [as 别名]
# 或者: from utils.ssh.SSHClient import run_command [as 别名]
def main():
parser = argparse.ArgumentParser(epilog=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('address', help='hostname or ip address of target appliance',
nargs='?', default=None)
args = parser.parse_args()
ssh_kwargs = {
'username': credentials['ssh']['username'],
'password': credentials['ssh']['password'],
}
if args.address:
ssh_kwargs['hostname'] = args.address
# Init SSH client
ssh_client = SSHClient(**ssh_kwargs)
# compile assets if required (not required on 5.2)
if not ssh_client.get_version().startswith("5.2"):
if ssh_client.run_command("ls /var/www/miq/vmdb/public/assets")[0] != 0:
ssh_client.run_rake_command("assets:precompile")
ssh_client.run_rake_command("evm:restart")
print "CFME UI worker restarted, UI should be available shortly"
示例10: get_appliance
# 需要导入模块: from utils.ssh import SSHClient [as 别名]
# 或者: from utils.ssh.SSHClient import run_command [as 别名]
def get_appliance(provider):
'''Fixture to provision appliance to the provider being tested if necessary'''
global appliance_list
global appliance_vm_name
if provider not in appliance_list:
if ('appliances_provider' not in cfme_data['basic_info'].keys() or
provider != cfme_data['basic_info']['appliances_provider']):
appliance_list[provider] = provision_appliance(provider)
else:
appliance_list[provider] = re.findall(r'[0-9]+(?:\.[0-9]+){3}', conf.env['base_url'])[0]
prov_data = cfme_data['management_systems'][provider]
if prov_data['type'] == 'virtualcenter':
# ssh in and see if vddk already present, if not, install
ssh_kwargs = {
'username': conf.credentials['ssh']['username'],
'password': conf.credentials['ssh']['password'],
'hostname': appliance_list[provider]
}
# Init SSH client
client = SSHClient(**ssh_kwargs)
if int(client.run_command("ldconfig -p | grep vix | wc -l")[1]) < 1:
install_vddk(appliance_list[provider])
client.close()
elif prov_data['type'] == 'rhevm':
add_rhev_direct_lun_disk(provider, appliance_vm_name)
return appliance_list[provider]
示例11: net_check_remote
# 需要导入模块: from utils.ssh import SSHClient [as 别名]
# 或者: from utils.ssh.SSHClient import run_command [as 别名]
def net_check_remote(port, addr=None, machine_addr=None, ssh_creds=None, force=False):
"""Checks the availability of a port from outside using another machine (over SSH)"""
from utils.ssh import SSHClient
port = int(port)
if not addr:
addr = my_ip_address()
if port not in _ports[addr] or force:
if not machine_addr:
machine_addr = urlparse.urlparse(store.base_url).hostname
if not ssh_creds:
ssh = store.current_appliance.ssh_client
else:
ssh = SSHClient(
hostname=machine_addr,
username=ssh_creds['username'],
password=ssh_creds['password']
)
with ssh:
# on exception => fails with return code 1
cmd = '''python -c "
import sys, socket
addr = socket.gethostbyname('%s')
socket.create_connection((addr, %d), timeout=10)
sys.exit(0)
"''' % (addr, port)
ret, out = ssh.run_command(cmd)
if ret == 0:
_ports[addr][port] = True
else:
_ports[addr][port] = False
return _ports[addr][port]
示例12: disable_external_auth_ipa
# 需要导入模块: from utils.ssh import SSHClient [as 别名]
# 或者: from utils.ssh.SSHClient import run_command [as 别名]
def disable_external_auth_ipa():
"""Unconfigure external auth."""
ssh = SSHClient()
ensure_browser_open()
login_admin()
auth = DatabaseAuthSetting()
auth.update()
rc, out = ssh.run_command("appliance_console_cli --uninstall-ipa")
assert rc == 0, out
示例13: test_verify_revert_snapshot
# 需要导入模块: from utils.ssh import SSHClient [as 别名]
# 或者: from utils.ssh.SSHClient import run_command [as 别名]
def test_verify_revert_snapshot(test_vm, provider_key, provider_type, provider_data,
soft_assert, register_event, request):
"""Tests revert snapshot
Metadata:
test_flag: snapshot, provision
"""
snapshot1 = new_snapshot(test_vm)
ip = snapshot1.vm.provider_crud.get_mgmt_system().get_ip_address(snapshot1.vm.name)
print ip
ssh_kwargs = {
'username': credentials[provider_data['full_template']['creds']]['username'],
'password': credentials[provider_data['full_template']['creds']]['password'],
'hostname': ip
}
ssh = SSHClient(**ssh_kwargs)
ssh.run_command('touch snapshot1.txt')
snapshot1.create()
ssh.run_command('touch snapshot2.txt')
snapshot2 = new_snapshot(test_vm)
snapshot2.create()
snapshot1.revert_to()
# Wait for the snapshot to become active
logger.info('Waiting for vm %s to become active', snapshot1.name)
wait_for(snapshot1.wait_for_snapshot_active, num_sec=300, delay=20, fail_func=sel.refresh)
test_vm.wait_for_vm_state_change(desired_state=Vm.STATE_OFF, timeout=720)
register_event(
test_vm.provider_crud.get_yaml_data()['type'],
"vm", test_vm.name, ["vm_power_on_req", "vm_power_on"])
test_vm.power_control_from_cfme(option=Vm.POWER_ON, cancel=False)
pytest.sel.force_navigate(
'infrastructure_provider', context={'provider': test_vm.provider_crud})
test_vm.wait_for_vm_state_change(desired_state=Vm.STATE_ON, timeout=900)
soft_assert(test_vm.find_quadicon().state == 'currentstate-on')
soft_assert(
test_vm.provider_crud.get_mgmt_system().is_vm_running(test_vm.name), "vm not running")
client = SSHClient(**ssh_kwargs)
request.addfinalizer(test_vm.delete_from_provider)
try:
wait_for(lambda: client.run_command('test -e snapshot2.txt')[1] == 0, fail_condition=False)
logger.info('Revert to snapshot %s successful', snapshot1.name)
except:
logger.info('Revert to snapshot %s Failed', snapshot1.name)
示例14: disable_external_auth_ipa
# 需要导入模块: from utils.ssh import SSHClient [as 别名]
# 或者: from utils.ssh.SSHClient import run_command [as 别名]
def disable_external_auth_ipa():
"""Unconfigure external auth."""
ssh = SSHClient()
ensure_browser_open()
login_admin()
auth = DatabaseAuthSetting()
auth.update()
assert ssh.run_command("appliance_console_cli --uninstall-ipa")
appliance.IPAppliance().wait_for_web_ui()
logout()
示例15: main
# 需要导入模块: from utils.ssh import SSHClient [as 别名]
# 或者: from utils.ssh.SSHClient import run_command [as 别名]
def main():
parser = argparse.ArgumentParser(epilog=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('address', help='hostname or ip address of target appliance')
parser.add_argument('repo_url', help='updates base url')
parser.add_argument('--reboot', help='reboot after installation ' +
'(required for proper operation)', action="store_true")
args = parser.parse_args()
ssh_kwargs = {
'username': credentials['ssh']['username'],
'password': credentials['ssh']['password'],
'hostname': args.address
}
# Init SSH client
client = SSHClient(**ssh_kwargs)
# create repo file
repo_file = "[rhel-updates]\nname=rhel6-updates\nbaseurl=" + args.repo_url + "\nenabled=1\ngpgcheck=0"
# create repo file on appliance
print 'Create update repo file'
status, out = client.run_command('echo "%s" >/etc/yum.repos.d/rhel_updates.repo' % repo_file)
# update
print 'Running rhel updates...'
status, out = client.run_command('yum update -y --nogpgcheck')
print "\n" + out + "\n"
if status != 0:
print "ERROR during update"
sys.exit(1)
# reboot
if args.reboot:
print 'Appliance reboot'
status, out = client.run_command('reboot')
else:
print 'A reboot is recommended.'