Created
November 30, 2023 20:12
-
-
Save kjs3/f0360b162925ea6db2ca3c302d00843e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import sys | |
import re | |
# | |
# Allows user to approve sudo commands with TouchID and Apple Watch. | |
# This script adds the following line to /etc/pam.d/sudo: | |
# | |
# auth sufficient pam_tid.so | |
# | |
def insert_line_after_regex(file_path, exit_pattern, search_pattern, new_line): | |
try: | |
# Read the content of the file | |
with open(file_path, 'r') as file: | |
content = file.read() | |
# Check if desired line already exists | |
if re.search(exit_pattern, content): | |
print(f"\nLine already exists in {file_path}:\n\n{new_line}\n\nYou should be good to go but might need to restart.") | |
return | |
# Search for pattern and insert new line | |
match = re.search(search_pattern, content) | |
if match: | |
# Insert a new line below the matched line | |
index = match.end() | |
modified_content = content[:index] + '\n' + new_line + content[index:] | |
# Write the modified content back to the file | |
with open(file_path, 'w') as file: | |
file.write(modified_content) | |
print(f"\nNew line inserted in {file_path}:\n\n{new_line}\n\nRestart the computer and you're done. 🍻") | |
# No match found | |
else: | |
# Append new line to end of file | |
with open(file_path, 'a') as file: | |
file.write(new_line) | |
print(f"\nNew line inserted in {file_path}:\n\n{new_line}\n\nRestart the computer and you're done. 🍻") | |
except Exception as e: | |
print(f"An error occurred: {e}") | |
def run_with_sudo(): | |
# Re-run the script with sudo privilege | |
if os.geteuid() != 0: | |
args = ['sudo', sys.executable] + sys.argv + [os.environ] | |
os.execlpe('sudo', *args) | |
if __name__ == "__main__": | |
run_with_sudo() | |
file_path = '/etc/pam.d/sudo' | |
search_pattern = r'auth\s+sufficient\s+pam_smartcard\.so' | |
exit_pattern = r'auth\s+sufficient\s+pam_tid\.so' | |
new_line = 'auth sufficient pam_tid.so' | |
insert_line_after_regex(file_path, exit_pattern, search_pattern, new_line) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment