Indent or sequencing problems with python - python-2.7

I am new to python and have probably started with something a little complicated. Nevertheless I am nearly there.
My problem is I am having a bit of difficulty understanding how to group, or sequence a group of statements in my code (my syntax is probably wrong as well) using try and except or if, elsif and else. I really just need someone to say I should be using this instead of that and I can figure it out from there.
Here is a diagram of what I am trying to accomplish:
https://drive.google.com/file/d/0BxtxgkV8mylgSFRuMnZtaEpXLVE/view?usp=sharing
And here is my code so far (please note this is my FIRST python program - actually first program of any sort - so I would appreciate it if you would not tear me apart too badly for any formatting or syntax errors - updated to include Johns fix)
import ldap
import os
import subprocess
import uuid
from pwd import getpwnam
# Lookup all the users in the cloud group
path='dc=saao'
l=ldap.open('ldap1.cape')
l.protocol_version = ldap.VERSION3
l.simple_bind('dc=cape')
a=l.search_s(path,ldap.SCOPE_SUBTREE,'cn=cloudcape')
# Add members to uids
uids=a[0][1]['memberUid']
# Check if a bindmount already exists or it not, that each cloud group user has the required directory i.e. /home/USER/cloud and /var/www/owncloud/data/USER/files
for uid in uids:
cloudfiledir="/var/www/owncloud/data/"+uid+"/files"
clouddir="/home/"+uid+"/cloud"
try:
subprocess.check_output(["mountpoint", cloudfiledir])
# If the output is all good, their bind mount is setup and mounted
break
except:
print uid+" has not logged into ownCloud yet - please ask them to do so and then try again"
break
# Now check if they have the required directories
try:
if os.path.isdir(cloudfiledir):
print "user "+ uid +" has a data directory in the owncloud data directory- this is good."
if os.path.isdir("/home/"+uid+"/cloud"):
print "user "+ uid +" has a cloud dir in their home directory - this is good."
else:
# They don't have a cloud directory, creating one
print uid+" does not have a cloud folder in their home directory, creating it"
if not os.path.exists("/home/"+uid+"/cloud"):
os.makedirs("/home/"+uid+"/cloud")
# Now set permissions ("+uid+":Domain Users) - os.chown(path, uid, gid)
os.chown("/home/"+uid+"/cloud", "+uid+", "Domain Users")
else:
break
# Now make sure the cloufilesdir is empty
if not os.listdir(cloudfiledir):
print "Empty"
break
except:
print "rename and recreate the folder"
os.rename(clouddir, clouddir + str(uuid.uuid4()))
os.makedirs(clouddir)
os.chown(clouddir, 33, 33)
print "Now let's bind mount the directories"
# Bind each users home dir to their cloud dir
# Eg: bindfs -M www-data --create-for-user=1168 --create-for-group=513 /home/simon/cloud /var/www/owncloud/data/simon/files
# Still figuring this bit out
for user in a[0][1]['memberUid']:
filt = "(uid=" + user + ")"
u=l.search_s(path, ldap.SCOPE_SUBTREE, filt, ['uidNumber'])
print "\t", user, "filter: ", filt, u, "or"
uid = u[0][1]['uidNumber'][0]
print "\t\t", user, filt, uid
command = 'bindfs -M www-data --create-for-user=' + uid + ' --create-for-group=513 ' + '/home/' + user + '/cloud' + ' /var/www/owncloud/data/' + user + '/files'
print "BINGO: ", command, "\n"
John's advice fixed my except syntax, not I need to try and understand why the program only runs for the first UID and not the rest of them (there are 5 in the ldap group at the moment, 2 of which I have manually mounted so I would expect 3 bind mounts to happen).
I would appreciate any guidance as I continue to try and figure this out by trial and error.
Thanks in advance.
Simon

So, much reading and asking some wise colleagues later, I much a much better understanding of how for loops work, what break does and how useful continue can be.
Here is my final piece of code:
#!/usr/bin/python
import ldap
import os
import subprocess
import uuid
from pwd import getpwnam
# Lookup all the users in the cloudcape group
path='dc=cape'
l=ldap.open('ldap1.cape')
l.protocol_version = ldap.VERSION3
l.simple_bind('dc=cape')
a=l.search_s(path,ldap.SCOPE_SUBTREE,'cn=cloudcape')
# Add members to uids
uids=a[0][1]['memberUid']
# Check if a bindmount already exists or it not, that each cloud group user has the required directory i.e.home/USER/cloud and /var/www/owncloud/data/USER/files
for uid in uids:
# Define the directory paths
cloudfiledir="/var/www/owncloud/data/"+uid+"/files"
clouddir="/home/"+uid+"/cloud"
try:
subprocess.check_output(["mountpoint", cloudfiledir])
# If the output is all good, their bind mount is setup and mounted, if not carry on
except subprocess.CalledProcessError:
print uid+" does not have a mountpoint"
else:
continue
# Check if they have /var/www/owncloud/data/UID
if not os.path.isdir(cloudfiledir):
print uid+" does not have a owncloud directory structure in /var/www/owncloud, creating it"
os.makedirs("/var/www/owncloud/data/"+uid+"")
os.makedirs("/var/www/owncloud/data/"+uid+"/files")
os.makedirs("/var/www/owncloud/data/"+uid+"/cache")
# Now set permissions ("+uid+":Domain Users) - os.chown(path, uid, gid)
os.chown("/var/www/owncloud/data/"+uid+"", 33, 33)
os.chown("/var/www/owncloud/data/"+uid+"/files", 33, 33)
os.chown("/var/www/owncloud/data/"+uid+"/cache/", 33, 33)
# Now check if the have /home/UID/cloud
if not os.path.isdir(clouddir):
# They don't have a cloud directory, creating one
print uid+" does not have a cloud folder in their home directory, creating it"
os.makedirs(clouddir)
# Now set permissions ("+uid+":Domain Users) - os.chown(path, uid, gid)
os.chown(clouddir, "+uid+", "Domain Users")
# Now make sure the cloudfilesdir is empty
try:
if not os.listdir(cloudfiledir) == []:
print "The mount point is not empty"
os.rename(cloudfiledir, cloudfiledir + str(uuid.uuid4()))
os.makedirs(cloudfiledir)
os.chown(cloudfiledir, 33, 33)
except:
print "The mount point is empty, moving on"
print "Now let's bind mount the directories"
# Bind each users home dir to their cloud dir
filt = "(uid=" + uid + ")"
userid=l.search_s(path, ldap.SCOPE_SUBTREE, filt, ['uidNumber'])
print "\t", uid, "filter: ", filt, userid, "or"
numuid = userid[0][1]['uidNumber'][0]
print "\t\t", uid, filt, uid
os.system('bindfs -M www-data --create-for-user=' + numuid + ' --create-for-group=513 ' + '/home/' + uid + '/cloud' + ' /var/www/owncloud/data/' + uid + '/files')
I have no doubt there are simpler and more efficient ways to do this but for now, the code does what I want it to do. I still need to build some fault tolerance into it, I already spotted one area where it might fail if a certain directory exists but that is next weeks problem.

Related

Crack a zip using python 2

I need to crack a zip file and i know the first part of the password but I don't know the last 3 letters. This is what i've written but it doesn't work. I have no idea why. can anyone spot my mistake?
T
import zipfile
import itertools
import time
# Function for extracting zip files to test if the password works!
def extractFile(zip_file, password):
try:
zip_file.extractall(pwd=password)
return True
except KeyboardInterrupt:
exit(0)
except Exception, e:
pass
# Main code starts here...
# The file name of the zip file.
zipfilename = 'data.zip'
# The first part of the password.
first_half_password = 'Cola'
# We don't know what characters they add afterwards...
# This is case sensitive!
alphabet = 'abcdefghijklmnopqrstuvwxyz'
zip_file = zipfile.ZipFile(zipfilename)
# We know they always have 3 characters after the first half of the password
# For every possible combination of 3 letters from alphabet...
for c in itertools.product(alphabet, repeat=3):
# Slowing it down on purpose to improve performance in web terminal.
# Remove this line at your peril
time.sleep(0.001)
# Add the three letters to the first half of the password.
password = first_half_password+''.join(c)
# Try to extract the file.
print "Trying: %s" % password
# If the file was extracted, you found the right password.
if extractFile(zip_file, password):
print '*' * 20
print 'Password found: %s' % password
print 'Files extracted...'
exit(0)
# If no password was found by the end, let us know!
print 'Password not found.'

Python script executable crashes immediately

I work with python 2.7 and I have a python script that ssh to remote servers and it works fine using python command from cmd but when I convert this script to executable file using py2exe or cx_freeze or Pyinstaller and try to run it, the window open and close immediately like if the program crashes. I tried another simple scripts like print function or some math function the executable files work fine so any one could help what would be the reason?
Thanks
Here is my code:
import sys
import paramiko
import getpass
def print_menu():
print 30 * "-", "MENU", 30 * "-"
print "1. LAB1"
print "2. LAB2"
print "3. LAB3"
print "4. Exit"
print 67 * "-"
def ssh_command(ssh):
while True:
command = raw_input("Enter command or q :")
ssh.invoke_shell()
stdin, stdout, stderr = ssh.exec_command(command)
stdout = stdout.readlines()
if command == "q":
break
for line in stdout:
if "Size" in line:
print "found the string"
break`enter code here`
else:
print "There was no output for this command"
def ssh_connect(host, user, password):
try:
ssh = paramiko.SSHClient()
print('Connecting...')
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=host, username=user, password=password)
ssh_command(ssh)
except Exception as e:
print('Connection Failed')
print(e)
def ssh_close():
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.close()
def credentials(host):
user = raw_input("Username:")
password = getpass.getpass("password for " + user + ":")
ssh_connect(host, user, password)
loop = True
while loop:
print_menu()
choice = input("Enter your choice [1-3]: ")
if choice == 1:
credentials('x.x.x.x')
elif choice == 2:
credentials('x.x.x.x')
elif choice == 3:
credentials('x.x.x.x')
elif choice == 4:
loop = False
print "Closing SSH connection"
print
ssh_close()
else:
raw_input("Wrong option selection. Enter any key to try again..")
You can check the error by running the exe file in command prompt.
This will give you an upper hand.
Especially in cx_freeze you have to mention the dependencies.
I think you are facing some dependency problem.
When you specifiy --debug=all after your pyinstall command when packaging, you will see specific errors when starting your applicataion in the dist folder.
Read here https://pyinstaller.readthedocs.io/en/stable/when-things-go-wrong.html to get more information on debugging specific errors and how to fix them.
you can use the pyinstaller with -F argument to fully package the python interpreter then open windows cmd and run it
pyinstaller -F <your_script>.py
Worry not, my friend! Just add a window.mainloop() call at the end of your program. Then, everything should work properly. I was stumped by the same problem got revelation from your words:
I tried another simple scripts like print function or some math function the executable files work fine
So, I compared both programs side by side and received my answer.
Running pyinstaller with the F flag should solve the problem of immediate close after startup.

Python program can't open txt file

I'm new to python and i'm trying to make a password manager.
the problem is that my program works fine when i run it through IDLE or Pycharm
but it stops running when i run it directly from windows when it reaches the line where I import the file where i store the password.
import time
user = raw_input("Username: ")
pw = raw_input("Password: ")
if user == "PrOoOg" and pw == "aka443":
def add_acc_func(acc, user, pw):
database.write("\nAccount: ")
database.write(acc)
database.write(" Username: ")
database.write(user)
database.write(" Password: ")
database.write(pw)
database.close()
def print_database_func():
for lines in database.readlines():
print lines.strip('\n')
database.close()
user_input = raw_input('Press "A" to add a new account\nPress "M" to modify and existing account\n'
'Press "D" to delete and existing account\nPress "S" to show all accounts and passwords\n')
user_choice = user_input.lower()
if user_choice == "a":
database = open("source.txt", "a") #Everything worked fine when i deleted this line
acc_to_add = raw_input("Write the name of the site or service: ").lower()
acc_to_add_user = raw_input("Write the username or email you want to set for that account: ")
acc_to_add_pw = raw_input("Write the password you want to set to that account: ")
add_acc_func(acc_to_add, acc_to_add_user, acc_to_add_pw)
print "Account added"
if user_choice == "s":
database = open("source.txt", "r") #Everything worked fine when i deleted this line
print_database_func()
raw_input("Press Enter to quit")
else:
print ("Wrong username or password")
time.sleep(3)
I tried to delete the lines where I import the text file and it worked.
i don't know why the code can't open the file when opened from windows and can open it when opened from IDLE or Pycharm
"it's just crashes when i run it from windows (rightclick ==> open with ==> python.exe)"
When you do this the working directory is C:\Windows\system32. Most likely you don't have write permissions to this directory. When running the script using the other methods the working directory is most likely the one containing the script. You need to change to a directory which you have write permissions for.
Here is an example to use the current user's Documents folder:
import os
dir = os.path.expanduser('~/Documents')
os.chdir(dir)

Program for Backup - Python

Im trying to execute the following code in Python 2.7 on Windows7. The purpose of the code is to take back up from the specified folder to a specified folder as per the naming pattern given.
However, Im not able to get it work. The output has always been 'Backup Failed'.
Please advise on how I get resolve this to get the code working.
Thanks.
Code :
backup_ver1.py
import os
import time
import sys
sys.path.append('C:\Python27\GnuWin32\bin')
source = 'C:\New'
target_dir = 'E:\Backup'
target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.zip'
zip_command = "zip -qr {0} {1}".format(target,''.join(source))
print('This is a program for backing up files')
print(zip_command)
if os.system(zip_command)==0:
print('Successful backup to', target)
else:
print('Backup FAILED')
See if escaping the \'s helps :-
source = 'C:\\New'
target_dir = 'E:\\Backup'

Windows error 5: Access is denied when trying delete a directory in windows

i am trying to delete a directory but when i run the code it gives windows error 5: access is denied. here is my code: in the Release folder, there is a folder called OD.
if os.path.exists(os.path.join(get_path_for_output,'Release')):
shutil.rmtree(os.path.join(get_path_for_output,'Release'))
the error is like:
WindowsError: [Error 5] Access is denied: 'C:\\Users\\marahama\\Desktop\\Abdur_Release\\Release\\OD\\automations\\GEM\\FMS_adapter.py'
This was due to the file permissions issue.
You need to have the permissions to perform that task on that file.
To get the permissions associated with a file, useos.stat(fileName)
You can explicitly check the write permission for that file using os.access(fileName, os.W_OK)
Then, to change the permission, os.chmod(fileName,permissionNumeric).
Ex: os.chmod(fileName, '0777')
To change the permission for the current file that is being executed,
use os.chmod(__file__, '0777')
I use pydev. And my solution is:
Stop Eclipse.
Start Eclipse with option Run as administrator
takeown /F C:\<dir> /R /A
icacls C:\<dir> /grant administrators:F /t
Give ownership to administrators and give full control to administrators, if your user is an administrator.
in order to change files located in "C:" you must have admin privileges,
you can either get them before starting the script or while doing so, for instance:
#!python
# coding: utf-8
import sys
import ctypes
def run_as_admin(argv=None, debug=False):
shell32 = ctypes.windll.shell32
if argv is None and shell32.IsUserAnAdmin():
return True
if argv is None:
argv = sys.argv
if hasattr(sys, '_MEIPASS'):
# Support pyinstaller wrapped program.
arguments = map(unicode, argv[1:])
else:
arguments = map(unicode, argv)
argument_line = u' '.join(arguments)
executable = unicode(sys.executable)
if debug:
print 'Command line: ', executable, argument_line
ret = shell32.ShellExecuteW(None, u"runas", executable, argument_line, None, 1)
if int(ret) <= 32:
return False
return None
if __name__ == '__main__':
ret = run_as_admin()
if ret is True:
print 'I have admin privilege.'
raw_input('Press ENTER to exit.')
elif ret is None:
print 'I am elevating to admin privilege.'
raw_input('Press ENTER to exit.')
else:
print 'Error(ret=%d): cannot elevate privilege.' % (ret, )
code taken from: How to run python script with elevated privilege on windows
script by: Gary Lee