Python file not found error when the file clearly exists - python

I have been working on a project that takes a MySQL dump and restores a database with the information that a user provides. I keep getting a file can not be found error then my custom error for debugging stating that. OS command has failed.
try:
username = self.username.get()
password = self.password.get()
database = self.database.get()
file = self.filename
print str(username)
print str(file)
test = os.system("mysql -u" + username + " -p" + password + " " + database + " <" + file)
if (test != 0):
print "OS COMMAND FAILED"
else:
print "pass"
print test
except:
print "fail"
print "Unexpected error:", sys.exc_info()[0]
raise
I will also continue to do research just in case I find the solution. I have been looking at the os.system command but the problem goes away if I specify the file name right in the command instead of retrieving it from a variable.
All the variables are pulled from entry boxes. There is no way for a user to type the file name incorectly as the program populates the filename based on a openfiledialog box and does not allow for the user to edit that box.
Error text:
C:/Documents and Settings/XPMUser/Desktop/src/database.sql
root
The system cannot find the file specified.
OS COMMAND FAILED
1

If there is a space in the filename, that will cause the kind of problem you describe. The shell will parse the space as being a delimiter. You may want to do something like
import pipes
...
database + " < " + pipes.quote(filename)
Better yet, use the subprocess module
test = subprocess.call(['mysql', '-u', username, '-p', password, database],
stdin=open(file))

Related

subprocess.call returns 0 but command did not execute successfully

I have a rather odd case that I can't seem to debug or reliably replicate.
When I run the following code for a directory with many files (~1000), there will occasionally be a few files that fail to move to the destination directory. Yet, when I check the logs, I will see that those files that failed to move still had a return code of 0, as the log files would log that they did move.
Initially I thought that it might have to do with the use of threading so that was removed entirely from the code but this still occurs. Does anyone know why this is happening?
def move(origin,dest,filename):
command = "mv " + os.path.join(origin,filename) + " " + dest
rc = subprocess.call(command,shell=True)
return rc
for f in files:
# do stuff
rc = move(origin,dest,filename)
if rc==0:
logging.debug('%s moved from %s to %s', f, origin, dest)

process run by pexpect.run() method terminates abruptly

When i run below code i see the process terminates even before completion.
I validated command by running it manually command just works file.
cmssso-util produces output which are about 1200 lines.Can this be a buffer issue.
I validated script by assigning 'ls -ltr' to variable command works fine.
Referred Documentation from below link:
https://pexpect.readthedocs.io/en/stable/_modules/pexpect/run.html
I tried prefixing command by 'bash -c' which did not fix this issue.
I tried to find out how pexpect determines to terminate a process , still could not get any clear documentation.
Please help me.
import pexpect
command = "cmsso-util domain-repoint -m execute --src-emb-admin " + 'sourceVcAdmin' + " --replication-partner-fqdn " + 'destVc' + " --replication-partner-admin " + 'destVcAdmin' + " --dest-domain-name " + 'destDomain'
print("Running command : " + command)
(command_output, exitstatus) = pexpect.run(command ,withexitstatus=1, events={'Enter Source embedded vCenter Server Admin Password :' : '\r\n','Enter Replication partner Platform Services Controller Admin Password :' : '\r\n','All Repoint configuration settings are correct; proceed?(.*)' : 'Y\r\n'})
print("----Command output------------")
print(command_output)
print("-----------------------------")
assert exitstatus is 0 , "Execution Failed"
print("Successfully Completed Embedded Cross Domain Re-pointing ")
I could resolve this issue by using the following code:
import pexpect
try :
command = "cmsso-util domain-repoint -m execute --src-emb-admin " + 'sourceVcAdmin' + " --replication-partner-fqdn " + 'destVc' + " --replication-partner-admin " + 'destVcAdmin' + " --dest-domain-name " + 'destDomain'
print("Running command : " + command)
child = pexpect.spawn(command, timeout=3000,maxread=12000)
child.expect (['Enter Source embedded vCenter Server Admin Password :'],timeout=40000)
child.sendline(<password>)
child.expect (['Enter Replication partner Platform Services Controller Admin Password :'],timeout=40000)
child.sendline(<password>)
child.expect (['All Repoint configuration settings are correct; proceed?(.*)'],timeout=40000)
child.sendline('Y')
child.expect(pexpect.EOF)
print(child.before)
assert(child.status == 0 , "Operation Failed!", "Successfully Completed Embedded Cross Domain Re-pointing")
except:
print("Exception was thrown")
print("debug information:")
print(str(child))
child.close()
exit(1)
This is done by increasing default child = pexpect.spawn(command, timeout=600,maxread=8000)value and maxread parameters

Ethical hacking script not working - no error message

I've been taking an Ethical Hacking course. Part of the course is creating a Python script that finds the password for a locked zip file, from a password list text file (hope that makes sense!) - basically iterates through a text file trying each password. The script doesn't work, doesn't error out, and the instructor says "well, it works for me" - not useful. Here's the script:
import optparse
import zipfile
from threading import Thread
def extract_zip(zfile, password):
try:
zfile.extractall(pwd=password)
print("[+] Password Found: " + password + '\n')
except:
pass
def main():
parser = optparse.OptionParser("usage %prog "+\
"-f <zipfile> -d <dictionary>")
parser.add_option('-f', dest='zname', type='string',\
help='specify zip file')
parser.add_option('-d', dest='dname', type='string',\
help='specify dictionary file')
(options, arg) = parser.parse_args()
if (options.zname == None) | (options.dname == None):
print(parser.usage)
exit(0)
else:
zname = options.zname
dname = options.dname
zFile = zipfile.ZipFile(zname)
passFile = open(dname)
for line in passFile.readlines():
password = line.strip('\n')
t = Thread(target=extract_zip, args=(zFile, password))
t.start()
if __name__ == '__main__':
main()
The other two files are a text file with a list of passwords, and a password protected zip file where one of the passwords from the text file will unlock it.
Within the course there's a thread mentioning that optparse is depracated, and argparse is its replacement - but even rewriting the script with that doesn't work.
For want of closing out this part of the course I'm looking for help in why this doesn't work.
Thanks in advance for any help on this.
Per my comment above - I added the code below just below the "try" statement:
password = bytes(password.encode('utf-8'))
...then changed
print('[+] Password Found: ' + password + '\n')
to
print("[+] Password Found: " + (password.decode("utf-8")) + '\n')
Now I get the password printed to the console, and the zip file is unzipped. Here's the final, working code.
import optparse
import zipfile
from threading import Thread
def extract_zip(zfile, password):
try:
password = bytes(password.encode('utf-8'))
zfile.extractall(pwd=password)
print("[+] Password Found: " + (password.decode("utf-8")) + '\n')
except:
pass
def main():
parser = optparse.OptionParser("usage %prog " + '-f <zipfile> -d <dictionary>')
parser.add_option('-f', dest='zname', type='string', help='specify zip file')
parser.add_option('-d', dest='dname', type='string', help='specify dictionary file')
(options, args) = parser.parse_args()
if (options.zname is None) | (options.dname is None):
print(parser.usage)
exit(0)
else:
zname = options.zname
dname = options.dname
zFile = zipfile.ZipFile(zname)
passFile = open(dname)
for line in passFile.readlines():
password = line.strip('\n')
t = Thread(target=extract_zip, args=(zFile, password))
t.start()
if __name__ == '__main__':
main()
The way I found this was by changing the 'except' statement to print exceptions to the console:
except Exception as e: print(e)
From there I had a couple of issues to solve, but at least I had errors to work with. Once the password was being successfully logged to the console I change the exeception statement back to "pass" - don't need to see the passwords that failed!
I hope this helps someone else hitting the same issues I had.
I run your code using python3 it excuted without problem i did this long ago
it is a book called violent something
the password.txt should contain this line
victim: HX9LLTdc/jiDE: 503:100:Iama Victim:/home/victim:/bin/sh
root: DFNFxgW7C05fo: 504:100: Markus Hess:/root:/bin/bash
and the command should look like
python stack.py -f evil.zip -d passwords.txt

Python script to catch failed commands or warnings messages

I have a little script that telnets into a network switch and executes commands. It works fine but I need it stop and show an error message if any of the commands fail or network give a waning or something.
Here is the code:
import sys
import telnetlib
HOST = "10.10.10.1"
user = "Test"
password = "TestPW"
tn = telnetlib.Telnet(HOST)
tn.read_until("username: ")
tn.write(user + "\n")
tn.read_until("password: ")
tn.write(password + "\n")
n, match, previous_text = tn.expect([r'Login incorrect', r'\$'], 1)
if n == 0:
print "Invalid Credentials"
tn.close()
else:
tn.write("Term len 0\n")
#Reads data from commands.txt file and executes it line by line
with open("commands.txt") as commands:
singlecommand = commands.read()
tn.write(singlecommand)
print singlecommand
#Need exception/error checking to catch fail commands or warnings.
tn.write("exit\n")
tn.write("y\n")
print tn.read_all()
tn.close()
I want the script to stop executing more commands after a fail command or a warning from CLI that something maybe wrong. It already has the print function so it should display the error message and command that failed.
Here is a example of a failed command:
% Invalid input detected at '^' marker.
Here is an example warning message:
%Warning:
You can use Try/Except statements.
They're related to the Errors and Exceptions part of the Python docs.
Example:
try:
wrong_sum = "a" + 2
except ValueError:
print "You got a Value Error"
else:
break
you can extract the message based on key word appeared in failed command, then raise the exception.
for example:
try:
if '%Warning' == message[:8]:
raise Exception('Test')
except Exception:
print message

Python WindowsError 2, Discover Which File is Missing

I have a python script which takes a Java jar file from my Continuous Integration Server and starts it after each build. I am getting a strange error when I attempt to run the Jar file though, "[Error 2] The system cannot find the file specified". Now this would make sense if the file I am looking to utilize was missing or I had the wrong path, but os.path.exists() returns true on the file just before the WindowsError occurs. So, I am wondering which file can't be found... perhaps some part of my startup command is being interpreted as a file argument (which would understandably be missing)? So my question is, how do I discover which file Windows is failing to find in the case of error 2?
To ensure that my issue is not related to some other error in my script, here are the relevant bits:
serverConstants.py:
import os
__author__ = 'Brendon Dugan'
serverJarName = "eloquence-server.jar"
backupJarName = "eloquence-server-backup.jar"
deployedJarName = "eloquence-server-jar-with-dependencies.jar"
serverLocation = os.path.join("C:" + os.path.sep, "eloquence-alpha")
serverFlag = "-isServer=true"
javaVariant = "javaw"
javaExecutable = os.path.join(os.environ["JAVA_HOME"], "bin", javaVariant)
serverStartCommand = ("start \"Eloquence Server\" /d" +
serverLocation + " \"" + javaExecutable + "\" -jar " +
os.path.join(serverLocation, serverJarName) + " " + serverFlag)
startServer.py:
import os
import subprocess
import traceback
import psutil
import serverConstants
def startServer(server):
if os.path.exists(server):
print "Server seems to exist"
os.chdir(serverConstants.serverLocation)
kwargs = {}
DETACHED_PROCESS = 0x00000008
CREATE_NEW_PROCESS_GROUP = 0x00000200
kwargs.update(creationflags=DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP)
try:
print serverConstants.serverStartCommand
print os.getcwd()
eloquenceProcess = subprocess.Popen(serverConstants.serverStartCommand, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **kwargs)
print eloquenceProcess.pid
print "Server started successfully"
return 0
except WindowsError, error:
print "A Windows Error Has Occurred"
print error.strerror
print error
print "An error occurred while starting the server"
return 1
if __name__ == "__main__":
print "Preparing to start server"
server = os.path.join(serverConstants.serverLocation, serverConstants.serverJarName)
print server
if startServer(server) == 0:
exit(0)
exit(1)
Full Program Output:
Preparing to start server
C:\eloquence-alpha\eloquence-server.jar
Server seems to exist
start "Eloquence Server" /dC:\eloquence-alpha "C:\Program Files\Java\jdk1.7.0_11\bin\javaw" -jar C:\eloquence-alpha\eloquence-server.jar -isServer=true
C:\eloquence-alpha
A Windows Error Has Occurred
The system cannot find the file specified
[Error 2] The system cannot find the file specified
An error occurred while starting the server
Process finished with exit code 1

Categories