Hi I'm currently working on a python script that generates shell scripts to install agents on a linux server. The .sh files that the python scripts output keeps ending up with a "syntax error: unexpected end of file" but when i manually type in the exact output in vi, there seems to be no issue. Is there any issue with how I'm writing it in python or is it feasible to do it through python?
python script
import csv
def menu():
print("type of scripts")
print("1. Install + Generation")
print("2. Unregister + Reregister")
print("3. Unregister + Uninstall")
#Converts numeral choice into type for script naming
def choicename(choice):
choice = int(choice)
if choice==1:
return "install"
elif choice == 2 :
return "rereg"
else:
return "uninstall"
#Generates the install agent scripts
def installScript(agentname,agentfile,mgrfile,prigw,secgw,ostype):
#Generates the script for Linux agents (.sh)
if ostype=="Linux":
agentpath = 'agent="/opt/test/ragent/bin/racli"'
installerpath = '\ninstaller="/opt/test/installer/bin/racli"'
checkAgent = '\nif [ ! -e "$agent" ]; then' +"\n" + "./" + agentfile + " -n -d /opt/test" + '\nelse\necho "Agent is already installed"\nfi'
checkInstaller = '\nif [ ! -e "$installer" ]; then' + "\n" +"./" + mgrfile + " -n -d /opt/test"+ '\nelse\necho "Manager is already installed"\nfi'
regAgent = "\n/opt/test/ragent/bin/cli registration advanced-register registration-type=Primary ragent-name="+ agentname+ " gw-ip="+ prigw+ " gw-port=443 manual-settings-activation=Automatic monitor-networkchannels=Both password=$1"
if secgw!="":
regAgent+="\n/opt/test/ragent/bin/cli registration advanced-register registration-type=Secondary ragent-name="+ agentname+ " gw-ip="+ secgw+ " gw-port=443 manual-settings-activation=Automatic monitor-networkchannels=Both password=$1"
startAgent="\n/opt/test/ragent/bin/rainit start"
regInstaller="\n/opt/test/installer/bin/cliinstaller registration register-use-existing package-folder-path=\".\" package-folder-size=1024"
startInstaller="\n/opt/test/installer/bin/rainstallerinit start"
sf = open(agentname+ "_install.sh","w")
sf.write(agentpath+installerpath+checkAgent+checkInstaller+regAgent+startAgent+regInstaller+startInstaller)
sf.close()
def scriptSplit(option,agentname,agentfile,mgrfile,prigw,secgw,ostype):
if option=="install":
installScript(agentname,agentfile,mgrfile,prigw,secgw,ostype)
elif option =="rereg":
reregScript(agentname,agentfile,mgrfile,prigw,secgw,ostype)
elif option =="uninstall":
uninstallScript()
#Collects user input for function type
def main():
menu()
choice = input("Please choose the type of script you would like to generate: ")
option = choicename(choice)
filename = input("Please enter the name of the csv file: ")
with open(filename) as csv_file:
creader = csv.reader(csv_file, delimiter=",")
line_count = 0
for row in creader:
if line_count!=0:
agentname=row[0]
agentfile=row[1]
mgrfile=row[2]
prigw=row[3]
secgw=row[4]
installtype=row[5]
scriptSplit(option,agentname,agentfile,mgrfile,prigw,secgw,installtype)
line_count += 1
#### END OF FUNCTIONS ###
main()
output from above script
agent="/opt/test/ragent/bin/racli"
installer="/opt/test/installer/bin/racli"
if [ ! -e "$agent" ]; then
./agent1.bsx -n -d /opt/test
else
echo "Agent is already installed"
fi
if [ ! -e "$installer" ]; then
./installer1.bsx -n -d /opt/test
else
echo "Manager is already installed"
fi
/opt/test/ragent/bin/cli registration advanced-register registration-type=Primary ragent-name=agent1 gw-ip=10.255.0.80 gw-port=443 manual-settings-activation=Automatic monitor-networkchannels=Both password=$1
/opt/test/ragent/bin/cli registration advanced-register registration-type=Secondary ragent-name=agent1 gw-ip=10.255.0.81 gw-port=443 manual-settings-activation=Automatic monitor-networkchannels=Both password=$1
/opt/test/ragent/bin/rainit start
/opt/test/installer/bin/cliinstaller registration register-use-existing package-folder-path="." package-folder-size=1024
/opt/test/installer/bin/rainstallerinit start
csv file it reads from
Agent Name,Agent File,Installer File,Primary IP,Secondary IP,Type
agent1,agent1.bsx,installer1.bsx,10.255.0.80,10.255.0.81,Linux
agent2,agent2.bsx,installer2.bsx,10.255.0.81,,Linux
The newline convention is \r\n on windows. Bash interprets newline character as... newline character, and the \r is a normal character for bash.
Fix:
sf = open(agentname+ "_install.sh", "w", newline='\n')
Related
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')
I am attempting to get a Python script working that is designed to set Ubuntu shortkeys. It does not appear to be working in Ubuntu 16.10 and I am unsure why. In addition, I am finding it difficult to keep track of the quotation marks and their respective escapes needed for commands, strings, Bash etc.
The script is designed to be used in a way like the following:
./set_Ubuntu_shortkey.py \
--command="bash -c \"xvkbd -text \$(date \"+%Y-%m-%dT%H%MZ\" --utc) 2>/dev/null\"" \
--name="type_time_UTC" \
--keys="<Control><Shift>d"
This should ideally then set the Ubuntu shortkey such that it has the following characteristics:
name: type_time_UTC
command: bash -c "xvkbd -text $(date "+%Y-%m-%dT%H%MZ" --utc) 2>/dev/null"
key-bindings: Ctrl+Shift+D
#!/usr/bin/env python
"""
################################################################################
# #
# set_Ubuntu_shortkey #
# #
################################################################################
usage:
program [options]
options:
-h, --help display help message
--version display version and exit
--command=TEXT command
--keys=TEXT keys
--name=TEXT name
--debugpassive display commands without executing
"""
import docopt
import logging
import os
import subprocess
import sys
import time
def main(options):
command = options["--command"]
keys = options["--keys"]
name = options["--name"]
debug_passive = options["--debugpassive"]
if None in [command, keys, name]:
print("insufficient options specified")
exit()
print("\nset shortkey:" )
print("- name: " + name )
print("- command: " + command )
print("- keys: " + keys + "\n")
shortkeys_current = subprocess.check_output([
"gsettings",
"get",
"org.gnome.settings-daemon.plugins.media-keys",
"custom-keybindings"
]).decode("utf-8")
if shortkeys_current.strip() == "#as []":
shortkeys_current = "[]"
shortkeys_current = eval(shortkeys_current)
index_shortkey_new = len(shortkeys_current)
address_shortkey_new =\
"/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/" +\
"custom" + str(index_shortkey_new) + "/"
shortkeys_current.append(
address_shortkey_new
)
command_list_1 = [
"gsettings",
"set",
"org.gnome.settings-daemon.plugins.media-keys.custom-keybinding:" +\
address_shortkey_new,
"name",
name
]
command_list_2 = [
"gsettings",
"set",
"org.gnome.settings-daemon.plugins.media-keys.custom-keybinding:" +\
address_shortkey_new,
"command",
command
]
command_list_3 = [
"gsettings",
"set",
"org.gnome.settings-daemon.plugins.media-keys.custom-keybinding:" +\
address_shortkey_new,
"binding",
keys
]
if debug_passive:
print(" ".join(command_list_1))
print(" ".join(command_list_2))
print(" ".join(command_list_3))
else:
subprocess.Popen(command_list_1)
subprocess.Popen(command_list_2)
subprocess.Popen(command_list_3)
if __name__ == "__main__":
options = docopt.docopt(__doc__)
if options["--version"]:
print(version)
exit()
main(options)
so i want to run this python program but i am unsure how to run it, when i insert in the arguments it get a token error.
First i "import cw2" which is the file name in the terminal after typing python and then i type in the argument to run a individual task but i get and error. Heres the code, can you tell me how to run the individual parts.
Heres what i typed as the argument cw2 -u user_745409913574d4c6 -d doc_140228202800-6ef39a241f35301a9a42cd0ed21e5fb0 -t task_2, But that doesnt work. Heres the code below showing what the argument is.
def main(argv):
user_uuid = ''
doc_uuid = ''
task_id = 0
try:
opts, args = getopt.getopt(argv, "hu:d:t:", ["user_uuid=", "doc_uuid=", "task_id="])
except getopt.GetoptError:
print 'cw2 -u <user_uuid> -d <doc_uuid> -t <task_id>'
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print 'cw2.py -u <user_uuid> -d <doc_uuid> -t <task_id>'
sys.exit()
elif opt in ("-u", "--user_uuid"):
user_uuid = arg
elif opt in ("-d", "--doc_uuid"):
doc_uuid = arg
elif opt in ("-t", "--task_id"):
task_id = arg
if(int(task_id) == 1):
with open("../requirements.txt", 'r') as fin:
print("Requirments.txt file content")
print fin.read()
if(int(task_id) == 2):
if(doc_uuid == ''):
print(" No doc_uuid supplied")
else:
task_2(doc_uuid)
print("Histograms for per country beed saved in : static/results/countries_to_book_UUID.png")
print("Histograms for per continent beed saved in : static/results/continent_to_book_UUI.png")
elif(int(task_id) == 3):
task_3()
print("Histograms of browser usage has been seaved in 'static/results/simple_browser_usage.png' ")
print("Histograms of generalised browser usage has been seaved in 'static/results/general_browser_usage.png")
elif(int(task_id) == 4):
print("Data of 10 most active readers")
task_4(10)
elif(int(task_id) == 5):
if((user_uuid == '') | (doc_uuid == '')):
print("Provide user_uuid or/and doc_uuid")
# 938601f24509a9f1 , 110727005030-000000009cca70787e5fba1fda005c85
else:
task_5(user_uuid, doc_uuid)
if __name__ == "__main__":
main(sys.argv[1:])
Don't run it from the Python shell, this is set up to run as a normal program from your terminal.
cd <wherever this script is>
chmod a+x ./cw.py
./cw.py -u user_745409913574d4c6 -d doc_140228202800-6ef39a241f35301a9a42cd0ed21e5fb0 -t task_2
Also, the indentation is all wrong on the script in your question, but I assume that that's a copy-and-paste error.
please refer following code, which creates batch file for executing certain programs synchronously. but after execution of first file, the program stops and asks whether the batch to be continued. This is causing a delay for user input. Since i wish to run several files overnight, the program waits for user input. Could anyone help me with this error ?
import os
from subprocess import call
version = "0.1"
os.system('CLS')
print("////////////////////////////////////////////////")
print("// LS-DYNA Simulation Start Script, V" + version + " //")
print("////////////////////////////////////////////////\n")
input_flag = 0
while input_flag == 0:
solver_type_string = raw_input("Use single or double precision solver (s/d)?")
if solver_type_string == "s":
solver_type_string = "ls971_s_R5.1.1_winx64_p.exe"
print("Choosen Solver: " + solver_type_string + "\n")
input_flag = 1
elif solver_type_string == "d":
solver_type_string = "ls971_d_R5.1.1_winx64_p.exe"
print("Choosen Solver: " + solver_type_string + "\n")
input_flag = 1
else:
print("Invalid input!\n")
current_path = os.path.dirname(os.path.abspath(__file__))
solver_path = "C:\Programme\LSDyna-971.1\program\\" + solver_type_string
batch_file = open("sim_start.bat", "w")
batch_file.write("#echo off\n")
sim_counter = 0
for (path, dirs, files) in os.walk(current_path):
for sim_file in files:
if sim_file.endswith((".k", ".dyn")):
sim_counter = sim_counter + 1
sim_path = path
print("Found: \'" + sim_file + "\'")
batch_file.write("pushd " + sim_path + "\\\n")
batch_file.write(solver_path + " i=" + sim_path + "\\" + sim_file + "\n")
print "\nDone! Found ", sim_counter, " simulation files in total."
batch_file.close()
print "\nStarting LS-DYNA batch run...\n"
call(current_path + "\sim_start.bat")
The created file looks like
#echo off
pushd E:\Shah\CPW\t25_nw100_amp25_ptr35_matDC04\
C:\Programme\LSDyna-971.1\program\ls971_d_R5.1.1_winx64_p.exe i=E:\Shah\CPW\t25_nw100_amp25_ptr35_matDC04\t25_nw100_amp25_ptr35_matDC04.dyn
pushd E:\Shah\CPW\t25_nw100_amp30_ptr40_matDC04\
C:\Programme\LSDyna-971.1\program\ls971_d_R5.1.1_winx64_p.exe i=E:\Shah\CPW\t25_nw100_amp30_ptr40_matDC04\t25_nw100_amp30_ptr40_matDC04.dyn
pushd E:\Shah\CPW\t25_nw10_amp15_ptr25_matDC04\
C:\Programme\LSDyna-971.1\program\ls971_d_R5.1.1_winx64_p.exe i=E:\Shah\CPW\t25_nw10_amp15_ptr25_matDC04\t25_nw10_amp15_ptr25_matDC04.dyn
pushd E:\Shah\CPW\t25_nw10_amp20_ptr30_matDC04\
C:\Programme\LSDyna-971.1\program\ls971_d_R5.1.1_winx64_p.exe i=E:\Shah\CPW\t25_nw10_amp20_ptr30_matDC04\t25_nw10_amp20_ptr30_matDC04.dyn
pushd E:\Shah\CPW\t25_nw10_amp25_ptr35_matDC04\
C:\Programme\LSDyna-971.1\program\ls971_d_R5.1.1_winx64_p.exe i=E:\Shah\CPW\t25_nw10_amp25_ptr35_matDC04\t25_nw10_amp25_ptr35_matDC04.dyn
pushd E:\Shah\CPW\t25_nw10_amp30_ptr40_matDC04\
C:\Programme\LSDyna-971.1\program\ls971_d_R5.1.1_winx64_p.exe i=E:\Shah\CPW\t25_nw10_amp30_ptr40_matDC04\t25_nw10_amp30_ptr40_matDC04.dyn
pushd E:\Shah\CPW\t25_nw30_amp15_ptr25_matDc04\
C:\Programme\LSDyna-971.1\program\ls971_d_R5.1.1_winx64_p.exe i=E:\Shah\CPW\t25_nw30_amp15_ptr25_matDc04\t25_nw30_amp15_ptr25_matDc04.dyn
After some research, I can conclude that, when we press 'ctrl + c' during the batch run (i was pressing ctrl + c to check the execution time of ls dyna program ), the window of "whether you want to terminate the batch prohgram" appears and program waits for user input..
final="cacls " + "E:/" + "\"" + list1[2] + " " + list1[3] + "\"" + " /p " + str
os.system(final)
I am trying to set permission to a folder Using Python but while running this command , User input needs to be provided too i.e
it asks ARE YOU SURE(Y/N) and the user needs to enter "Y" or "N"
Is there any way to use python to send the user input "Y" along with the above code?
pro = subprocess.Popen(final,shell=True, stdin=subprocess.PIPE)
pro.communicate(bytes("Y\r\n",'utf-8'))
I have added the following code . The program exits without setting the permission.
http://jimmyg.org/blog/2009/working-with-python-subprocess.html#writing-to-standard-input
Try using the subprocess module
import subprocess
cmd = ["cacls", "E:/" + list1[2], list1[3], "/p", str]
pro = subprocess.Popen(final, stdin=subprocess.PIPE)
pro.communicate("y\r\n")
As a smart programmer, use PBS
Then, the code is:
from pbs import type as echo# Isn't it echo for Windows? If not, use the correct one
script = Command("/path/to/cacls ")
print script(echo("Y"), ("E:/" + "\"" + list1[2] + " " + list1[3] + "\"" + " /p " + str).split())