I could really use some help on this python script that is to call and run existing PowerShell scripts that are in a specific folder. From want I can see on from many of the articles on this site I've read my code seems correct. First a little background I'm trying to write a python script that will take Powershell scripts in a targeted folder and create a menu that can be selected 1, 2, 3 etc. The use makes the selection and that corresponding Powershell script is run. Now the issue is when I place the code on a server and run it with some test PowerShell scripts I get the following error: The term "Filename.ps1" is not recognized as the name of a cmdlet, function, script file, or operable program. And of course the Powershell scripts won't run. A copy of my code is below. Can anyone see any issue.
## ENOC Text Menu Dynamic test
##version 1
## Created By MTDL Marcus Dixon
## Code produce in Notpad++ For python v3.4.4
import os, subprocess, time, pathlib, logging, fnmatch,
re, sys, io
## Directory Enumerator
fileFolderLocationFilter = fnmatch.filter(os.listdir
('C:\\Users\\MTDl\\Documents\\Automation_Scripts\
\ENScripts\\'), "*.ps1")
selectedFile=""
## Menu defined setting veriables
def ENOC_menu():
files = fileFolderLocationFilter
counter = 1
print (20 * "=" , "Enoc Quick Menu" , 20 * "=")
enumFiles = list(enumerate(files))
for counter, value in enumFiles:
str = repr(counter) + ") " + repr(value);
print(str)
str = repr(counter+1) + ") Exit";
print(str)
print (57 * "_")
str = "Enter your choice [1 - " + repr((counter+1))
+ "]:"
choice = int(input("Please Enter a Selection: "))
selectedFiles = enumFiles[choice]
return(selectedFiles[1])
if choice > counter :
choice = -1
elif choice != counter :
print("Please selecte a valid choice")
else:
selectedFiles = enumFiles[choice]
print(selectedFiles[1])
##selectedFiles = selectedFiles[1]
return choice
##initiating loop
loop = True
while loop:
try:
choice = ENOC_menu()
scriptToRun = choice
powershell = 'C:\\WINDOWS\\system32\
\WindowsPowerShell\\v1.0\\powershell.exe'
print ('\n' +'You selected '+ choice
+'\n')
subprocess.call(powershell + ' ' +
choice, shell=True)
except OSError as err:
logger.error(err) ##continue to work on
logging this renders but may be incorrect.
print ('OS error: {0}' .format(err))
except ValueError:
print ('Oops we had an issue try again')
else:
print ('---' + choice + '---' + '\n')
Related
First off I am not too familiar with python and still currently learning also its my first time ever posting here so sorry if I am mess up with some details.
I am running experiments, and need to run multiple replicates. The issue arises when I need to start a new set of replicates, the program moves the already run experiments into a new folder and is then suppose to start the new replicates. However, what happens only on the last experiment, the environment.cfg folder is not transferred and the program crashes.
from os import listdir,chdir
import subprocess
from random import randrange,sample
from shutil import copy,copytree,rmtree
from os import mkdir,remove
import csv
import time
import shutil
test = input("Is this a test? (y/n)")
if test == "y":
text = input("What are you testing?")
testdoc=open("Testing Documentation.txt","a")
testdoc.write(text)
elif test != "y" and test != "n":
print("Please type in y or n")
test = input("Is this a test? (y/n)")
expnum = int(input("Number of Experiments: "))
exptype = int(input("Which experiment do you want to run? (1/2)"))
repnum= int(input("How many replicates do you want?"))
print(f"You want {repnum} replicates, each replicate will contain {expnum} for a total of {repnum*expnum}")
confirm = input("Is this correct? (y/n)")
if confirm == "y":
for rep in range(repnum):
if exptype == 1:
for ex in range (expnum):
num= ex + 1
mkdir('experiment_'+str(num)) #create a directory named cdir
copy('./default_files/environment.cfg','./experiment_'+str(num)+'/environment.cfg') #copy one file from one place to another
#WSIZE
env_file = open('./experiment_'+str(num)+'/environment.cfg','r')
env_file_content = []
for i in env_file:
env_file_content.append(i.split(' '))
#env_file_content = [['a','b'],['c','d']]
#access first line: env_file_content[0] ; note that index in python start from 0
#access first element in second line: env_file_content[1][0] ; note that index in python start from 0
n = num #number of resources
var0 = '100' #resource inflow
var1 = '0.01' #resource outflow
var3 = '1' # The minimum amount of resource required
reactiontype = ['not','nand','and','orn','or','andn','nor','xor','equ']
reward = ["1.0","1.0","2.0","2.0","4.0","4.0","8.0","8.0","16.0"]
#n = sample(range(10),1)[0]
out = open('./experiment_'+str(num)+'/environment.cfg','w')
for i in range(n):
out.write('RESOURCE res'+str(i)+':inflow='+var0+':outflow='+var1+'\n')
sc=0
for i in range(n):
out.write('REACTION reaction'+str(i)+' '+reactiontype[sc]+' process:resource=res'+str(i)+':value='+reward[sc]+':min='+var3+ '\n')
sc+=1
if sc==len(reactiontype):
sc = 0
out.close()
##RUN Avida from python
copy('./experiment_' + str(num) + '/environment.cfg', './')
print("starting experiment_" + str(num))
proc = subprocess.Popen(['./avida'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# Wait for the subprocess to finish
output, error = proc.communicate()
# Close the subprocess
proc.terminate()
shutil.move('./data','./experiment_' +str(num))
#copytree('./data', './experiment_' + str(num) + '/data')
#rmtree('./data')
remove('./environment.cfg')
replicatenum = rep + 1
mkdir('replicate_'+str(replicatenum)) #create a directory named replicate_
for repl in range(expnum):
numb = repl + 1
source = './experiment_'+str(numb)
dest = './replicate_' + str(replicatenum) + '/experiment_' + str(numb)
shutil.move(source, dest)
I tried renaming the folder, however that also failed. The issue seems only to arise when the program is running as taking the same code after the program has crashed, will cause no problems.
I am receiving the following error when trying to use pbcopy to add the output to the clipboard. I tried different variations of the command and still no luck.
Does anyone have any ideas where I may have failed?
Error Screenshot:
#!/usr/bin/env python3
# This script creates a secure password using all available key combinations.
import secrets , string, os
def prRed(skk): print("\033[91m {}\033[00m" .format(skk))
chars = string.ascii_letters+string.punctuation+string.digits # Cleaner way of assigning variable
print()
pwd_length = int(input('Enter the length of the desired password: '))
print()
print('[+] ' + 'Your secure password is:')
print()
for n in range(1):
output = ""
for i in range(pwd_length):
next_index = secrets.SystemRandom().randrange(len(chars))
output = output + chars[next_index]
prRed(os.system("echo '%s' | pbcopy" % output))
print()
I am using a simple python script to search and play songs on my laptop. The code goes as follows :-
import os
d_name = raw_input("enter drive name:-")
choice = raw_input("song or video(s/v):-")
if(choice == 's'):
s_name = raw_input("enter song name:- ")
flag = 1
elif(choice=='v'):
s_name = raw_input("enter video name:-")
flag = 2
if(flag == 1):
f_s_name = "start "+d_name+":/"+s_name+".mp3"
elif(flag == 2):
f_s_name = "start "+d_name+":/"+s_name+".mp4"
dir_list = os.listdir("d_name:/")
i=0
while(1):
if(not(os.system(f_s_name))):
break
else:
if(flag == 1):
f_s_name = "start "+d_name+":/"+dir_list[i]+"/"+s_name+".mp3"
elif(flag == 2):
f_s_name = "start "+d_name+":/"+dir_list[i]+"/"+s_name+".mp4"
i = i+1
the above program works fine but when one of the calls to the function os.system() fails until the required condition matches it pops out a dialog box claiming that the song is not there until it is found. How can i prevent popping up of that dialog box?
You'd use os.path.exists to test whether the file you're about to start actually exists; if it is not found, do not try to start that file:
import os
....
filename = '{}:/{}/{}.mp3'.format(d_name, dir_list[i], s_name)
if os.path.exists(filename):
system('start ' + filename)
else:
print "File {} was not found".format(filename)
So I wrote this code
spec = raw_input("Enter the specimen number: ")
naorimp = raw_input("Native or Implant (N/I)? ")
trial = raw_input("Trial number: ")
typana = raw_input("What do you want to analyze (contact area[CA]/contact pressure[CP])? ")
try :
if typana.lower() == "cp" :
naorimp = naorimp.upper()
TSfilnm = 'pressure'+spec+naorimp.upper()+trial+'.txt'
else :
naorimp = naorimp.upper()
TSfilnm = 'area'+spec+naorimp+trial+'.txt'
TSfile = open(TSfilnm, 'r')
myofilnm = 'accelerometer'+spec+naorim.upper()+trial+'.txt'
print myofilnm
myofile = open(myofilnm, 'r')
except :
print "File could not be found."
print "Please re-run the program."
exit()
print "OK"
I want to open a file based on user's input and several parameters (specimen no., native or implant, trial no., and type of analysis.) The file is already in the same folder as the python file code. But when I run the program I always end up with except statements (File could not be found. Please re-run the program). I have double-checked the real file name and the string inside the TSfilnm variable, and they are the same. However, the TSfile could not be executed.
P.S. The file name in my folder is: pressure3N1.txt, area3N1.txt, accelerometer3N1.txt
You are missing a p in the variable name in this line
myofilnm = 'accelerometer'+spec+naorim.upper()+trial+'.txt'
should be
myofilnm = 'accelerometer'+spec+naorimp.upper()+trial+'.txt'
Also don't use 'except' alone during development, it will only hide errors like in this case. It's better to do something like.
import sys
try:
#Your_code_here
except:
print sys.exc_info()[1]
#Any other code you wanna run
So I've designed a program that runs on a computer, looks for particular aspects of files that have been plaguing us, and deletes the files if a flag is passed. Unfortunately the program seems to be almost-randomly shutting down/crashing. I say almost-randomly, because the program always exits after it deletes a file, though it will commonly stay up after a success.
I've run a parallel Python program that counts upwards in the same intervals, but does nothing else. This program does not crash/exit, and stays open.
Is there perhaps a R/W access issue? I am running the program as administrator, so I'm not sure why that would be the case.
Here's the code:
import glob
import os
import time
import stat
#logging
import logging
logging.basicConfig(filename='disabledBots.log')
import datetime
runTimes = 0
currentPhp = 0
output = 0
output2 = 0
while runTimes >= 0:
#Cycles through .php files
openedProg = glob.glob('*.php')
openedProg = openedProg[currentPhp:currentPhp+1]
progInput = ''.join(openedProg)
if progInput != '':
theBot = open(progInput,'r')
#Singles out "$output" on this particular line and closes the process
readLines = theBot.readlines()
wholeLine = (readLines[-4])
output = wholeLine[4:11]
#Singles out "set_time_limit(0)"
wholeLine2 = (readLines[0])
output2 = wholeLine2[6:23]
theBot.close()
if progInput == '':
currentPhp = -1
#Kills the program if it matches the code
currentTime = datetime.datetime.now()
if output == '$output':
os.chmod(progInput, stat.S_IWRITE)
os.remove(progInput)
logging.warning(str(currentTime) +' ' + progInput + ' has been deleted. Please search for a faux httpd.exe process and kill it.')
currentPhp = 0
if output2 == 'set_time_limit(0)':
os.chmod(progInput, stat.S_IWRITE)
os.remove(progInput)
logging.warning(str(currentTime) +' ' + progInput + ' has been deleted. Please search for a faux httpd.exe process and kill it.')
currentPhp = 0
else:
currentPhp = currentPhp + 1
time.sleep(30)
#Prints the number of cycles
runTimes = runTimes + 1
logging.warning((str(currentTime) + ' botKiller2.0 has scanned '+ str(runTimes) + ' times.'))
print('botKiller3.0 has scanned ' + str(runTimes) + ' times.')
Firstly, it'll be hell of a lot easier to work out what's going on if you base your code around something like this...
for fname in glob.glob('*.php'):
with open(fname) as fin:
lines = fin.readlines()
if '$output' in lines[-4] or 'set_time_limit(0)' in lines[0]:
try:
os.remove(fname)
except IOError as e:
print "Couldn't remove:", fname
And err, that's not actually a secondly at the moment, your existing code is just too tricky to follow fullstop, let alone all the bits that could cause a strange error that we don't know yet!
if os.path.exists(progInput):
os.chmod(progInput, stat.S_IWRITE)
os.remove(progInput)
ALSO:
You never reset the output or output2 variables in the loop?
is this on purpose?