Fabric python script outputting "Encountered a bad command exit code!" - python

For context:
I have an HP DL380p and the fans are annoyingly loud because of PCIe cards and non HP-drives. So I flashed the iLO (HPE Integrated Lights-Out) on the server with a modded version which allows to edit fan curves. I already tried it manually and it works fine, PCIe cards and CPU never go over 60 °C with my usage. There is problem with the mod however, which makes to if you're SSH connection turns off, the fan command (used to change the fan curves) doesn't work anymore. You have to reset the iLO with the "reset /map1" command, which resets previous fan curves adjustments. Which is why I found fabric and decided to use for this instead of a bash script.
I wrote this code:
from fabric import Connection
import time
connection = Connection(host = "username#ip", connect_kwargs = {"password" : "password"})
connection.run("reset /map1")
time.sleep(40)
connection = Connection(host = "username#ip", connect_kwargs = {"password" : "password"})
connection.run("fan info g")
But every time I run it, I get this error:
reset /map1
status=0
status_tag=COMMAND COMPLETED
Tue Jan 31 11:35:12 2023
Resetting iLO.
CLI session stopped
Traceback (most recent call last):
File "C:\Users\ewenlau\Desktop\silence fan.py", line 4, in <module>
connection.run("reset /map1")
File "<decorator-gen-3>", line 2, in run
File "C:\Users\ewenlau\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\fabric\connection.py", line 27, in opens
return method(self, *args, **kwargs)
File "C:\Users\ewenlau\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\fabric\connection.py", line 739, in run
return self._run(self._remote_runner(), command, **kwargs)
File "C:\Users\ewenlau\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\invoke\context.py", line 98, in _run
return runner.run(command, **kwargs)
File "C:\Users\ewenlau\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\fabric\runners.py", line 75, in run
return super().run(command, **kwargs)
File "C:\Users\ewenlau\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\invoke\runners.py", line 376, in run
return self._run_body(command, **kwargs)
File "C:\Users\ewenlau\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\invoke\runners.py", line 432, in _run_body
return self.make_promise() if self._asynchronous else self._finish()
File "C:\Users\ewenlau\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\invoke\runners.py", line 499, in _finish
raise UnexpectedExit(result)
invoke.exceptions.UnexpectedExit: Encountered a bad command exit code!
Command: 'reset /map1'
Exit code: -1
Stdout: already printed
Stderr: already printed
What I was expecting to happen is this script to return me the current fan speed (fan info g). Instead it outputted the error above. I tried removing the sleep command, nothing changed. I have to note that the reset /map1 command closes the connection host side, and I think the problem comes from there, but I have no idea how to fix it.

Related

VI_ERROR_TMO (-1073807339) on Anritsu OSA

I'm working on interfacing an old Optical Spectrum Analyzer Anritsu MS9710B with a RS232 connection. A year ago, I managed to comunicate with him, send SCPI command using pyvisa and receive data. Today, I execute the exact same code with libraries up to date and I get an error Timeout when I query IDN or anything. The RS232-USB drivers are ok, I manage to open a communication but a query or read fail.
I changed the parameter to "RS232C" on the OSA parameters and my communication parameters are the same between OSA and program. Following advices from the forum, I tried the connection with NI-VISA where I get the same error. I tried to change timeout parameter, write_termination and read_termination but there isn't any change. The manual is very hard to understand termination value, but when it worked I didn't add anything.
I don't know anymore what to do.
Any advices and help would be warmly welcome to fix my problem !
import pyvisa
from pyvisa.constants import StopBits, Parity
rm = pyvisa.ResourceManager()
print(rm.list_resources())
my_instrument = rm.open_resource('ASRL5::INSTR')
my_instrument.baud_rate=9600
my_instrument.data_bits=8
my_instrument.parity=Parity.even
my_instrument.stop_bits=StopBits.one
my_instrument.write('*IDN?')
print(my_instrument.read())```
'''
('ASRL5::INSTR',)
Traceback (most recent call last):
File "PremiereComm.py", line 26, in <module>
print(my_instrument.read())
File "C:\Program Files\Python38\lib\site-packages\pyvisa\resources\messagebased.py", line 486, in read
message = self._read_raw().decode(enco)
File "C:\Program Files\Python38\lib\site-packages\pyvisa\resources\messagebased.py", line 442, in _read_raw
chunk, status = self.visalib.read(self.session, size)
File "C:\Program Files\Python38\lib\site-packages\pyvisa\ctwrapper\functions.py", line 2337, in read
ret = library.viRead(session, buffer, count, byref(return_count))
File "C:\Program Files\Python38\lib\site-packages\pyvisa\ctwrapper\highlevel.py", line 222, in _return_handler
return self.handle_return_value(session, ret_value) # type: ignore
File "C:\Program Files\Python38\lib\site-packages\pyvisa\highlevel.py", line 251, in handle_return_value
raise errors.VisaIOError(rv)
pyvisa.errors.VisaIOError: VI_ERROR_TMO (-1073807339): Timeout expired before operation completed.
>>> '''

Python psutil.wait raise timeout without good reason

I'm facing a strange situation, I've searched on google without any good results.
I'm running a python script as a subprocess from a parent subprocess with nohup using subprocess package:
cmd = list()
cmd.append("nohup")
cmd.append(sys.executable)
cmd.append(os.path.abspath(script))
cmd.append(os.path.abspath(conf_path))
_env = os.environ.copy()
if env:
_env.update({k: str(v) for k, v in env.items()})
p = subprocess.Popen(cmd, env=_env, cwd=os.getcwd())
After some time the parent process exists and the subprocess (the one with the nohup continues to run).
After another minute or two the process with the nohup exits, and with obvious reasons, becomes a zombie.
When running it on local PC with python3.6 and ubuntu 18.04, I manage to run the following code and everything works like a charm:
comp_process = psutil.Process(pid)
if comp_process.status() == "zombie":
comp_status_code = comp_process.wait(timeout=10)
As I said, everything works like a charm, The zombie process removed and I got the status code of the mentioned process.
But for some reason, when doing the SAME at docker container with the SAME python version and Ubuntu version, It fails after the timeout (Doesn't matter if its 10 seconds or 10 minutes)
The error:
psutil.TimeoutExpired timeout after 60 seconds (pid=779)
Traceback (most recent call last): File
"/usr/local/lib/python3.6/dist-packages/psutil/_psposix.py", line 84,
in wait_pid
retpid, status = waitcall() File "/usr/local/lib/python3.6/dist-packages/psutil/_psposix.py", line 75,
in waitcall
return os.waitpid(pid, os.WNOHANG) ChildProcessError: [Errno 10] No child processes
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File ".py", line 41, in
run
comp_status_code = comp_process.wait(timeout=60) File "/usr/local/lib/python3.6/dist-packages/psutil/init.py", line
1383, in wait
return self._proc.wait(timeout) File "/usr/local/lib/python3.6/dist-packages/psutil/_pslinux.py", line
1517, in wrapper
return fun(self, *args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/psutil/_pslinux.py", line
1725, in wait
return _psposix.wait_pid(self.pid, timeout, self._name) File "/usr/local/lib/python3.6/dist-packages/psutil/_psposix.py", line 96,
in wait_pid
delay = check_timeout(delay) File "/usr/local/lib/python3.6/dist-packages/psutil/_psposix.py", line 68,
in check_timeout
raise TimeoutExpired(timeout, pid=pid, name=proc_name) psutil.TimeoutExpired: psutil.TimeoutExpired timeout after 60 seconds
(pid=779)
One possibility may be the lack of an init process to reap zombies. You can fix this by running with docker run --init, or using e.g. tini. See https://hynek.me/articles/docker-signals/

Python Debugger on VS Code 2019 hangs

I'm trying to use the Python debugger on VS Code 2019 on my Mac, but it looks like it is causing the program to hang indefinitely (the print statement never gets executed). If I run the program without the debugger, everything works. I don't have any breakpoints configured either.
Here is my code:
#!/usr/bin/env python3
dummy = input("Enter something: ")
print(dummy)
Edit: I'm not sure if it's related, but when I click the stop button "square", the program doesn't immediately quit. It takes a few seconds, and then I see this in my terminal window:
E+01487.808: Failed to kill Debuggee[PID=2791]
Traceback (most recent call last):
File "/Users/XXXXX/.vscode/extensions/ms-python.python-2020.8.101144/pythonFiles/lib/python/debugpy/launcher/../../debugpy/launcher/debuggee.py", line 160, in kill
os.killpg(process.pid, signal.SIGKILL)
PermissionError: [Errno 1] Operation not permitted
Stack where logged:
File "/Users/XXXXX/.vscode/extensions/ms-python.python-2020.8.101144/pythonFiles/lib/python/debugpy/launcher/../../debugpy/launcher/debuggee.py", line 162, in kill
log.swallow_exception("Failed to kill {0}", describe())
File "/Users/XXXXX/.vscode/extensions/ms-python.python-2020.8.101144/pythonFiles/lib/python/debugpy/launcher/../../debugpy/common/log.py", line 215, in swallow_exception
_exception(format_string, *args, **kwargs)
(.venv) Scripts %

How to solve "control message failed, win error: A device which does not exist was specified" error PyUSB

I'm trying to connect a POS receipt printer to python and have been using python-escpos to do so. I'm running windows 10.
My code in my file 'print.py' is:
from escpos.printer import Usb
p = Usb(0x0456,0x0808)
p.text('Hello World\n')
but when i run it i get the following error log:
Traceback (most recent call last):
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\core.py", line 223, in get_interface_and_endpoint
return self._ep_info[endpoint_address]
KeyError: 1
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "print.py", line 5, in <module>
p.text('Hello World\n')
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\escpos\escpos.py", line 437, in text
self._raw(txt.encode())
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\escpos\printer.py", line 73, in _raw
self.device.write(self.out_ep, msg, self.timeout)
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\core.py", line 940, in write
intf, ep = self._ctx.setup_request(self, endpoint)
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\core.py", line 102, in wrapper
return f(self, *args, **kwargs)
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\core.py", line 215, in setup_request
intf, ep = self.get_interface_and_endpoint(device, endpoint_address)
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\core.py", line 102, in wrapper
return f(self, *args, **kwargs)
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\core.py", line 225, in get_interface_and_endpoint
for intf in self.get_active_configuration(device):
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\core.py", line 102, in wrapper
return f(self, *args, **kwargs)
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\core.py", line 239, in get_active_configuration
bConfigurationValue=self.backend.get_configuration(self.handle)
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\backend\libusb0.py", line 510, in get_configuration
100)
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\backend\libusb0.py", line 593, in ctrl_transfer
timeout
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\backend\libusb0.py", line 431, in _check
raise USBError(errmsg, ret)
usb.core.USBError: [Errno None] b'libusb0-dll:err [control_msg] sending control message failed, win error: A device which does not exist was specified.\r\n\n'
Does anyone know what i need to do to make this work.
I have installed libusb into my System32 and SysWOW64 folders, aswell as installing a libusb-32 driver for my printer with zadig.
The printer i'm using is a 'Hoin 58mm POS Printer'.
I would be grateful if someone could explain to me why i'm having this error and how to solve it!
Firstly, you can check this link for the complete thread.
As suggested by KM4YRI,
I ran into the same No backend available exception when trying to follow the tutorial on a Windows 7 machine. The following worked for me, per one of the StackOverflow replies:
1. Download the latest Windows binary: https://sourceforge.net/projects/libusb/files/libusb-1.0/libusb-1.0.21/libusb-1.0.21.7z/download
2. Unzip using 7zip into a temp dir
3. If on 64-bit Windows, copy `MS64\dll\libusb-1.0.dll` into `C:\windows\system32`. If on 32-bit windows, copy `MS32\dll\libusb-1.0.dll` into `C:\windows\SysWOW64`.
I've verified the above answer on Windows-10 64-bit version.
I had a tight experience with that error using at least 3 different USB Storage Devices. After hours of trials I ended up to a feeling that USB transmission errors are the cause of this error.
The USB bus will return it in a random pattern for a low quality connection as if a device remove has presumably happened.
In my scenario I was bulk writing sectors to a \\.\PhysicalDriveN device and I noticed that after a short period the connection reestablished and the file handle was still valid and going.
To overcome the error I've ended up with the following steps:
Seek To File Position;
Write Sector;
For any 433 error:
250 ms delay;
Seek To file Position, ignoring ERROR_NO_SUCH_DEVICE and ERROR_NOT_READY errors and trying for at least 1000 ms before giving up;
Read Sector, ignoring ERROR_NO_SUCH_DEVICE and ERROR_NOT_READY errors and retrying for up to 1000 ms before giving up;
Specially for my scenario: I've compared input buffer and read buffer and stop if matching;
Repeat the whole procedure up to 5 times.
So the idea here is the following: The device driver returns ERROR_NO_SUCH_DEVICE assuming a device remove scenario, but still in a pending state. As the problem is simply quality of physical connection, the link continues and the bus driver starts a renegotiation, in which case a ERROR_NOT_READY is temporarily returned. When the link is stable and negotiated, communication continues without the need to reopen the device handle.
I would recommend adding a sleep statement of a second or two in between the instantiation of the USB printer, and the attempt to print to it. e.g:
from escpos.printer import Usb
from time import sleep
p = Usb(0x0456,0x0808)
sleep(1)
p.text('Hello World\n')

Having problems using telnet twice into server from python script

Working on my first python script at work to automate some testing.
I'm having trouble telneting to a server twice from my script. The first time I'm calling the telnet function, everything works, the second time my script calls the telnet function, I get the following errors below. I have a second function that runs some commands and exits. I've also tried without an exit, but that did not work either. So I thought that would close out the session, by doing a "close" on the session as well.
Thanks in advance.
The reason I want to go back into the server, is I make a change to the DB and want to verify the change took affect.
I'm calling these functions from another python script.
** Updated with where "tn" is assigned, which is outside the function, so I'm unsure how telnet even works the first time.
tn = telnetlib.Telnet(intems03, "8123")
def telnet_ems():
tn.read_until(b"Login :")
tn.write(bytes(username + "\n", "UTF-8"))
tn.read_until(b"Password:")
tn.write(bytes(password + "\n", "UTF-8"))
def show_sip_domain(sipDomain):
str2byte = sipDomain.encode("ascii")
tn.write(b"show Sip_Domain Sip_Domain_Id "+str2byte)
tn.write(b"\n")
tn.write(b"exit\n")
** Error messages **
Traceback (most recent call last):
File "c:\Users\xxxx\.vscode\extensions\ms-python.python-2019.8.30787\pythonFiles\ptvsd_launcher.py", line 43, in <module> main(ptvsdArgs)
File "c:\Users\xxxx\.vscode\extensions\ms-python.python-2019.8.30787\pythonFiles\lib\python\ptvsd\__main__.py", line 432, in main run()
File "c:\Users\xxxx\.vscode\extensions\ms-python.python-2019.8.30787\pythonFiles\lib\python\ptvsd\__main__.py", line 316, in run_file runpy.run_path(target, run_name='__main__')
File "C:\Users\xxxx\AppData\Local\Programs\Python\Python37-32\lib\runpy.py", line 263, in run_path pkg_name=pkg_name, script_name=fname)
File "C:\Users\xxxx\AppData\Local\Programs\Python\Python37-32\lib\runpy.py", line 96, in _run_module_code mod_name, mod_spec, pkg_name, script_name)
File "C:\Users\xxxx\AppData\Local\Programs\Python\Python37-32\lib\runpy.py", line 85, in _run_code exec(code, run_globals)
File "c:\Python_Exercises\Selenium_test_examples\test_TelnetEms.py", line 11, in <module> telnet_ems()
File "c:\Python_Exercises\Selenium_test_examples\Telnet_EMS_Show_functions.py", line 16, in telnet_ems tn.read_until(b"Login :")
File "C:\Users\xxxx\AppData\Local\Programs\Python\Python37-32\lib\telnetlib.py", line 315, in read_until self.fill_rawq()
File "C:\Users\xxxx\AppData\Local\Programs\Python\Python37-32\lib\telnetlib.py", line 524, in fill_rawq buf = self.sock.recv(50)
ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine
Error 10053 is telling you that the other end is telling you to get lost, though I'm not sure we have enough context to know what's going on.
One thing to check: after you run the first one that works, see if there is still a TCP connection from the python-hosted computer to whatever it's talking to; you can find this at the command line (Linux or Windows, at least), with the netstat command: if you still have a lingering connection, you for sure have to close the old one with .close()
Also, is there a delay before you get the above message, indicating it might be timing out, or does it happen immediately?
[Disclaimer: network guy, not a python guy]

Categories

Resources