我正在嘗試從字典中的鍵中獲取值。我正在嘗試匹配主機設備的已知指紋并回傳相關值。我相信它沒有正確解釋變數,因為它有斜線。代碼如下。
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])
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/390764.html
標籤:蟒蛇-3.x
