简体   繁体   中英

replace a character in a /etc/passwd file without breaking system using Python

I am trying to harden a Ubuntu system and doing the 2 steps:

  1. Running the following command and verifying no output is returned

grep '^+:' /etc/passwd

  1. If there is a output being returned then Remove any legacy '+' entries from /etc/passwd if they exist.

I have written the following python function :

def passwd_safe():
    file = "/etc/passwd"
    for line in fileinput.input(file,inplace=1):
        if '+' in line:
            line = line.replace('+','')
        else:
            pass

But it seems like this doesn't work as expected , infact it overwrites the whole /etc/passwd file and leaves the system broken.

You should print the line to standard output:

def passwd_safe():
    file = "/etc/passwd"
    for line in fileinput.input(file,inplace=1):
        if not line.startswith('+'):
            print(line, end='')

Excerpt from fileinput 's documentation :

Optional in-place filtering: if the keyword argument inplace=True is passed to fileinput.input() or to the FileInput constructor, the file is moved to a backup file and standard output is directed to the input file (if a file of the same name as the backup file already exists, it will be replaced silently).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM