Check if local account has a blank password using Python - python

I'm trying to build a script that checks to see whether or not the password on the currently logged in user's local account has a password that isn't blank in Windows. I need this to run as part of a background check for security compliance; it's going to report to a Nagios server. I need this done in Python, but I'm open to PowerShell if Python won't do it.
So, the script will need to detect:
The username of the currently logged in user.
Whether or not the aforementioned user has a blank password.
Return error code 0 if the password is NOT blank, error code 2 if it is.
I'm stuck on just whichever bit of code will allow me to check if the password of the current user is "". I have a layout which, without too many embellishments, looks something like this:
import os
import Tkinter
import tkMessageBox
from Tkinter import Tk, Toplevel
MyGui.update_idletasks()
MyGui.attributes('-topmost', True)
MyGui.geometry('{}x{}'.format(300, 150))
MyGui.resizable(width=False, height=False)
MyGui.withdraw()
ThisUser = os.getlogin()
ThisPassword = ... # line of code necessary to test for blank password; this is the part where I'm stuck
if ThisPassword = "":
tkMessageBox.showerror("Error For User Here", parent=MyGui)
print "No password set!"
sys.exit(2)
else:
print "Password exists."
sys.exit(0)
I spotted this article, where a WinAPI commend LogonUser is used, but I'm not savvy with C#. Python is more within my comfort zone, I just can't figure out how to check whether or not a password set is blank. I don't want to collect the password, itself.

If a user's password is not blank, then attempting a logon with a blank password will fail with the error code ERROR_LOGON_FAILURE. If it is blank, then the logon will either succeed or, if system policy forbids blank passwords, will fail with the error code ERROR_ACCOUNT_RESTRICTION. For example:
import winerror
import win32security
def is_password_blank(username):
try:
token = win32security.LogonUser(username, None, '',
win32security.LOGON32_LOGON_INTERACTIVE,
win32security.LOGON32_PROVIDER_DEFAULT)
except win32security.error as e:
if e.winerror == winerror.ERROR_ACCOUNT_RESTRICTION:
return True
elif e.winerror == winerror.ERROR_LOGON_FAILURE:
return False
raise
else:
token.Close()
return True

Related

Wondering why my error message pops up through every name read in a file?

I'm making a program in Python for a class that involves logging in to get to the main GUI. Currently, this file has 3 sets of usernames and passwords. My intention was for when the user clicks a button, the program reads through all account username and password combinations from a txt file, and if it does not find a match, an error message shows up. Right now it is giving that error message after it reads each set of names. So if I try to sign in with the last account's information in the file, it will give me the error 2 times, then proceed to log in. If anyone has any advice to help fix my logic, I'd greatly appreciate it.
def verify_login(login):
user = login.login_window.username_entry.get()
password = login.login_window.password_entry.get()
accounts = open("accounts.txt",'r')
for line in accounts.readlines():
login_info = line.split()
if (user == login_info[0] and password == login_info[1]):
print("Account found. Logging in...")
###
### take to main gui
###
else:
tk.messagebox.showerror("Error", "Account not found. Try again.")
login.login_window.username_entry.delete(0,END)
login.login_window.password_entry.delete(0,END)
Like this:
def verify_login(login):
user = login.login_window.username_entry.get()
password = login.login_window.password_entry.get()
accounts = open("accounts.txt",'r')
found = False
for line in accounts.readlines():
login_info = line.split()
if (user == login_info[0] and password == login_info[1]):
print("Account found. Logging in...")
found = True
break
###
### take to main gui
###
if not found:
tk.messagebox.showerror("Error", "Account not found. Try again.")
login.login_window.username_entry.delete(0,END)
login.login_window.password_entry.delete(0,END)
If you return during the "success" processing, then you don't need the found flag. Once you exit the loop, you know you have a failure.

How do I get the right string to work with Database connection

I am using python Qt and MySQLdb and I got this problem:
In this function
def connection(self,username,password):
try:
self.conn=MySQLdb.connect(host="localhost",user=username,passwd=password)
return True
except MySQLdb.Error:
return False
When I enter manually the username and password it goes well but when I try to get it from a Qt interface using:
str(pass_text.text())
it couldn't connect. When I tried:
print str(pass_text.text())
it does print the write string. I am confused... can you help me please?

Is there a way to detect whether a command prompt is available in python/django?

I have some code that will some times be run from a command line (django management command) and sometimes not (django changelist action). In this code, if a certain exception is raised, I can get some user input and keep going if the a command prompt (stdin) is available. Otherwise, I need to just let the exception propagate or do something different.
e.g.
def copy_account_settings(old_acct_domain, new_acct_domain):
try:
new_account = Account.objects.get(domain = new_acct_domain)
except Account.DoesNotExist:
print ("Couldn't find an account matching %s." % new_acct_domain)
if <command prompt is available>:
print "Would you like to create the account? (y/n)"
if raw_input().lower().strip()='y':
# get some more input and create the account and move on
else:
raise
How would you do this?
Perhaps you can check for a TTY?
import os
if os.isatty(0):
That should return true if the session is interactive and false if not.

GData: How to avoid hardcoding login info

I am working on a reporting system which automatically updates results overnight and puts them in files on a google drive.
The way it is working right now is by hardcoding the login and password information which is by no means ideal even if it works. A search in StackOverflow does not point this question specifically, which surprises me.
A very simplified example with the relevant sections of code looks like:
import gdata.docs.service
class GDrive(object):
def __init__(self, email, password)
self.gd_client = gdata.docs.service.DocService()
self.gd_client.ClientLogin(email, password)
def upload(self):
# Code to Upload file somewhere in GDrive.
gd = GDrive("the#email.address", "ThePassword")
gd.upload()
Can something be done to avoid writing explicitly the username and password?
I would make use of the OAuth2 protocol. It is a secure way to store credentials for a long time (but not forever).
A bit of a short answer from my cell, but check:
https://developers.google.com/drive/about-auth
And this bit makes working with Oauth2 a lot easier:
https://developers.google.com/api-client-library/python/platforms/google_app_engine#Decorators
import gdata.docs.service
import sys
class GDrive(object):
def __init__(self, email, password)
self.gd_client = gdata.docs.service.DocService()
self.gd_client.ClientLogin(email, password)
def upload(self):
# Code to Upload file somewhere in GDrive.
if __name__ == "__main__":
username = sys.argv[1]
password = sys.argv[2]
gd = GDrive(username, password)
gd.upload()
now run from your commandline like script.py the#email.address ThePassword where script.py is the name of your python scripts...

git server side hooks

I am running into a problem when running the follow python script on the server looking for commit information for the push making sure it follows a particular syntax, I am unable to get input from the user which is why the username and password are hard coded. I am now also unable to get the list of commit message that occurred before this particular push.
#!/usr/bin/python
import SOAPpy
import getpass
import datetime
import sys
import re
import logging
import os
def login(x,y):
try:
auth = soap.login(x, y)
return auth
except:
sys.exit( "Invalid username or password")
def getIssue(auth,issue):
try:
issue = soap.getIssue(auth, issue)
except:
sys.exit("No issue of that type found : Make sure all PRs are vaild jira PRs")
def git_get_commit_msg(commit_id):
return get_shell_cmd_output("git rev-list --pretty --max-count=1 " + commit_id)
def git_get_last_commit_id():
return get_shell_cmd_output("git log --pretty=format:%H -1")
def getCommitText():
commit_msg_filename = sys.argv[1]
try:
commit_msg_text = open(commit_msg_filename).read()
return commit_msg_text
except:
sys.exit("Could not read commit message")
def git_get_array_of_commit_ids(start_id, end_id):
output = get_shell_cmd_output("git rev-list " + start_id + ".." + end_id)
if output == "":
return None
commit_id_array = string.split(output, '\n')
return commit_id_array
def get_shell_cmd_output(cmd):
try:
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
return proc.stdout.read().rstrip('\n')
except KeyboardInterrupt:
logging.info("... interrupted")
except Exception, e:
logging.error("Failed trying to execute '%s'", cmd)
def findpattern(commit_msg):
pattern = re.compile("\w\w*-\d\d*")
group = pattern.findall(commit_msg)
print group
found = len(group)
found =0
issues = 0
for match in group:
auth = soap.login(jirauser,passwd)
getIssue(auth,match)
issues = issues + 1
found+=1
if found ==0:
sys.exit("No issue patterns found.")
print "Retrieved issues: " + str(issues)
def update():
print sys.argv[2]
print sys.argv[3]
old_commit_id = sys.argv[2]
new_commit_id = sys.argv[3]
commit_id_array = git_get_array_of_commit_ids(old_commit_id, new_commit_id)
for commit_id in commit_id_array:
commit_text = git_get_commit_msg(commit_id)
findpattern(commit_text)
soap = SOAPpy.WSDL.Proxy('some url')
# this line if for repointing the input from dev/null
#sys.stdin = open('/dev/tty', 'r') # this fails horribly.
#ask user for input
#jirauser = raw_inp
#("Username for jira: ")
jirauser = "username"
passwd = "987654321"
#passwd = getpass.getpass("Password for %s: " % jirauser)
login(jirauser,passwd)
#commit_msg = getCommitText()
#findpattern(commit_msg)
update()
The intended goal of this code is to check the commits made locally, and to parse through them for the intended pattern, as well as checking the in jira if that PR exists. it is a server side hook that get activated on a push to the repository.
Any tips on writing python hooks would be appreciated. Please and thank you.
I suggest that you have a look at gitorious (http://gitorious.org/gitorious).
They use ssh to handle authentication and rights management (getting the username given by ssh).
They also have some hooks on git repositories. I guess it could help to see how they are processing git hooks using ruby.
By the time your update hook fires, the server has the new commits: the question is whether your hook will allow the ref in question to move. What information from the local (sending) repository do you want?
For the credentials issue, funnel everyone through a single user. For example, GitHub does it with the git user, which is why their SSH URLs begin with git#github.com:.... Then in ~git/.ssh/authorized_keys, associate a username with each key. Note that the following should be on a single line but is wrapped for presentation purposes.
no-agent-forwarding,no-port-forwarding,no-pty,no-X11-forwarding,
command="env myuser=gbgcoll /usr/bin/git-shell -c \"${SSH_ORIGINAL_COMMAND:-}\""
ssh-rsa AAAAB...
Now to see who's trying to do the update, your hook examines the $myuser environment variable.
This doesn't give you each user's Jira credentials. To solve that issue, create a dummy Jira account that has read-only access to everything, and hardcode that Jira account's credentials in your hook. This allows you to verify that a given PR exists.

Categories