I am automating instance creation using OpenstackSDK and passing bash script with commands as userdata. But the script does not excute even though the instance is crated. When I do this manually via GUI, the bash scripts executes fine to the newly created instance.
#Reading bash script
with open('elk.sh', 'r') as f:
init_script = f.read()
server = conn.compute.create_server(
name=name,
image_id=IMAGE_ID,
flavor_id=FLAVOUR_ID,
networks=[{"uuid": NETWORK_ID}],
user_data=init_script, # pass script to the instance
key_name=KEY_PAIR
)
Note: Also tried to encode as Base64 file butstill failed with
is not JSON serializable.
Code snippet:
with open(USER_DATA,'r') as file:
f = file.read()
bytes_content = bytes(f,encoding='utf-8')
init_script = base64.b64encode(bytes_content)
Can anyone advice on this, please?
Thanks
Python3 handles string and binary differently. Also, to pass bash/cloud-config file to --user_data via OpenstackSDK, it has to be base46 encoded.
Code snippet:
with open(USER_DATA,'r') as file:
f = encodeutils.safe_encode(file.read().encode('utf-8'))
init_script = base64.b64encode(f).decode('utf-8')
Related
I am constructing a command to pass to requests library to Post an attachment - as in
files= attachment = {"attachment": ("image.png", open("C:\tmp\sensor.png", "rb"), "image/png")}
The code is working but I cannot get PyTest to test it as -is because of the open command which is executed when evaluated. Here is simplified code of the problem
import pytest
def openfile():
cmd = {"cmd": open(r"C:\tmp\sensor.png")}
return cmd
def test_openfile():
cmd = openfile()
#assert str(cmd) == str({"cmd": open(r"C:\tmp\sensor.png")}) # this works
assert cmd == {"cmd": open(r"C:\tmp\sensor.png")} # this does not
PyTest complains that the two side are different but then confirms they are the same in the diff panel!
Expected :{'cmd': <_io.TextIOWrapper name='C:\tmp\sensor.png' mode='r' encoding='cp1252'>}
Actual :{'cmd': <_io.TextIOWrapper name='C:\tmp\sensor.png' mode='r' encoding='cp1252'>}
'Click to see difference' - Opening diff panel reports 'Contents are identical'!
I can just stick with comparing the generated string with expected string but am wondering if there is a better way to do this.
Ideas?
You need to test the properties of the actual file buffer that is returned by the open call, instead of the references to that buffer, for example:
def test_openfile():
cmd = openfile()
expected_filename = r"C:\tmp\sensor.png"
assert "cmd" in cmd
file_cmd = cmd["cmd"]
assert file_cmd.name == expected_filename
with open(expected_filename) as f:
contents = f.read()
assert file_cmd.read() == contents
Note that in a test you may not have the file contents, or have them in another place like a fixture, so testing the file contents may have to be adapted, or may not be needed, depending on what you want to test.
After talking this through with a friend I think my original approach is perfectly valid. For anyone that trips over this question here's why:
I am trying to pytest building of an executable parameter to pass to another library for execution. The execution of the parameter is not relevant, just that it is correctly formatted. The test is to compare what is generated with the expected parameter ( as if I typed it) .
Therefore casting to string or json and comparing is appropriate since that is what a human does to manually check the code!
The following code working for executing the batch file:
def GetCMD_Encoding(self):
self.CMD = QProcess(self)
self.CMD.setProcessChannelMode(QProcess.MergedChannels)
self.CMD.readyReadStandardOutput.connect(self.EventDataForGetCMDEncoding)
self.CMD.start("chcp.bat")
def EventDataForGetCMDEncoding(self):
output = bytearray(self.CMD.readAllStandardOutput())
output = output.decode("ascii")
print (output)
The content of .bat file is only :
chcp
But if i want to exclude but file and i only execute simple command like:
self.CMD.start("chcp")
it does not working and any kind of signal isnt emit.
Other commands is working like :
self.CMD.start("ipconfig")
self.CMD.start("help")
You should try to
Use the full path of the file chcp.bat
Or add the path of the file chcp.bat to your system PATH
and maybe ensure that the file is executable.
I'm currently stuck on trying to find a way to put to a generation data group (GDG) on mainframe(zos) using Jsch.
The command line syntax would be
put myFile.txt GDG.MYGDG(+1)
This I know works fine when using sftp or ftp command via a linux shell. I have not found any way to replicate this via the put method of the ChannelSftp class.
I have searched wide and far looking for examples and not found any which makes me think it is not possible with this framework.
Any help would be appreciated.
UPDATE
adding some example code. This is not the full code but shows what I have tried.
String localFileName = localFile.getName();
String remoteFile = "GDG.GDGROUP1(+1)";
FileInputStream inputStream = new FileInputStream(localFile);
ChannelSftp channelSftp = this.getChannelSftp();
String pwd = channelSftp.pwd();
channelSftp.put(inputStream, remoteFile);
The put call always returns that this is directory. I have also tried this for the remote file:
String remoteFile = localFile + " GDG.GDGROUP1(+1)";
This just returns failure.
I have tried absolute path using // and /-/. So far nothing has worked.
I want to use a relative file path as a command line argument but as the example and assessment below will demonstrate, the variable passes \..\ as a string, it doesn't evaluate it.
Can I can force the command line to parse and expand the variable as a string?
: For example: I have a R script file I want to launch from the command line:
Set RPath=C:\Program Files\R\R-3.1.0\bin\Rscript.exe
SET RScript=%CD%\..\..\HCF_v9.R
SET SourceFile=%CD%\..\Source\
ECHO String used for Source Location - %SourceFile%
"%RPath%" "%RScript%" %SourceFile%
The inclusion of \..\ works in the call to R as an external program because the batch file can resolve it's own commands.
The variable of SourceFile however doesn't work because the SourceFile variable hasn't expanded \..\, it has just included it as part of the string and R can't process \..\
You can use the for replaceable parameters to resolve to the real path
for %%a in ("..\..\HCF_v9.R") do set "RScript=%%~fa"
#MC ND has provided the batch file approach; an R-centric approach would be to pass the current directory to R, and modify it there.
; batch file
Set RPath=C:\Program Files\R\R-3.1.0\bin\Rscript.exe
SET RScript=%CD%\..\..\HCF_v9.R
"%RPath%" "%RScript%" %CD%
# in R
srcpath <- commandArgs(TRUE)[1]
srcpath <- normalizePath(file.path(srcpath, "../Source"))
i wrote the following code to output source address and destination address of all packets that are in a .pcap file to a text file using lua and tshark.
#!/usr/bin/lua
do
local file = io.open("luawrite", "w")
local function init_listener()
local tap = Listener.new("ipv6")
function tap.packet(pinfo, tvb)
local srcadd = pinfo.src
local dstadd = pinfo.dst
file:write(tostring(srcadd), "\t", tostring(dstadd)"\n")
end
end
end
I am running this script using the following command:
tshark -r wireless.pcap -xlua_script:MyScript.lua
Why is nothing being written in my text file? Is there something wrong on the code? Help is very much appreciated. Thanks!
Probably because you are missing a comma before "\n":
---------------------------------------------------vv-----
file:write(tostring(srcadd), "\t", tostring(dstadd), "\n")
It may be useful to check for file value returned by the open call.
I don't see any other problems with the script; if you still have issues, I have a page on debugging Wireshark Lua scripts that may help.