用索引更改日志文件

2024-05-19 02:58:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含用户的文件:

Sep 15 04:34:31 li146-252 sshd[13326]: Failed password for invalid user ronda from 212.58.111.170 port 42579 ssh2

正在尝试使用字符串的索引方法来编辑文件中的用户。到目前为止,我可以打印用户,但现在删除并放入新用户

newuser = 'PeterB'
with open ('test.txt') as file: 
        for line in file.readlines(): 
                lines = line.split() 
                string = ' '.join(lines)
                print string.index('user')+1

Tags: 文件用户forstringlinepasswordsepfile
2条回答

如果您想更改日志中的名称,下面是如何更改的

file = open('tmp.txt', 'r')
new_file = []
for line in file.readlines():  # read the lines
    line = (line.split(' '))
    line[10] = 'vader'  # edit the name
    new_file.append(' '.join(line))  # store the changes to a variable

file = open('tmp.txt', 'w')  # write the new log to file
[file.writelines(line) for line in new_file]

是否要更新文件内容?如果是这样,您可以更新用户名,但需要重写文件或写入第二个文件(为了安全起见):

keyword = 'user'
newuser = 'PeterB'
with open('test.txt') as infile, open('updated.txt', 'w') as outfile:
    for line in infile.readlines():
        words = line.split()
        try:
            index = words.index(keyword) + 1
            words[index] = newuser
            outfile.write('{}\n'.format(' '.join(words)))
        except (ValueError, IndexError):
            outfile.write(line)    # no keyword, or keyword at end of line

请注意,此代码假定输出文件中的每个字都用一个空格隔开

还要注意,这段代码不会删除其中不包含关键字的行(其他解决方案也是如此)


如果要保留原始空白,正则表达式非常方便,生成的代码相对简单:

import re

keyword = 'user'
newuser = 'PeterB'
pattern = re.compile(r'({}\s+)(\S+)'.format(keyword))

with open('test.txt') as infile, open('updated.txt', 'w') as outfile:
    for line in infile:
        outfile.write(pattern.sub(r'\1{}'.format(newuser), line))

相关问题 更多 >

    热门问题