我正在尝试从字典中的键中获取值。我正在尝试匹配主机设备的已知指纹并回传相关值。我相信它没有正确解释变量,因为它有斜线。代码如下。
fingerprints = {
'AAAABBBB': 'host1',
'AAAA/CCC': 'tester',
'AAAADDDD': 'plif'
}
host_fingerprint = os.system("ssh-keyscan <ip of target> 2>&1 | grep ed25519 | cut -d ' ' -f 3")
print(host_fingerprint)
print(fingerprints['AAAA/CCC'])
print(fingerprints[host_fingerprint])
前 2 个打印陈述句按预期作业,host_fingprint 的输出为 AAAA/CCC。如何正确使用变量来打印字典中的值?
尝试使用 subprocess.check_output 时,我得到
Getting error:
Traceback (most recent call last):
File "~/starkiller/starkiller.py", line 50, in <module>
main()
File "~/starkiller/starkiller.py", line 45, in main
match_users()
File "~/starkiller/starkiller.py", line 37, in match_users
host_fingerprint = subprocess.check_output("ssh-keyscan 10.10.10.30 2>&1 | grep ed25519 | cut -d ' ' -f 3")
File "/usr/lib/python3.9/subprocess.py", line 424, in check_output
return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
File "/usr/lib/python3.9/subprocess.py", line 505, in run
with Popen(*popenargs, **kwargs) as process:
File "/usr/lib/python3.9/subprocess.py", line 951, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "/usr/lib/python3.9/subprocess.py", line 1823, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: "ssh-keyscan <target IP> 2>&1 | grep ed25519 | cut -d ' ' -f 3"
最终的作业是在子流程的末尾添加几个部分,然后去除换行符。
keyscan = subprocess.check_output(["ssh-keyscan <target IP> 2>&1 | grep ed25519 | cut -d ' ' -f 3"], shell=True, universal_newlines=True)
host_fingerprint = keyscan.strip()
uj5u.com热心网友回复:
你被愚弄了,认为它是按照终端上打印的方式作业的,但os.system
不回传字符串。您执行的命令只是将其正常输出直接打印到 stdout,然后os.system
回传数字退出代码 (0)。
这应该有效:
fingerprints = {
'AAAABBBB': 'host1',
'AAAA/CCC': 'tester',
'AAAADDDD': 'plif'
}
host_fingerprint = subprocess.check_output("ssh-keyscan <ip of target> 2>&1 | grep ed25519 | cut -d ' ' -f 3")
print(host_fingerprint)
print(fingerprints['AAAA/CCC'])
print(fingerprints[host_fingerprint])
0 评论