Linux Virtual Serial Port for creating a device commuication - python

I created a VSP using SOCAT with below command:
socat -d -d pty,raw,echo=0 pty,raw,echo=0
where I was able create a serial device (19200,N,8,1) and send and receive data using Python.
So I have to do the same for one more device with config of (19200,even_aprity,hardware flow in Python) when I do that its throwing below error:
Traceback (most recent call last):
File "py2.py", line 163, in <module>
buffer += ser.read(1) # this will block until one more char or timeout
File "/usr/lib/python2.6/dist-packages/serial/serialposix.py", line 311, in read
if self.fd is None: raise portNotOpenError
serial.serialutil.SerialException: Port not open
Exception SystemError: 'error return without exception set' in <bound method BreakHandler.__del__ of <sig_handler.BreakHandler instance at 0xb719338c>> ignored
Guide me

Related

"This socket is already used by another greenlet" using locust to report response times into graphite

Hello I managed to get locust to work with graphite with the following code:
class MyLocust(HttpUser):
tasks = [MyTask]
sock = None
def exit_handler(self):
self.sock.shutdown(socket.SHUT_RDWR)
self.sock.close()
def hook_request_success(self, request_type, name, response_time, response_length):
# print(response_time)
message="%s %d %d\n" % ("client." + name.replace('.', '-'), response_time, time.time())
self.sock.send(message.encode())
def hook_request_fail(self, request_type, name, response_time, exception):
self.request_fail_stats.append([name, request_type, response_time, exception])
def __init__(self, parent):
super().__init__(parent)
self.sock = socket.socket()
self.sock.connect( ("192.168.XX.YYYY", 2003) )
events.request_success.add_listener(self.hook_request_success)
events.request_failure.add_listener(self.hook_request_fail)
atexit.register(self.exit_handler)
Adn this works quiet good while I use a small amout of users in locust, around 100.
But when the users start to go up, I get the following exception:
[2021-05-31 18:40:48,430] HMG28/ERROR/root: Uncaught exception in event handler:
Traceback (most recent call last):
File "c:\python39\lib\site-packages\gevent\_socketcommon.py", line 722, in send
return self._sock.send(data, flags)
BlockingIOError: [WinError 10035] A non-blocking socket operation could not be completed immediately
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\python39\lib\site-packages\locust\event.py", line 40, in fire
handler(**kwargs)
File "C:\Users\AAA\Desktop\AAA\locust_files\locustfile.py", line 60, in hook_request_success
self.sock.send(message.encode())
File "c:\python39\lib\site-packages\gevent\_socketcommon.py", line 727, in send
self._wait(self._write_event)
File "src\\gevent\\_hub_primitives.py", line 317, in gevent._gevent_c_hub_primitives.wait_on_socket
File "src\\gevent\\_hub_primitives.py", line 322, in gevent._gevent_c_hub_primitives.wait_on_socket
File "src\\gevent\\_hub_primitives.py", line 297, in gevent._gevent_c_hub_primitives._primitive_wait
gevent.exceptions.ConcurrentObjectUseError: This socket is already used by another greenlet: <bound method Waiter.switch of <gevent._gevent_c_waiter.Waiter object at 0x00000222BA8FB4F0>>
Is there a way to make the socket connections wait until they can send the data?
Searching SO for your error, I found this possibly helpful answer:
Non-Blocking error when adding timeout to python server
If you continue to have issues, you can try using a gevent compatible socket and see if that gets you the concurrency you want more easily.

How do I troubleshoot spur failing to make an SSH connection in python?

I have two nearly identical devices. spur will connect via ssh with one, but not the other. How do I figure out why?
>>> shell1 = spur.SshShell('10.201.140.242', 'username', 'password', missing_host_key=spur.ssh.MissingHostKey.accept)
>>> results = shell1.run(['ls', '-a'])
>>> results.output
'.\n..\n.aptitude\n.bashrc\n.cache\n.config\n.profile\n'
>>> shell2 = spur.SshShell('10.201.129.56', 'username', 'password', missing_host_key=spur.ssh.MissingHostKey.accept)
>>> results = shell2.run(['ls', '-a'])
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "E:\development\virtenv\lib\site-packages\spur\ssh.py", line 166, in run
return self.spawn(*args, **kwargs).wait_for_result()
File "E:\development\virtenv\lib\site-packages\spur\ssh.py", line 178, in spawn
channel = self._get_ssh_transport().open_session()
File "E:\development\virtenv\lib\site-packages\spur\ssh.py", line 268, in _get_ssh_transport
raise self._connection_error(error)
ConnectionError: Error creating SSH connection
Original error: ('10.201.129.56', <paramiko.ecdsakey.ECDSAKey object at 0x11328070>, <paramiko.ecdsakey.ECDSAKey object at 0x1135F350>)
I'm confused by the error message. What does returning the ip, and two key objects supposed to mean? Is there helpful info here I'm supposed to glean from that?
Both devices will accept ssh connections from the command line, so that sets aside an obvious problem.
Both are running the same version of Ubuntu, with the same login credentials. Home directories are even the same (no .ssh dir). Even further, both of their sshd_config files are identical (so, also using the same version among other config options).
The problem doesn't seem to be in the ssh settings, but the error gives no indication of where the problem could be!
Any ideas?
Enabling logging doesn't add much.
shell1:
11:32:11|[ INFO] - paramiko.transport - _log - Connected (version 2.0, client OpenSSH_5.9p1)
11:32:11|[ INFO] - paramiko.transport - _log - Authentication (password) successful!
shell2:
11:32:25|[ INFO] - paramiko.transport - _log - Connected (version 2.0, client OpenSSH_5.9p1)
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "E:\development\virtenv\lib\site-packages\spur\ssh.py", line 166, in run
return self.spawn(*args, **kwargs).wait_for_result()
File "E:\development\virtenv\lib\site-packages\spur\ssh.py", line 178, in spawn
File "E:\development\virtenv\lib\site-packages\spur\ssh.py", line 268, in _get_ssh_transport
raise self._connection_error(error)
ConnectionError: Error creating SSH connection
Original error: ('10.201.129.56', <paramiko.ecdsakey.ECDSAKey object at 0x1132EF10>, <paramiko.ecdsakey.ECDSAKey object at 0x11366DF0>)
It might be telling that the SSH reports connection. The failure occurs before/during authentication. But as I said above, the passwords are the same -- both connections even use the same copy-pasted pw, which works without error on a command line connection.

Python Script Pexpect SSH

I'm trying to do a Python script (with a loop) to connect in SSH,it works if everything is good ( password and route) but stop when it's not working(wrong password or no routes to host ).Here is the important part of the script, how can I control if everything is working ?
connexion = pexpect.spawn("ssh -o StrictHostKeyChecking=no "+user+"#" + ip )
index=connexion.expect(':')
connexion.sendline(password + "\r")
connexion.expect('>')
connexion.sendline('show clock \r')
connexion.expect('>')
connexion.sendline('exit')
connexion.close()
I get the error :
Traceback (most recent call last):
File "script.py", line 21, in <module>
connexion.expect('>')
File "/usr/lib/python2.7/dist-packages/pexpect/__init__.py", line 1418, in expect
timeout, searchwindowsize)
File "/usr/lib/python2.7/dist-packages/pexpect/__init__.py", line 1433, in expect_list
timeout, searchwindowsize)
File "/usr/lib/python2.7/dist-packages/pexpect/__init__.py", line 1521, in expect_loop
raise EOF(str(err) + '\n' + str(self))
pexpect.EOF: End Of File (EOF). Exception style platform.
<pexpect.spawn object at 0x7fcfeecee750>
version: 3.1
command: /usr/bin/ssh
args: ['/usr/bin/ssh', '-o', 'StrictHostKeyChecking=no', 'username#10.9.128.5']
searcher: <pexpect.searcher_re object at 0x7fcfeecee850>
buffer (last 100 chars): ''
before (last 100 chars): ' connect to host 10.9.128.5 port 22: No route to host\r\r\npassword\r\n\r\n'
Thanks
The problem is that the host 10.9.128.5 was not reachable at the moment.
ssh has returned this message:
connect to host 10.9.128.5 port 22: No route to host
And not that, what was expected.
You are getting an exception which needs to be handled correctly. Below is some code that you can use as an example to pass the exception and log it.
def ignore_exception_out(conn, text, timeout=10):
try:
conn.expect(text, timeout)
except Exception as e:
logging.log("Exception reached {0}".format(e))
pass

PyEZ: jnpr.junos.exception.ConnectRefusedError: ConnectRefusedError(xx.xxx.xxx.xxx)

PyEZ Device connection returns ConnectRefusedError.
>>> dev = Device(host='xx.xxx.xx.xx', user='xxxx',password='xxxx')
>>> dev.open()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\jnpr\junos\device.py", line 459, in open
raise EzErrors.ConnectRefusedError(self)
jnpr.junos.exception.ConnectRefusedError: ConnectRefusedError(xx.xxx.xx.xx)
It looks like netconf is not enabled on the given device. (hence PyEZ is not able to connect to netconf default 830 port).
We have 2 option
Enable netconf on device using below config command
"set system services netconf ssh"
Or pass port=22 in device class, so that PyEZ uses sh port to communicate in place of netconf 830 port.
dev = Device(host='xx.xx.xx.xxx', user='xxx', password='xxxx', port=22)

paramiko's ssh channel closed after executing one cmd - Python

I'm using Python's Paramiko to execute commands in a remove server. The code is much simple.
Here's my definition of the SSHConn class:
class SSHConn:
def __init__(self, hostname, user, pwd, filename=None):
self.client = paramiko.SSHClient()
self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.client.connect(hostname, username=user, password=pwd,
key_filename=filename)
self.transport = self.client.get_transport()
self.channel = self.transport.open_session()
So I'm running the following code:
local_ssh = ssh.SSHConn(host, user, passwd)
cmds = ('foo', 'bar')
for cmd in cmds:
local_ssh.channel.exec_command(cmd)
self.log.info(local_ssh.channel.recv(1024))
However, when I execute the following code snipped I'm getting:
INFO:paramiko.transport:Connected (version 2.0, client OpenSSH_6.6.1p1)
INFO:paramiko.transport:Authentication (publickey) failed.
INFO:paramiko.transport:Authentication (password) successful!
INFO:paramiko.transport:Secsh channel 1 opened.
INFO:testsets.testcase:
ERROR:testsets.testcase:Channel is not open
Traceback (most recent call last):
File "/root/fds-src/source/test/integration-framework/testsets/testcases/test_100gb_volume.py", line 87, in runTest
local_ssh.channel.exec_command(cmd)
File "/usr/lib/python2.7/dist-packages/paramiko/channel.py", line 209, in exec_command
raise SSHException('Channel is not open')
SSHException: Channel is not open
ERROR:testsets.testcase:Test Case Test100GBVolume failed.
Traceback (most recent call last):
File "/root/fds-src/source/test/integration-framework/testsets/testcases/test_100gb_volume.py", line 87, in runTest
local_ssh.channel.exec_command(cmd)
File "/usr/lib/python2.7/dist-packages/paramiko/channel.py", line 209, in exec_command
raise SSHException('Channel is not open')
SSHException: Channel is not open
How can I keep the channel open?
The channel docs are very clear about this point. You need to open a new channel for each exec_command.
exec_command(*args, **kwds)
Execute a command on the server. If the server allows it, the channel will then be directly connected to the stdin, stdout, and stderr of the command being executed.
When the command finishes executing, the channel will be closed and can’t be reused. You must open a new channel if you wish to execute another command.
The SSHClient object has an exec_command method that does this for you.

Categories