I am trying to get the value from the key in my dictionary. I am trying to match known fingerprints of host devices and return the associated value. I believe it is not properly interperting the variable since there is a slash in it. The code is below.
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])
The first 2 print statements work as expected and the output of host_fingprint is AAAA/CCC. How can I properly use the variable to print the value in the dictionary?
When trying with subprocess.check_output, I am getting
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"
What finally ended up working was to add a couple pieces to the end of the subprocess and then strip the newline charachter.
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()
CodePudding user response:
You are being fooled into thinking that worked by the way things print on the terminal, but os.system
does not return a string. The command you execute just prints its normal output directly to stdout, then os.system
returns the numeric exit code (0).
This should work:
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])