Skip to content

Commit a006476

Browse files
committed
Merging pull request 150
Signed-off-by: Lukáš Doktor <[email protected]> * github.com:autotest/aexpect: Remove password from clear text logging in windows ops Pass both ops linux/windows modules through black linting
2 parents c47fdfe + 37785e2 commit a006476

File tree

2 files changed

+79
-46
lines changed

2 files changed

+79
-46
lines changed

aexpect/ops_linux.py

Lines changed: 23 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@
5454
from shlex import quote
5555

5656
from aexpect.exceptions import ShellCmdError
57+
5758
# Need this import for sphinx and other documentation to produce links later on
5859
# from .client import ShellSession
5960

@@ -231,7 +232,7 @@ def ls(session, path, quote_path=True, flags="-1UNq"): # pylint: disable=C0103
231232
Just like :py:func:`os.listdir`, does not include file names starting with
232233
dot (`'.'`)
233234
"""
234-
cmd = f'ls {flags} {quote(path)}' if quote_path else f'ls {flags} {path}'
235+
cmd = f"ls {flags} {quote(path)}" if quote_path else f"ls {flags} {path}"
235236
status, output = session.cmd_status_output(cmd)
236237
status, output = _process_status_output(cmd, status, output)
237238
return output.splitlines()
@@ -253,7 +254,7 @@ def glob(session, glob_pattern):
253254
Alternative implementations are either shell specific or use `echo` and
254255
thus cannot handle spaces in paths well.
255256
"""
256-
cmd = f'find {glob_pattern} -maxdepth 0'
257+
cmd = f"find {glob_pattern} -maxdepth 0"
257258
status, output = session.cmd_status_output(cmd)
258259
if status == 1:
259260
return []
@@ -276,8 +277,11 @@ def move(session, source, target, quote_path=True, flags=""):
276277
Calls `mv source target` through a session. See `man mv` for what source
277278
and target can be and what behavior to expect.
278279
"""
279-
cmd = f'mv {flags} {quote(source)} {quote(target)}' if quote_path \
280-
else f'mv {flags} {source} {target}'
280+
cmd = (
281+
f"mv {flags} {quote(source)} {quote(target)}"
282+
if quote_path
283+
else f"mv {flags} {source} {target}"
284+
)
281285
status, output = session.cmd_status_output(cmd)
282286
_process_status_output(cmd, status, output)
283287

@@ -297,8 +301,11 @@ def copy(session, source, target, quote_path=True, flags=""):
297301
Calls `cp source target` through a session. See `man cp` for what source
298302
and target can be and what behavior to expect.
299303
"""
300-
cmd = f'cp {flags} {quote(source)} {quote(target)}' if quote_path \
301-
else f'cp {flags} {source} {target}'
304+
cmd = f"cp {flags} "
305+
if quote_path:
306+
cmd += f"{quote(source)} {quote(target)}"
307+
else:
308+
cmd += f"{source} {target}"
302309
status, output = session.cmd_status_output(cmd)
303310
_process_status_output(cmd, status, output)
304311

@@ -316,7 +323,7 @@ def remove(session, path, quote_path=True, flags="-fr"):
316323
317324
Calls `rm -rf`.
318325
"""
319-
cmd = f'rm {flags} {quote(path)}' if quote_path else f'rm {flags} {path}'
326+
cmd = f"rm {flags} {quote(path)}" if quote_path else f"rm {flags} {path}"
320327
status, output = session.cmd_status_output(cmd)
321328
_process_status_output(cmd, status, output)
322329

@@ -335,7 +342,7 @@ def make_tempdir(session, template=None):
335342
336343
Calls `mktemp -d`, refer to `man` for more info.
337344
"""
338-
cmd = f'mktemp -d {template}' if template is not None else 'mktemp -d'
345+
cmd = f"mktemp -d {template}" if template is not None else "mktemp -d"
339346
status, output = session.cmd_status_output(cmd)
340347
_, output = _process_status_output(cmd, status, output)
341348
return output
@@ -355,7 +362,7 @@ def make_tempfile(session, template=None):
355362
356363
Calls `mktemp`, refer to `man` for more info.
357364
"""
358-
cmd = f'mktemp {template}' if template is not None else 'mktemp'
365+
cmd = f"mktemp {template}" if template is not None else "mktemp"
359366
status, output = session.cmd_status_output(cmd)
360367
_, output = _process_status_output(cmd, status, output)
361368
return output
@@ -377,7 +384,7 @@ def cat(session, filename, quote_path=True, flags=""):
377384
Should only be used for very small files without tabs or other fancy
378385
contents. Otherwise, it is better to download the file or use some other method.
379386
"""
380-
cmd = f'cat {flags} {quote(filename)}' if quote_path else f'cat {flags} {filename}'
387+
cmd = f"cat {flags} {quote(filename)}" if quote_path else f"cat {flags} {filename}"
381388
status, output = session.cmd_status_output(cmd)
382389
_, output = _process_status_output(cmd, status, output)
383390
return output
@@ -486,15 +493,16 @@ def hash_file(session, filename, size="", method="md5"):
486493
if output:
487494
output = output.strip()
488495
if status != 0 or not output:
489-
raise RuntimeError(f'Could not hash {filename} using {cmd}: {output}')
496+
raise RuntimeError(f"Could not hash {filename} using {cmd}: {output}")
490497

491498
# parse output
492499
hash_str = output.split(maxsplit=1)[0].lower()
493500

494501
# check that all chars are hex
495-
if hash_str.strip('0123456789abcdef'):
496-
raise RuntimeError('Resulting hash string has unexpected characters: '
497-
+ hash_str)
502+
if hash_str.strip("0123456789abcdef"):
503+
raise RuntimeError(
504+
f"Resulting hash string has unexpected characters: {hash_str}"
505+
)
498506
return hash_str
499507

500508

@@ -509,6 +517,6 @@ def extract_tarball(session, tarball, target_dir, flags="-ap"):
509517
:param str flags: extra flags passed to ``tar`` on the command line
510518
:raises: :py:class:`RuntimeError` if tar command returned non-null
511519
"""
512-
cmd = f'tar -C {quote(target_dir)} {flags} -xf {quote(tarball)}'
520+
cmd = f"tar -C {quote(target_dir)} {flags} -xf {quote(tarball)}"
513521
status, output = session.cmd_status_output(cmd)
514522
_process_status_output(cmd, status, output)

aexpect/ops_windows.py

Lines changed: 56 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ def ps_cmd(session, script, timeout=60):
6767
6868
This function was slightly based on a similar function from `pywinrm`.
6969
"""
70+
7071
def nicely_log_str(header, string):
7172
LOG.info(header)
7273
LOG.info("-" * len(header))
@@ -78,12 +79,14 @@ def nicely_log_str(header, string):
7879
# must use utf16 little endian on Windows
7980
encoded_cmd = b64encode(script.encode("utf_16_le")).decode("ascii")
8081
try:
81-
output = session.cmd(f"powershell -NoLogo -NonInteractive -OutputFormat text "
82-
f"-ExecutionPolicy Bypass -EncodedCommand {encoded_cmd}",
83-
timeout=timeout)
82+
output = session.cmd(
83+
f"powershell -NoLogo -NonInteractive -OutputFormat text "
84+
f"-ExecutionPolicy Bypass -EncodedCommand {encoded_cmd}",
85+
timeout=timeout,
86+
)
8487

8588
# there was an error but the exit code was still zero
86-
if output.startswith("#< CLIXML") and "<S S=\"Error\">" in output:
89+
if output.startswith("#< CLIXML") and '<S S="Error">' in output:
8790
raise ShellError(script, output)
8891

8992
# TODO: PowerShell sometimes ignores the -OutputFormat and outputs
@@ -113,7 +116,7 @@ def ps_file(session, filename, timeout=60):
113116
:returns: the output of the command
114117
:rtype: str
115118
"""
116-
cmd = f"powershell -ExecutionPolicy RemoteSigned -File \"{filename}\""
119+
cmd = f'powershell -ExecutionPolicy RemoteSigned -File "{filename}"'
117120
LOG.info("Executing PowerShell file with `%s`", cmd)
118121
return session.cmd(cmd, timeout=timeout)
119122

@@ -132,7 +135,7 @@ def _clean_error_message(message):
132135

133136
output = []
134137
# the strings are between <S S="Error">...</S> tags
135-
for msgstr in message.split("<S S=\"Error\">"):
138+
for msgstr in message.split('<S S="Error">'):
136139
if not msgstr.endswith("</S>"):
137140
continue
138141
msgstr = re.sub(r"</S>$", "", msgstr).replace("_x000D__x000A_", "")
@@ -203,10 +206,16 @@ def query_registry(session, key_name, value_name):
203206
:returns: value of the corresponding sub key and value name or None if not found
204207
:rtype: str or None
205208
"""
206-
key_types = ["REG_SZ", "REG_MULTI_SZ", "REG_EXPAND_SZ",
207-
"REG_DWORD", "REG_BINARY", "REG_NONE"]
209+
key_types = [
210+
"REG_SZ",
211+
"REG_MULTI_SZ",
212+
"REG_EXPAND_SZ",
213+
"REG_DWORD",
214+
"REG_BINARY",
215+
"REG_NONE",
216+
]
208217

209-
out = session.cmd_output(f"reg query \"{key_name}\" /v {value_name}").strip()
218+
out = session.cmd_output(f'reg query "{key_name}" /v {value_name}').strip()
210219
LOG.info("Reg query for key %s and value %s: %s", key_name, value_name, out)
211220
for k in key_types:
212221
parts = out.split(k)
@@ -216,7 +225,9 @@ def query_registry(session, key_name, value_name):
216225
return None
217226

218227

219-
def add_reg_key(session, path, name, value, key_type, force=True): # pylint: disable=R0913
228+
def add_reg_key(
229+
session, path, name, value, key_type, force=True
230+
): # pylint: disable=R0913
220231
"""
221232
Wrapper around the reg add command.
222233
@@ -231,7 +242,7 @@ def add_reg_key(session, path, name, value, key_type, force=True): # pylint: d
231242
if not isinstance(key_type, RegistryKeyType):
232243
raise TypeError(f"{key_type} must be instance of RegistryKeyType")
233244

234-
cmd = f"reg add \"{path}\" /v {name} /d {value} /t {key_type.value}"
245+
cmd = f'reg add "{path}" /v {name} /d {value} /t {key_type.value}'
235246
if force:
236247
cmd += " /f"
237248

@@ -269,7 +280,7 @@ def path_exists(session, path):
269280
:returns: whether the given path exists
270281
:rtype: str
271282
"""
272-
output = session.cmd_output(f"if exist \"{path}\" echo yes")
283+
output = session.cmd_output(f'if exist "{path}" echo yes')
273284
return output.strip() == "yes"
274285

275286

@@ -283,7 +294,7 @@ def hash_file(session, filename):
283294
:returns: hash value
284295
:rtype: str
285296
"""
286-
output = session.cmd(f"certutil -hashfile \"{filename}\" MD5")
297+
output = session.cmd(f'certutil -hashfile "{filename}" MD5')
287298
LOG.debug("certutil output for %s is %s", filename, output)
288299
hash_value = output.splitlines()[1]
289300
LOG.debug("Hash value is %s", hash_value)
@@ -302,9 +313,9 @@ def mkdir(session, path, exist_ok=True):
302313
exists and exist_ok is False
303314
"""
304315
if exist_ok:
305-
cmd = f"if not exist \"{path}\" mkdir \"{path}\""
316+
cmd = f'if not exist "{path}" mkdir "{path}"'
306317
else:
307-
cmd = f"mkdir \"{path}\""
318+
cmd = f'mkdir "{path}"'
308319
session.cmd(cmd)
309320

310321

@@ -318,7 +329,7 @@ def touch(session, path):
318329
:returns: path of the file created
319330
:rtype: str
320331
"""
321-
session.cmd(f"type nul > \"{path}\"")
332+
session.cmd(f'type nul > "{path}"')
322333
return path
323334

324335

@@ -381,7 +392,9 @@ def tempfile(session, local=True):
381392
###############################################################################
382393

383394

384-
def run_as(session, user, password, command, timeout=60, background=False): # pylint: disable=R0913
395+
def run_as(
396+
session, user, password, command, timeout=60, background=False
397+
): # pylint: disable=R0913
385398
"""
386399
Run a command as different user.
387400
@@ -401,17 +414,17 @@ def run_as(session, user, password, command, timeout=60, background=False): #
401414
def _run_as(cmd_to_run):
402415
LOG.debug("Running command `%s`", cmd_to_run)
403416
session.sendline(cmd_to_run)
404-
LOG.debug("Entering password `%s`", password)
417+
LOG.debug("Entering password")
405418
session.read_until_output_matches(["Geben Sie das Kennwort"])
406419
session.sendline(password)
407420

408421
if background is True:
409-
_run_as(f"runas /user:{user} \"{command}\"")
422+
_run_as(f'runas /user:{user} "{command}"')
410423
return None
411424

412425
outfile = tempfile(session, local=False)
413426
# runas produces no output, so we add a redirection to the inner command
414-
cmd = f"runas /user:{user} \"cmd.exe /c {command} > {outfile}\""
427+
cmd = f'runas /user:{user} "cmd.exe /c {command} > {outfile}"'
415428
_run_as(cmd)
416429
LOG.debug("Waiting %s seconds for the command to finish", timeout)
417430
# no need to capture anything, we redirected the output
@@ -432,7 +445,7 @@ def kill_program(session, program, kill_children=True):
432445
:param str program: name of the program to kill
433446
:param bool kill_children: whether to kill child processes
434447
"""
435-
cmd = f"taskkill /f /im \"{program}\""
448+
cmd = f'taskkill /f /im "{program}"'
436449
if kill_children:
437450
cmd += " /t"
438451
session.cmd(cmd)
@@ -452,8 +465,9 @@ def wait_process_end(session, process, timeout=30):
452465
LOG.info("Waiting for process %s to end using PowerShell", process)
453466

454467
# give some extra timeout to wait for PowerShell to return
455-
ps_cmd(session, f"Wait-Process -Name {process} -Timeout {timeout}",
456-
timeout=timeout+5)
468+
ps_cmd(
469+
session, f"Wait-Process -Name {process} -Timeout {timeout}", timeout=timeout + 5
470+
)
457471

458472

459473
def kill_session(session):
@@ -504,7 +518,9 @@ def find_unused_port(session, start_port=10024):
504518
:rtype: int
505519
"""
506520
# pylint: disable=C0301
507-
output = ps_cmd(session, f"""
521+
output = ps_cmd(
522+
session,
523+
f"""
508524
$port = {start_port}
509525
while($true) {{
510526
try {{
@@ -521,7 +537,8 @@ def find_unused_port(session, start_port=10024):
521537
}}
522538
523539
Write-Host "::unused=$port"
524-
""")
540+
""",
541+
)
525542
# pylint: enable=C0301
526543
port = re.search(r"::unused=(\d+)", output).group(1)
527544
return int(port)
@@ -540,7 +557,9 @@ def curl(session, url, proxy_address=None, proxy_port=None, insecure=False):
540557
:rtype: (int, str)
541558
"""
542559
# extra indentation is not allowed within PS heredocs
543-
skip_ssl_template = dedent("""\
560+
# pylint: disable=C0301
561+
skip_ssl_template = dedent(
562+
"""\
544563
Add-Type -Language CSharp @"
545564
namespace System.Net
546565
{
@@ -555,22 +574,28 @@ def curl(session, url, proxy_address=None, proxy_port=None, insecure=False):
555574
}
556575
}
557576
"@;
558-
[System.Net.Util]::Init()""")
577+
[System.Net.Util]::Init()"""
578+
)
559579

560580
# TODO: WebRequest (wrapper on top of System.Net.WebClient) is painfully slow
561581
# for some reason compared to the 3rd-party curl.exe tool, but let's use it for now.
562-
webrequest_cmd = f"Invoke-WebRequest -Uri \"{url}\""
582+
webrequest_cmd = f'Invoke-WebRequest -Uri "{url}"'
563583
if proxy_address is not None:
564584
# the session user must have access to the proxy (otherwise use -ProxyCredential)
565-
webrequest_cmd += f" -Proxy http://{proxy_address}:{proxy_port} -ProxyUseDefaultCredentials"
585+
webrequest_cmd += (
586+
f" -Proxy http://{proxy_address}:{proxy_port} -ProxyUseDefaultCredentials"
587+
)
566588

567-
output = ps_cmd(session, f"""
589+
output = ps_cmd(
590+
session,
591+
f"""
568592
{skip_ssl_template if insecure else ''}
569593
$ProgressPreference = 'SilentlyContinue'
570594
$result = {webrequest_cmd}
571595
Write-Output $result.StatusCode
572596
Write-Output $result.Content
573-
""")
597+
""",
598+
)
574599

575600
LOG.debug("Powershell request produced output:\n'%s'", output)
576601
try:

0 commit comments

Comments
 (0)