Python program can't open txt file - python-2.7

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)

Related

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.

.zip file password not found (present in .txt file)

This code is verbatim from a book titled 'Violent Python'. It is meant to be a simple script that iterates through a .txt file and tries each entry as the password to a locked .zip file.
The script runs and no errors are thrown but no output is given until I
add a count variable that proves each entry is being checked. Although the correct password is in the file the 'if guess:' statement is never run.
Any help will be greatly appreciated!
import zipfile
def extractFile(zfile,password):
try:
zFile.extractall(pwd=password)
return password
except:
return
def main():
count = 0 #added for debugging
zFile = zipfile.ZipFile('secure.zip')
passFile = open('dictionary.txt')
for line in passFile.readlines():
count = count + 1 #added for debugging
password = line.strip('\n')
guess = extractFile(zFile, password)
print count #added for debugging
if guess:
print "[+] Password = " + password + "\n"
exit(0)
if __name__=='__main__':
main()

Paramiko SSH - Multiple Authentication Credentials with Python

I have the following code:
import paramiko
import time
import re
import sys
import random
import fileinput
ip_address = raw_input("Enter a valid WAP IP: ")
#Open SSHv2 connection to devices
def open_ssh_conn(ip):
try:
#Logging into device
session = paramiko.SSHClient()
#AutoAddPolicy
session.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#Passing the necessary
session.connect(ip, username = 'myUsername', password = 'myPassword')
#Start an interactive shell session on the switch
connection = session.invoke_shell()
#Commands
connection.send("enable\n")
time.sleep(1)
connection.send("show version\n")
time.sleep(1)
#Checking command output for IOS syntax errors
output = connection.recv(65535)
#Checking command output for IOS Syntax errors
if re.search(r"% Invalid input detected at", output):
print "* There was at least one IOS syntax error on device %s" % ip
else:
print "\nDONE for device %s" % ip
#Test for reading command output
print output + "\n"
#Closing the connection
session.close()
except paramiko.AuthenticationException:
print "* Invalid username or password. \n* Please check
the username/password file or the device configuration!"
print "* Closing program...\n"
#Calling the SSH function
open_ssh_conn(ip_address)
How can I test multiple credential without getting kick out of the program when an exception is caught?
for example, try this new credentials:
session.connect(ip, username = 'myNewUsername', password = 'myNewPassword')
I figured it out! I created a nested list with the credentials:
list = [['username1', 'password1'], ['username2', 'password2'], \
['username3', 'password3']]
Then, created a for loop and put my code inside:
for elem in list:
my code...
# this is the connect line:
session.connect(ip, username = elem[0], password = elem[1])
That did it!!!!

Indent or sequencing problems with python

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.

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