本文整理汇总了Python中pexpect.run方法的典型用法代码示例。如果您正苦于以下问题:Python pexpect.run方法的具体用法?Python pexpect.run怎么用?Python pexpect.run使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pexpect
的用法示例。
在下文中一共展示了pexpect.run方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_docker_volume_list
# 需要导入模块: import pexpect [as 别名]
# 或者: from pexpect import run [as 别名]
def get_docker_volume_list(*expected_volumes):
'''Get the output from "docker volume ls" for specified volumes.'''
volume_listing_pattern = (
r'(?P<driver>\S+)\s+'
r'(?P<name>\S+)'
# r'\s*$'
)
volume_listing_re = re.compile(volume_listing_pattern)
docker_volumes_response = pexpect.run('docker volume ls')
docker_volumes_response_l = docker_volumes_response.decode('utf-8').split('\n')
volume_list = []
for line in docker_volumes_response_l:
match = volume_listing_re.match(line)
if match:
volume_list.append(match.groupdict())
return volume_list
# - - - - - - - - - - - - - - - - - - - - - - - - - - - -
示例2: _scp_file
# 需要导入模块: import pexpect [as 别名]
# 或者: from pexpect import run [as 别名]
def _scp_file(self, url):
file_name = url.split('/')[-1]
logs.debug_3("scp file %s from RackHD" % url)
if not os.path.exists(file_name):
path = url[6:]
rackhd_hostname = fit_common.fitargs()['rackhd_host']
scp_file = fit_common.fitcreds()['rackhd_host'][0]['username'] + '@{0}:{1}'.format(rackhd_hostname, path)
cmd = 'scp -o StrictHostKeyChecking=no {0} .'.format(scp_file)
logs.debug_3("scp command : '{0}'".format(cmd))
logfile_redirect = None
if fit_common.VERBOSITY >= 9:
logfile_redirect = sys.stdout
(command_output, ecode) = pexpect.run(
cmd, withexitstatus=1,
events={'(?i)assword: ': fit_common.fitcreds()['rackhd_host'][0]['password'] + '\n'},
logfile=logfile_redirect)
assert ecode == 0, 'failed "{0}" because {1}. Output={2}'.format(cmd, ecode, command_output)
return file_name
示例3: _scp_file
# 需要导入模块: import pexpect [as 别名]
# 或者: from pexpect import run [as 别名]
def _scp_file(self, url):
file_name = url.split('/')[-1]
logs.debug_3("scp file %s from RackHD" % url)
if os.path.exists(file_name) is False:
path = url[6:]
rackhd_hostname = fit_common.fitargs()['rackhd_host']
scp_file = fit_common.fitcreds()['rackhd_host'][0]['username'] + '@{0}:{1}'.format(rackhd_hostname, path)
cmd = 'scp -o StrictHostKeyChecking=no {0} .'.format(scp_file)
logs.debug_3("scp command : '{0}'".format(cmd))
if fit_common.VERBOSITY >= 9:
logfile_redirect = sys.stdout
(command_output, ecode) = pexpect.run(
cmd, withexitstatus=1,
events={'(?i)assword: ': fit_common.fitcreds()['rackhd_host'][0]['password'] + '\n'},
logfile=logfile_redirect)
assert ecode == 0, 'failed "{0}" because {1}. Output={2}'.format(cmd, ecode, command_output)
return file_name
示例4: final_run
# 需要导入模块: import pexpect [as 别名]
# 或者: from pexpect import run [as 别名]
def final_run(image_id, arch, qemu_dir):
runsh_path = os.path.join(firmadyne_path, "scratch", image_id, "run.sh")
if not os.path.isfile(runsh_path):
print ("[!] Cannot emulate firmware, run.sh not generated")
return
if qemu_dir:
if arch == "armel":
arch = "arm"
elif arch == "mipseb":
arch = "mips"
print ("[+] Using qemu-system-{0} from {1}".format(arch, qemu_dir))
cmd = 'sed -i "/QEMU=/c\QEMU={0}/qemu-system-{1}" "{2}"'.format(qemu_dir, arch, runsh_path)
pexpect.run(cmd)
print ("[+] All set! Press ENTER to run the firmware...")
input ("[+] When running, press Ctrl + A X to terminate qemu")
print ("[+] Command line:", runsh_path)
run_cmd = ["--", runsh_path]
child = pexpect.spawn("sudo", run_cmd, cwd=firmadyne_path)
child.sendline(sudo_pass)
child.interact()
示例5: get_all_commands
# 需要导入模块: import pexpect [as 别名]
# 或者: from pexpect import run [as 别名]
def get_all_commands():
"""Retrieve all docker commands.
:return: set of str
"""
txt = pexpect.run('docker').strip().splitlines(False)
all_commands = set()
in_commands = False
for line in txt:
if in_commands:
if line:
all_commands.add(line.strip().split(' ', 1)[0])
else:
break
if line.lower() == 'commands:':
in_commands = True
return all_commands
示例6: execute_command
# 需要导入模块: import pexpect [as 别名]
# 或者: from pexpect import run [as 别名]
def execute_command():
logger.info('Got incoming request')
if 'command' not in request.form:
return jsonify(error="Missing parameter 'command'"), 422
command = request.form['command']
file_name = _extract_filename_from_command(command)
if file_name is not None and not os.path.isfile(file_name):
logger.warn("Couldn't find file %s", file_name)
if not command.startswith('idal ') and not command.startswith('idal64 '):
return jsonify(error="'idal' and 'idal64' are the only valid commands"), 422
try:
logger.info('Executing %s', command)
timeout = None if 'timeout' not in request.form else int(request.form['timeout'])
_, exit_code = pexpect.run(command, timeout=timeout, withexitstatus=True)
except pexpect.TIMEOUT:
return jsonify(error='request to ida timed out'), 408
finally:
if file_name is not None:
_remove_ida_created_files(file_name)
logger.info('Removed ida leftover files')
if exit_code == 0:
logger.info('Command %s finished executing successfully', command)
else:
logger.warn("Command %s didn't finish correctly, IDA returned exit code %s", command, exit_code)
if exit_code != 0:
return jsonify(error='ida finish with status code %s' % exit_code), 500
else:
return jsonify(message='OK'), 200
示例7: _stop_tunnel
# 需要导入模块: import pexpect [as 别名]
# 或者: from pexpect import run [as 别名]
def _stop_tunnel(cmd):
pexpect.run(cmd)
示例8: runu
# 需要导入模块: import pexpect [as 别名]
# 或者: from pexpect import run [as 别名]
def runu(command, timeout=-1, withexitstatus=False, events=None,
extra_args=None, logfile=None, cwd=None, env=None, **kwargs):
"""This offers the same interface as :func:`run`, but using unicode.
Like :class:`spawnu`, you can pass ``encoding`` and ``errors`` parameters,
which will be used for both input and output.
"""
return _run(command, timeout=timeout, withexitstatus=withexitstatus,
events=events, extra_args=extra_args, logfile=logfile, cwd=cwd,
env=env, _spawn=spawnu, **kwargs)
示例9: readlines
# 需要导入模块: import pexpect [as 别名]
# 或者: from pexpect import run [as 别名]
def readlines(self, sizehint=-1):
'''This reads until EOF using readline() and returns a list containing
the lines thus read. The optional 'sizehint' argument is ignored.
Remember, because this reads until EOF that means the child
process should have closed its stdout. If you run this method on
a child that is still running with its stdout open then this
method will block until it timesout.'''
lines = []
while True:
line = self.readline()
if not line:
break
lines.append(line)
return lines
示例10: execute
# 需要导入模块: import pexpect [as 别名]
# 或者: from pexpect import run [as 别名]
def execute(cmd):
output, status = pexpect.run(cmd
, withexitstatus=1
, timeout=600
)
return output
示例11: tearDown
# 需要导入模块: import pexpect [as 别名]
# 或者: from pexpect import run [as 别名]
def tearDown(self):
'''Test case common fixture teardown.'''
logger.info("======= tearDown: %s", self.delete_artifacts)
self.log_docker_constructs()
new_containers = self.new_constructs('container')
new_images = self.new_constructs('image')
new_volumes = self.new_constructs('volume')
if self.delete_artifacts:
# Every case should clean up its docker images and containers.
for container in new_containers:
# These should have been launched with the --rm flag,
# so they should be removed once stopped.
logger.info("REMOVING %s", container['id'])
pexpect.run('docker stop {}'.format(container['id']))
for image in new_images:
logger.info("REMOVING %s", image['id'])
pexpect.run('docker rmi {}'.format(image['id']))
for volume in new_volumes:
logger.info("REMOVING %s", volume['name'])
pexpect.run('docker volume rm {}'.format(volume['name']))
else:
# We'll leave behind any new docker constructs, so we need
# to update the "original docker volumes".
self.constructs['current']['container'].extend(new_containers)
self.constructs['current']['image'].extend(new_images)
self.constructs['current']['volume'].extend(new_volumes)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - -
示例12: get_docker_image_list
# 需要导入模块: import pexpect [as 别名]
# 或者: from pexpect import run [as 别名]
def get_docker_image_list(*expected_images):
'''Get the output from "docker image ls" for specified image names.'''
image_listing_pattern = (
r'(?P<name>[^\s]+)\s+'
r'(?P<tag>[^\s]+)\s+'
r'(?P<id>[0-9a-f]+)\s+'
r'(?P<created>.+ago)\s+'
r'(?P<size>[^\s]+)'
r'\s*$'
)
image_listing_re = re.compile(image_listing_pattern)
docker_images_response = pexpect.run('docker image ls')
image_list = []
expected_image_nametag_pairs = [
(x.split(':') + ['latest'])[0:2] for x in expected_images
] if expected_images else None
docker_images_response_l = docker_images_response.decode('utf-8').split('\n')
for line in docker_images_response_l:
match = image_listing_re.match(line)
if (
match and (
not expected_images or [
match.groupdict()['name'], match.groupdict()['tag']
] in expected_image_nametag_pairs
)
):
image_list.append(match.groupdict())
return image_list
# - - - - - - - - - - - - - - - - - - - - - - - - - - - -
示例13: get_docker_container_list
# 需要导入模块: import pexpect [as 别名]
# 或者: from pexpect import run [as 别名]
def get_docker_container_list(*expected_containers):
'''Get the output from "docker ps -a" for specified container names.'''
container_listing_pattern = (
r'(?P<id>[0-9a-f]+)\s+'
r'(?P<image>[^\s]+)\s+'
r'(?P<command>"[^"]+")\s+'
r'(?P<created>.+ago)\s+'
r'(?P<status>(Created|Exited.*ago|Up \d+ \S+))\s+'
r'(?P<ports>[^\s]+)?\s+'
r'(?P<name>[a-z]+_[a-z]+)'
# r'\s*$'
)
container_listing_re = re.compile(container_listing_pattern)
docker_containers_response = pexpect.run('docker ps -a')
container_list = []
# expected_container_nametag_pairs = [
# (x.split(':') + ['latest'])[0:2] for x in expected_containers
# ] if expected_containers else []
docker_containers_response_l = docker_containers_response.decode('utf-8').split('\n')
for line in docker_containers_response_l:
match = container_listing_re.match(line)
if match:
container_list.append(match.groupdict())
return container_list
# - - - - - - - - - - - - - - - - - - - - - - - - - - - -
示例14: get_container_details
# 需要导入模块: import pexpect [as 别名]
# 或者: from pexpect import run [as 别名]
def get_container_details(self, image):
'''Run a docker container shell and retrieve several details.'''
# (detail name, command, result filter) for extracting details
# from container command lines.
shell_commands = (
('pwd', 'pwd', None),
('config_file', 'ls {}'.format(CONTAINER_CONFIG_PATH), None),
('config_contents', 'cat {}'.format(CONTAINER_CONFIG_PATH), None),
)
command = "docker run --rm -it {} bash".format(image)
logger.info('IMAGE: %s', image)
logger.info('CONTAINER LAUNCH COMMAND: %s', command)
spawn = pexpect.spawn(command)
container_details = {}
for field, shell_command, response_filter in shell_commands:
container_details[field] = interact(
spawn, shell_command, response_filter
)
# Exit the container.
spawn.sendcontrol('d')
# "Expand" the config records if we found a config file.
if container_details['config_file'] == CONTAINER_CONFIG_PATH:
try:
exec(container_details['config_contents'], container_details)
except SyntaxError:
pass
# The '__builtins__' are noise:
if '__builtins__' in container_details:
del container_details['__builtins__']
return container_details
# - - - - - - - - - - - - - - - - - - - - - - - - - - - -
示例15: test_make_aardvark_sqlite_no_images_tag
# 需要导入模块: import pexpect [as 别名]
# 或者: from pexpect import run [as 别名]
def test_make_aardvark_sqlite_no_images_tag(self):
'''Test "make aardvark-sqlite" without specifying the images tag.'''
self.case_worker(
target='aardvark-sqlite',
expected_docker_images=[
'aardvark-base',
'aardvark-data-init',
'aardvark-collector',
'aardvark-apiserver',
],
expected_details={
'_common': {
'pwd': '/usr/share/aardvark-data',
'NUM_THREADS': 5,
'ROLENAME': 'Aardvark',
'SQLALCHEMY_DATABASE_URI': EXPECTED_SQLITE_DB_URI,
'SQLALCHEMY_TRACK_MODIFICATIONS': EXPECTED_SQL_TRACK_MODS,
},
'aardvark-base': {
'pwd': '/etc/aardvark',
},
},
expected_artifacts=[
'aardvark-base-docker-build',
'aardvark-data-docker-build',
'aardvark-data-docker-run',
'aardvark-apiserver-docker-build',
'aardvark-collector-docker-build',
],
set_images_tag=False
)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Define test suites.
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -