Python遍历等阴影的方式

时间:2018-07-31 10:20:10

标签: python

我正在尝试使用python实现逻辑:

 cat /etc/shadow | awk -F: '($2 == "" ) { print $1 " does not have a password "}'

如果上面的代码为我返回了用户的输出

passwd -l <username>

我正在尝试使用python实现上述逻辑,但是我不确定它是否能以这种方式实现;这是我的python代码:

/etc/shadow看起来

root:*:17709:0:99999:7:::
daemon:*:17709:0:99999:7:::
bin:*:17709:0:99999:7:::
sys:*:17709:0:99999:7:::
sync:*:17709:0:99999:7:::
games:*:17709:0:99999:7:::
man:*:17709:0:99999:7:::
lp:*:17709:0:99999:7:::
mail:*:17709:0:99999:7:::
news:*:17709:0:99999:7:::
uucp:*:17709:0:99999:7:::
proxy:*:17709:0:99999:7:::
www-data:*:17709:0:99999:7:::
backup:*:17709:0:99999:7:::

代码

with open("/etc/shadow") as file:
   for line in file:
       line = line.rstrip()
       if line[line.find(":")+1:line.find(":")]=="":
          print "This is a problem"
       elif line[line.find(":")+1:line.find(":")]=="*":
          print line[line.find(":")+1:line.find(":")]
       else:
          print "All Good"

上面的代码返回“这是一个问题”,这是不正确的

3 个答案:

答案 0 :(得分:1)

您可以使用re提取所需的列:

import re

data = """root:*:17709:0:99999:7:::
daemon:*:17709:0:99999:7:::
bin:*:17709:0:99999:7:::
sys:*:17709:0:99999:7:::
sync:*:17709:0:99999:7:::
games:*:17709:0:99999:7:::
man:*:17709:0:99999:7:::
lp:*:17709:0:99999:7:::
mail:*:17709:0:99999:7:::
news:*:17709:0:99999:7:::
uucp:*:17709:0:99999:7:::
proxy:*:17709:0:99999:7:::
www-data:*:17709:0:99999:7:::
backup:*:17709:0:99999:7:::"""

groups = re.findall('(.*?):(.*?):(.*?):(.*?):(.*?):(.*?):(.*?):(.*?):', data)

if all(g[1].strip() for g in groups):
    print('All good')
else:
    print('This is a problem')

此打印:

All good

此正则表达式here的解释。在第二组(g[1])中,您具有阴影的密码(*)或空字符串。

答案 1 :(得分:1)

尝试一下:

with open("/etc/shadow/") as ff:
   for line in ff:   
        login_name,pwd,remainder=line.split(":",maxsplit=2)
        print(login_name,pwd) # change it as you like

答案 2 :(得分:0)

只需在“:”分隔符上分割行,然后检查第二个位置的值(当然,该位置在索引1):

data = """
root:*:17709:0:99999:7:::
daemon:*:17709:0:99999:7:::
bin:*:17709:0:99999:7:::
sys:*:17709:0:99999:7:::
sync:*:17709:0:99999:7:::
games:*:17709:0:99999:7:::
man:*:17709:0:99999:7:::
lp:*:17709:0:99999:7:::
mail:*:17709:0:99999:7:::
news:*:17709:0:99999:7:::
uucp:*:17709:0:99999:7:::
proxy:*:17709:0:99999:7:::
www-data:*:17709:0:99999:7:::
backup:*:17709:0:99999:7:::
"""

for line in data.strip().splitlines():
    row = [part.strip() for part in line.split(":")]
    if row[1] == "":
        print("this is a problem")
    elif row[1] == "*":
        print row[1] 
    else: 
        print "all good"