websocket paramiko Throw a socket.timeout exception - websocket

Paramiko module always throws an exception
paramiko.buffered_pipe.PipeTimeout
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python37\lib\threading.py", line 917, in _bootstrap_innerenter code here
self.run()
File "c:/Users/LENOVO/Desktop/index.py", line 42, in runenter code here
data = self.chan.recv(1024)
File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python37\lib\site-packages\paramiko\channel.py", line 685, in recv
raise socket.timeout()
socket.timeout
I am building a webssh project using paramiko, websocket, xterm.js.
I tried Tornado and Flask but both throw an exception for socket.timeout
This is the Flask code
from flask import Flask, jsonify, request
from flask_sockets import Sockets
import paramiko
import threading
import time
from gevent import pywsgi
from geventwebsocket.handler import WebSocketHandler
app = Flask(__name__)
sockets = Sockets(app)
app.config['DEBUG'] = True
HOSTS = "172.16.100.100"
PORT = 22
USERNAME = "root"
PASSWORD = "123456"
#app.after_request
def after_request(response):
response.headers.add("Access-Control-Allow-Origin", "*")
if request.method == "OPTIONS":
response.headers["Access-Control-Allow-Methods"] = "DELETE, GET, POST, PUT"
headers = request.headers.get("Access-Control-Request-Headers")
if headers:
response.headers["Access-Control-Allow-Headers"] = headers
return response
class MyThread(threading.Thread):
def __init__(self, chan, ws):
threading.Thread.__init__(self)
self.chan = chan
self.ws = ws
def run(self):
while not self.chan.exit_status_ready():
time.sleep(0.1)
# try:
data = self.chan.recv(1024)
self.ws.send(data)
# except Exception as e:
# print("异常信息", str(e))
self.chan.sshclient.close()
return False
#sockets.route("/terminals/")
def terminals(ws):
sshclient = paramiko.SSHClient()
sshclient.load_system_host_keys()
sshclient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
sshclient.connect(HOSTS, PORT, USERNAME, PASSWORD)
chan = sshclient.invoke_shell(term='xterm')
chan.settimeout(0)
thread = MyThread(chan, ws)
thread.setDaemon(True)
thread.start()
while not ws.closed:
message = ws.receive()
if message is not None:
chan.send(bytes(message, encoding='utf-8'))
if __name__ == '__main__':
server = pywsgi.WSGIServer(
('0.0.0.0', 5000), app, handler_class=WebSocketHandler)
server.serve_forever()
This is the Javascript code
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="./xterm.css" />
<script src="./xterm.js"></script>
<script src="./fit.js"></script>
<script src="./attach.js"></script>
</head>
<body>
<div id="terminal" style="height: 800px;"></div>
<script>
var term = new Terminal();
var socket = new WebSocket('ws://127.0.0.1:5000/terminals/');
term.open(document.getElementById('terminal'), true);
term.attach(socket, true, true);
term.detach(socket);
term._initialized = true
term.writeln('Welcome to xterm.js');
term.fit();
// term.on('key', (key, ev) => {
// if (key.charCodeAt(0) == 13)
// term.write('\n');
// term.write(key);
// });
socket.onclose = function () {
term.writeln("closed. Thank you for use!");
};
</script>
</body>
</html>
To be sure, the host SSH connection is normal.
When the connection is established, data = self.chan.recv(1024) is data.

problem solved
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="./xterm.css" />
<script src="./xterm.js"></script>
<script src="./fit.js"></script>
<script src="./attach.js"></script>
</head>
<body>
<div id="terminal" style="height: 800px;"></div>
<script>
var term = new Terminal({cursorBlink: true});
term.open(document.getElementById('terminal'), true);
term.writeln('Welcome to xterm.js');
var socket = new WebSocket('ws://127.0.0.1:5000/terminals/');
term.attach(socket, true, true);
term._initialized = true
term.fit();
socket.onclose = function () {
term.writeln("closed. Thank you for use!");
};
</script>
</body>
</html>

Related

Can I connect to Memgraph using websocket?

Does Memgrpah support connections over WebSocket? I couldn't find the minimal required code to do that.
All that you need is a client that uses WebSocket to connect to Memgraph, and Memgraph will automatically recognize the nature of the connection. The port you will be connected to remains the same.
You should use Memgraph's address and the port number defined by the configuration flag --bolt-port to connect to Memgraph (7687 is the default port).
To connect to memgraph via WebSocket you can use the JavaScript client. Minimal code to connect would be:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Javascript Browser Example | Memgraph</title>
<script src="https://cdn.jsdelivr.net/npm/neo4j-driver"></script>
</head>
<body>
<p>Check console for Cypher query outputs...</p>
<script>
const driver = neo4j.driver(
"bolt://localhost:7687",
neo4j.auth.basic("", "")
);
(async function main() {
const session = driver.session();
try {
await session.run("MATCH (n) DETACH DELETE n;");
console.log("Database cleared.");
await session.run("CREATE (alice:Person {name: 'Alice', age: 22});");
console.log("Record created.");
const result = await session.run("MATCH (n) RETURN n;");
console.log("Record matched.");
const alice = result.records[0].get("n");
const label = alice.labels[0];
const name = alice.properties["name"];
const age = alice.properties["age"];
if (label != "Person" || name != "Alice" || age != 22) {
console.error("Data doesn't match.");
}
console.log("Label: " + label);
console.log("Name: " + name);
console.log("Age: " + age);
} catch (error) {
console.error(error);
} finally {
session.close();
}
driver.close();
})();
</script>
</body>
</html>
You can find more info at Memgraph documentation site.

function won`t run in if statement (eventlistener && eventlistener) javascript

I'm trying to get an if statement going to get api results.
First I put eventlisteners(click) on my images and when they are BOTH clicked, the get-api-results function should run.
I know I asked something similar before but I got that one screwed up, with this I`m a little closer I think.
Here`s the code
import axios from 'axios';
const container = document.getElementById('container')
let img = document.createElement("img");
img.src = "https://picsum.photos/200/301";
let img2 = document.createElement("img2");
img2.src = "https://picsum.photos/200/300";
const imgCheck = img.addEventListener("click", function(e) {
console.log("check")
})
const img2Check = img2.addEventListener("click", function(e) {
console.log("ok")
})
img.onclick = function () {location.href = "http://localhost:1234/pageTwo.html";};
document.body.appendChild(img);
document.body.appendChild(img2);
if (imgCheck && img2Check){
async function fetchRecipeOne() {
try {
const result = await axios.get('https://api.spoonacular.com/recipes/complexSearch?query=pasta&maxFat=25&number=2&apiKey=0b4d29adff5f4b41908e8ef51329fc48', {
headers: {
"Content-Type": "application/json"
}
})
console.log(result);
} catch (e) {
console.error(e);
}}
fetchRecipeOne();
} else {
console.log('no results');
}
And the html pages
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="styles.css">
<title>Title</title>
</head>
<body>
<img ><img/>
<script type="module" src="app.js"></script>
</body>
</html>
And page 2:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="styles.css">
<title>Title</title>
</head>
<body>
<img id="img2"><img/>
<script type="module" src="app.js"></script>
</body>
</html>
Again, I`m pretty new to this stuff so if can give me enough details to sort this out you would do me a big favour.
Thanks!
Tom
addEventListener() does not return anything.
Maybe you can create a variable and change it in the eventlistener, like so:
let imgCheck = false;
img.addEventListener("click", function(e) {
imgCheck = true;
});
let img2Check = false;
img2.addEventListener("click", function(e) {
img2Check = true;
});
Also you redirect the user when he click on img, reset the click so to say. Maybe delete that
And the where you define img2 you try to create an element with the name 'img2' which isn't a valid element.
So change:
let img2 = document.createElement("img2");
To:
let img2 = document.createElement("img");
Lastly you check is the user has clicked on both the images when the script runs, what you can do is set the if statement in the async function, and call the function when the user clicks on a img.
So it could look something like:
import axios from 'axios';
const container = document.getElementById('container')
let img = document.createElement("img");
img.src = "https://picsum.photos/200/301";
let img2 = document.createElement("img");
img2.src = "https://picsum.photos/200/300";
let imgCheck = false;
img.addEventListener("click", function(e) {
imgCheck = true;
fetchRecipeOne();
});
let img2Check = false;
img2.addEventListener("click", function(e) {
img2Check = true;
fetchRecipeOne();
});
document.body.appendChild(img);
document.body.appendChild(img2);
async function fetchRecipeOne() {
if (imgCheck && img2Check) {
try {
const result = await axios.get('https://api.spoonacular.com/recipes/complexSearch? query=pasta&maxFat=25&number=2&apiKey=0b4d29adff5f4b41908e8ef51329fc48', {
headers: {
"Content-Type": "application/json"
}
})
console.log(result);
} catch (e) {
console.error(e);
}
} else {
console.log('no results');
}
}

Why does 'import socket.io' doesn't work for me?

I'm learning Socket.io and practicing the demo tutorial with individual client side script file.
However, it didn't work as expected.
Here is my code.
client side HTML: index.html
<!DOCTYPE html>
<html>
<head>
...
</head>
<body>
<ul id="messages"></ul>
<form id="form" action="">
<input id="input" autocomplete="off" /><button>Send</button>
</form>
<script src="./app.js"></script>
</body>
</html>
client side JS: app.js
import { io } from "socket.io-client";
var socket = io('http://localhost:3000');
var messages = document.getElementById('messages');
var form = document.getElementById('form');
var input = document.getElementById('input');
form.addEventListener('submit', function(e) {
e.preventDefault();
if (input.value) {
socket.emit('chat message', input.value);
input.value = '';
}
});
socket.on('chat message', function(msg) {
var item = document.createElement('li');
item.textContent = msg;
messages.appendChild(item);
window.scrollTo(0, document.body.scrollHeight);
});
server side JS: index.js
const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env.PORT || 3000;
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', (socket) => {
console.log('a new user join: ', socket.id);
socket.on('chat message', msg => {
io.emit('chat message', msg);
});
});
http.listen(port, () => {
console.log(`Socket.IO server running at http://localhost:${port}/`);
});
After node index to execute my server and open localhost:3000 on my browser, the console.log should tells 'a new user join: xxx', but it didn't.
Is there anything wrong with client side app.js?

JQueryUI autocomplete search with Django not working

I am working on a project with Django, for a restaurant management system. I wanted to use an autocomplete feature to take orders at the table.
As far as I understand JQueryUI function autocomplete() is what I need.
However I cannot seem to get it to work.
Following is my my HTML code for the page. It works in such a way that once the number of people in the party is inserted the same number of form input fiels is inserted in the table by a Javascrip script.
addOrder.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<script type="text/javascript" src={% static "js/jquery-3.3.1.min.js" %}></script>
<script src={% static "js/jquery-ui.min.js" %}></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script type="text/javascript" src={% static "js/createOrderIn.js" %}> </script>
<script type="text/javascript" src={% static "js/autocompleteDrink.js" %}></script>
<script type="text/javascript" src={% static "js/autocompleteMenu.js" %}></script>
<style>
.move {
margin: 30px;
}
</style>
<title>Add Order</title>
</head>
<body>
<div class="move">
<form action="/orders/addOrder" method="post" id="the-form" class="ui-widget">
<label> Party of </label>
<input type="text" id="people">
<input type="submit" class="btn btn-primary" value="Submit order">
</form>
</div>
</body>
</html>
This is the script I use to spawn new form input fields
createOrderIn.js
$(document).ready(function () {
var previous = 0;
var considered = 0;
$("#people").keyup(function ( ) {
var actual = this.value;
if(actual==null){
actual=1;
}
var toAdd = actual-previous;
previous = actual;
if(toAdd > 0){
for(var i=0; i<toAdd; i++){
considered+=1;
var htmlToAdd = $("<div class="+considered+"><input type=\"text\" name=\"menu_"+considered+"\" id=\"menu\"><input type=\"text\" name=\"drink_"+considered+"\" value=\"No drink\" id=\"drink\"><br></div>");
$("#the-form").append(htmlToAdd);
}
}
else{
for(var j=0; j<(-1*toAdd); j++) {
if (considered > 0) {
$("."+considered).remove();
considered -= 1;
}
}
}
});
});
The following are the relative Python/Django files
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.ordersIndex, name = "index"),
path('changeStatus/<int:pk>', views.changeStatus, name="changeStatus"),
path('addOrder', views.addOrder, name="addOrder"),
path('addOrderRender', views.addOrderRender, name="addOrderRender"),
path('getDrinks', views.getDrinks, name="getDrinks"),
path('getMenus', views.getMenus, name="getMenu"),
]
views.py (only function getMenus())
def getMenus(request):
print("I am called")
if request.is_ajax():
q = request.GET.get('term', '')
menus = Menu.objects.filter(name__contains=q)
results=[]
for menu in menus:
menu_json = {}
menu_json['name'] = menu.name
menu_json['n_courses'] = menu.number_of_courses
menu_json['price'] = menu.price
results.append(menu_json)
data = json.dump(results)
else:
data = 'fail'
mimetype = 'application/json'
return HttpResponse(data, mimetype)
And lastly this is the function that is supposed to use JQueryUI to make the ajax call and retrieve the possible menu's
autocompleteMenu.js
$(function() {
$("#menu").autocomplete({
source: "/orders/getMenus/",
});
});
As you can probably see from the getMenus() function in views.py I also print a check line ("I am called"), which sure enough does not get printed on console. Also even by switching the autocomplete() source parameter to a local array there is no result.
I do feel like I am doing some very naive mistake but I really cannot seem to figure it out (I am also pretty new with JQuery).
I think the error should be in the provided files, but I'll be happy to post edits in just in case
Thank you in advance!
I realized that the problem was due to the fact that I had to bind autocomplete to the id of the newly created id's (which I changed to classes). Also the JSON data must have a lable field, (and I had to use json.dumps(), not json.dump() :p).
The followings did the trick:
createOrderIn.js
$(document).ready(function () {
var previous = 0;
var considered = 0;
$("#people").keyup(function ( ) {
var actual = this.value;
if(actual==null){
actual=1;
}
var toAdd = actual-previous;
previous = actual;
if(toAdd > 0){
for(var i=0; i<toAdd; i++){
considered+=1;
var htmlToAdd = $("<div class="+considered+"><input type=\"text\" name=\"menu_"+considered+"\" class=\"menu\"><input type=\"text\" name=\"drink_"+considered+"\" value=\"No drink\" class=\"drink\"><br></div>");
$("#the-form").append(htmlToAdd);
$('#the-form').find('input[class=menu]:last').autocomplete({
source: "/orders/getMenus"
});
$('#the-form').find('input[class=drink]:last').autocomplete({
source: "/orders/getDrinks"
});
}
}
else{
for(var j=0; j<(-1*toAdd); j++) {
if (considered > 0) {
$("."+considered).remove();
considered -= 1;
}
}
}
});
});
views.py
def getDrinks(request):
if request.is_ajax():
q = request.GET.get('term', '')
drinks = Drink.objects.filter(name__contains=q)
results=[]
for drink in drinks:
drink_json = {}
drink_json['label'] = drink.name
results.append(drink_json)
data = json.dumps(results)
else:
data = 'fail'
mimetype = 'application/json'
return HttpResponse(data, mimetype)
def getMenus(request):
if request.is_ajax():
q = request.GET.get('term', '')
menus = Menu.objects.filter(name__contains=q)
results=[]
for menu in menus:
menu_json = {}
menu_json['label'] = menu.name
menu_json['id'] = menu.number_of_courses
results.append(menu_json)
data = json.dumps(results)
else:
data = 'fail'
mimetype = 'application/json'
return HttpResponse(data, mimetype)

Node server to echo POST/URL parameters in real time

I'm working on a project where I'm sending temperature data via Arduino to a Node server. Arduino sends data to the server through URL parameters:
http://localhost:3000/submit?temprature=25
I'm then fetching the posted data using the following Node server.js
var express = require('express');
url = require('url');
var app = express();
app.get('/submit', function(req, res){
var data = url.parse(req.url,true).query;
console.log(data);
});
app.listen(3000, function(){
console.log('listening on *:3000');
});
I'm able to show the required data with console.log(), but what I want is, as soon as Arduino sends the data through URL parameters, that data should automatically echo/print on the server: http://localhost:3000/index.html like in real time. How can I achieve this?
You can use socket.io to emit events every time the temperature is updated by your arduino device:
var http = require('http');
var url = require('url');
var express = require('express');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server); //pass a http.Server instance
server.listen(3000);
app.get('/submit', function(req, res){
var data = url.parse(req.url,true).query;
io.emit('temperature', data);
res.send('Temperature Updated to: ' + data.temperature);
});
app.get('/index', function(req, res){
res.sendFile(__dirname + '/public/index.html');
});
Then on the client side, you can listen for events and update the information. This is public/index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Socket.IO Temperature Example</title>
<link rel="stylesheet" href="style.css">
<script src="https://cdn.socket.io/socket.io-1.3.5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js"></script>
</head>
<body>
<h1 id="temperature"></h1>
<script>
var socket = io('http://localhost:3000');
socket.on('temperature', function (data) {
console.log(data);
$('h1#temperature').html(data.temperature);
});
</script>
</body>
</html>

Resources