Mini Shell
#!/opt/imh-python/bin/python3
"""Search for and kill old moveuser keys"""
import os
import sys
import time
SSH_ROOT = '/home/moveuser/.ssh'
AGE = 604800 # 7 days in seconds
def main():
"""Search for and kill old moveuser keys"""
try:
found = os.listdir(SSH_ROOT)
except OSError:
print(SSH_ROOT, 'is missing; nothing to do')
sys.exit(0)
auth_found = 'authorized_keys' in found
found = [
os.path.join(SSH_ROOT, x)
for x in found
if x.endswith('.key') or x.endswith('.config')
]
if auth_found:
clean_auth()
clean_found(found)
print('done.')
def clean_auth():
"""Remove public keys older than 2 days"""
auth_path = os.path.join(SSH_ROOT, 'authorized_keys')
cutoff = time.time() - AGE
fixed = []
with open(auth_path, encoding='utf-8') as auth_file:
auth_data = auth_file.readlines()
for line in auth_data:
items = line.strip().split()
if not items: # blank line
continue
if items[0] != "ssh-rsa": # the only one we actually use
print('removed(invalid):', line)
continue # invalid line
comment_last = items[-1]
try:
stamp = get_stamp(comment_last)
except ValueError: # missing a timestamp
# add it to be expired in 2 days
fixed.append(f'{line} {time.time() + AGE}')
print('added expiration:', line)
continue
if stamp > cutoff:
fixed.append(line)
else:
print('removed(old):', line)
with open(auth_path, 'w', encoding='utf-8') as auth_file:
auth_file.write('\n'.join(fixed))
auth_file.write('\n')
def get_stamp(comment_last: str) -> int:
"""Try to get the timestamp placed by SNM in authorized_keys"""
try:
# it was just a column with a float timestamp
return int(float(comment_last))
except ValueError:
pass
# try to get it as comment_timestamp
return int(float(comment_last.split('_')[-1]))
def clean_found(found: list[str]):
"""Remove private keys and ssh configs older than 7 days"""
cutoff = time.time() - AGE
for item in found:
if os.stat(item).st_mtime < cutoff:
print('removed(old):', item)
os.remove(item)
if __name__ == '__main__':
main()
Zerion Mini Shell 1.0