简体   繁体   中英

python2.7 multiple definitions, only one executes

I'm new to python and coding in general, but a need at work has offered me an opportunity to see if I can find/write a workable idea/solution. The ultimate end goal is to have a Salt-Stack module, but for now am just focusing on straight python code.
The need is to have code that will help us determine stale/old logins, and then eventually logic to then do something with those accounts. Below is what I've been able to put together so far, and the first definition works and provides the output I'd expect. However, the second definition doesn't seem to execute at all and I'm at a loss as to why. Here is what I've pieced together so far:

import subprocess
import re


logins = "for i in `cat /etc/passwd |awk -F : '{print $1}'`; do lastlog -u     $i|grep -v Username|grep -v Never; done "
p = subprocess.Popen(logins, shell=True, bufsize=0, stdout=subprocess.PIPE, universal_newlines=True)
p.wait()
output = p.stdout.read()
p.stdout.close()

nevers = "for n in `cat /etc/passwd |awk -F : '{print $1}'`; do lastlog -u $n|grep -v Username|grep Never; done "
p = subprocess.Popen(nevers, shell=True, bufsize=0, stdout=subprocess.PIPE,   universal_newlines=True)
p.wait()
never_output = p.stdout.read()
p.stdout.close()


def last_login():
  pattern = re.compile(r'(\w+)(\s+\B.\bpts\/\d\s+[^A-Z]+)  (\w+\s\w+\s+\d+\s+\d+:\d+:\d+)(\s+-\d+\s+)(\d+)')

  for m in re.finditer(pattern, output):
    print m.group(1), '\t', m.group(3), m.group(5)
  #return output


def never_logged_in():
  pattern = re.compile(r'(\w+)(\s+\S+\s\s+\s\w+\S+)')

  for x in re.finditer(pattern, never_output):
     print x.group(1)
  #return never_output


def main():
     never_logged_in()
     last_login()

main()

This is an example of what "def last_login()" does provide:

test1   Sun Mar 26 15:21:58 2017
test2   Sun Mar 26 15:22:08 2017

This is an example of what "def never_logged_in()" SHOULD provide:

test4

Thanks for any ideas/suggestions as this has already been a grand learning adventure and I'm excited to see if I can actually make this work. And no, this is not a class project... those days are way behind me ... :-)

My code was okay, it was my regex that was not working as intended. The solution is:

def never_logged_in():
  pattern = re.compile(r'(\w+)(\s+\*\*Never logged in\*\*)')

  for x in re.finditer(pattern, never_output):
     print x.group(1)

Now on to the next phase ... thanks all!

do as following

  1. add print(never_output) after main()
  2. compare never_output with pattern = re.compile(r'(\\w+)(\\s+\\S+\\s\\s+\\s\\w+\\S+)')

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