I am working on a program where connecting over SSH to a raspberry pi is necessary to run the program through my GUI app window in python, here is what I have right now to "test" ssh connections on all devices but i have to type in the actual IP of the pi itself. I need to make this where it just tests connection of everything on the network and connects to the available device.
Any help?
def raspi_connecter():
for n in range(1, 255):
server_ip= "10.0.0.153".format(n)
subprocess.Popen('ssh' + ' ' + 'dev#' + server_ip, shell= True)
Here's python2 program (I've never reworked it for python3) that finds your Raspberries. It runs nmap to create XML output then crudely parses that.
It needs the iproute module sudo apt install python{,3}-pyroute
#!/usr/bin/python2
from pyroute2 import IPRoute
import socket
import subprocess
import xml.etree.ElementTree as ET
ip = IPRoute()
for x in ip.get_addr(label='eth0',family=socket.AF_INET):
ipa =x.get_attr('IFA_ADDRESS')+"/"+str(x['prefixlen'])
print ipa
process = subprocess.Popen(['sudo','nmap','-oX', '/tmp/nmap.xml','-sn',ipa],stdout=subprocess.PIPE)
process.wait()
tree = ET.parse('/tmp/nmap.xml')
for node in tree.iter('address'):
try:
if node.attrib['addrtype'] == "ipv4":
ip = node.attrib['addr']
except:
pass
try:
if node.attrib['vendor'] == "Raspberry Pi Foundation":
print "IP:", ip
except:
pass
Once you have an IP address for a Raspberry then you can run ssh with subprocess (or ping or netcat). It will need additional testing for Raspberry Pi 4 and Pi400 devices (as I don't have either of those (which use the new MAC OUI).
I want to implement an IoT application. I will give here a toy version of what I want to do.
Say I have two clients : 'client1' and 'client2' on REMOTE COMPUTERS, and a server 'server', that regulates the computations. The hard thing for me is the fact that the computations can't be made at the same place.
We have : clients_list = ['client1', 'client2']
I want to simulate an algorithm that looks like this:
The server starts with an initial value server_value
for round in range(R):
client_values_dict = {}
for client_id in clients_list:
server broadcasts server_value to the client 'client_id' # via http
client_value = action(server_value) # executed on clients computer
client broadcasts its value to the server # via http
at the meantime, server waits for the response
server fills dictionary with keys clients_list, values client values obtained with 'action' :
client_values_dict[client_id]
server_value = aggregate(client_values_dict) # executed on server computer
On the client side (in client.py), I have a function:
import time
def action(server_value):
time.sleep(10*random.random())
return server_value + random.random()-0.5
On the server side (in server.py), I have a function:
def aggregate(client_values_dict):
return sum(client_values_dict.values())/len(client_values_dict.values())
I want to implement that : I want to write a loop at server level that performs this. I think what I need is an API to handle client-server interactions and parallel computing.
I thought of using Flask for this but I'm afraid that the loop at server level will be blocked by the app.run(debug=True) loop, and that my code won't run until I break the app with CTRL+C.
I want the computations to be made in parallel by the two clients.
I am not familiar with web developpement, my problem might seem trivial and help is probably to be found everywhere on internet, but I don't know where to look at. Any help is cheerfully welcomed.
Here is an example ofa script that simulates what I want, but online.
# -*- coding: utf-8 -*-
import time
import random
server_value = 0
R = 10
clients_list = ['client1', 'client2']
def action(server_value):
time.sleep(3*random.random())
return server_value + random.random()-0.5
def aggregate(client_values_dict):
return sum(client_values_dict.values())/len(client_values_dict.values())
for round in range(R):
client_values_dict = {}
for client_id in clients_list:
client_value = action(server_value) # executed on clients computer
client_values_dict[client_id] = client_value
server_value = aggregate(client_values_dict)
print(server_value)
Have you tried network zero? It's an amazing networking library that I use all the time.
Install:
pip install networkzero
PyPI link: https://pypi.org/project/networkzero/
Docs: https://networkzero.readthedocs.io/en/latest/
Code sample (from their doc page):
Machine/process A:
import networkzero as nw0
address = nw0.advertise("hello")
while True:
name = nw0.wait_for_message_from(address)
nw0.send_reply_to(address, "Hello " + name)
Machine/process B:
import networkzero as nw0
hello = nw0.discover("hello")
reply = nw0.send_message_to(hello, "World!")
print(reply)
reply = nw0.send_message_to(hello, "Tim")
print(reply)
This library also supports more than just 2 connections on the local WiFi, read the docs for more info.
NOTE: I've used this answer before. You can see it here: How to set up a server for a local wifi multiplayer game for python
My requirement is ability to run a PowerShell script on a Windows 2012 server remotely, this has to be triggered from a Linux server using Python script.
Need suggestions on best way to handle this and also sample code (if possible).
Below are the steps I intend to achieve but i see it's not working as expected.
PowerShell scripts to be executed are already placed in Windows server (2012).
Python3 program running on Linux (CentOS) does SSH to Windows server (2012) using netmiko module.
sends the command (PowerShell command to execute script in remote Windows server) over the SSH connection.
I was able to connect to the remote Windows server using Python. But I don't see this method working as expected.
Need an effective and efficient way to achieve this.
from netmiko import ConnectHandler
device = ConnectHandler(device_type="terminal_server",
ip="X.X.X.x",
username="username",
password="password")
hostname = device.find_prompt()
output = device.send_command("ipconfig")
print (hostname)
print (output)
device.disconnect()
Nothing much is done for 'terminal_server" device type. You have to do manual passing at the moment.
Below is extracted from COMMON_ISSUES.md
Does Netmiko support connecting via a terminal server?
There is a 'terminal_server' device_type that basically does nothing post SSH connect. This means you have to manually handle the interaction with the terminal server to connect to the end device. After you are fully connected to the end network device, you can then 'redispatch' and Netmiko will behave normally
from __future__ import unicode_literals, print_function
import time
from netmiko import ConnectHandler, redispatch
net_connect = ConnectHandler(
device_type='terminal_server', # Notice 'terminal_server' here
ip='10.10.10.10',
username='admin',
password='admin123',
secret='secret123')
# Manually handle interaction in the Terminal Server
# (fictional example, but hopefully you see the pattern)
# Send Enter a Couple of Times
net_connect.write_channel("\r\n")
time.sleep(1)
net_connect.write_channel("\r\n")
time.sleep(1)
output = net_connect.read_channel()
print(output) # Should hopefully see the terminal server prompt
# Login to end device from terminal server
net_connect.write_channel("connect 1\r\n")
time.sleep(1)
# Manually handle the Username and Password
max_loops = 10
i = 1
while i <= max_loops:
output = net_connect.read_channel()
if 'Username' in output:
net_connect.write_channel(net_connect.username + '\r\n')
time.sleep(1)
output = net_connect.read_channel()
# Search for password pattern / send password
if 'Password' in output:
net_connect.write_channel(net_connect.password + '\r\n')
time.sleep(.5)
output = net_connect.read_channel()
# Did we successfully login
if '>' in output or '#' in output:
break
net_connect.write_channel('\r\n')
time.sleep(.5)
i += 1
# We are now logged into the end device
# Dynamically reset the class back to the proper Netmiko class
redispatch(net_connect, device_type='cisco_ios')
# Now just do your normal Netmiko operations
new_output = net_connect.send_command("show ip int brief")
Environment: Python v2.x in Windows OS.
Question: I am using COM4 to communicate with a robot. I notice that I cannot get complete return in my Python code when I send "getver(ion)" cmd to robot.
To be specific, my current code is:
########## open COM4
ser = serial.Serial(3)
########## send cmd 'getver'
ser.write ("testmode on \n")
ser.write ("getver \n")
print ser.read()
########### return
Component,Major,Minor,Build,Aux
APPassword,956FC721
BaseID,1.2,1.0,18000,2000,
BatteryType,4,LIION_4CELL_SMART,
Beehive URL, beehive.cloud.com
BlowerType,1,BLOWER_ORIG,
Bootloader Version,27828,,
BrushMotorType,1,BRUSH_MOTOR_ORIG,
BrushSpeed,1400,,
BrushSpeedEco,800,,
ChassisRev,1,,
Cloud Selector, 2
However, the right return is this:
Component,Major,Minor,Build,Aux
APPassword,956FC721
BaseID,1.2,1.0,18000,2000,
BatteryType,4,LIION_4CELL_SMART,
Beehive URL, beehive.cloud.com
BlowerType,1,BLOWER_ORIG,
Bootloader Version,27828,,
BrushMotorType,1,BRUSH_MOTOR_ORIG,
BrushSpeed,1400,,
BrushSpeedEco,800,,
ChassisRev,1,,
Cloud Selector, 2
DropSensorType,1,DROP_SENSOR_ORIG,
LCD Panel,137,240,124,
LDS CPU,F2802x/c001,,
LDS Serial,KSH13315AA-0000153,,
LDS Software,V2.6.15295,0000000001,
LDSMotorType,2,LDS_MOTOR_MABUCHI,
Locale,1,LOCALE_USA,
MagSensorType,1,MAG_SENSOR_ORIG,
MainBoard Serial Number,OPS13115,544a1696de32,
MainBoard Version,1,,
Model,BotVacConnected,905-0143,
QAState,QA_STATE_APPROVED
Serial Number,KSH13715,544a1696de32,P
SideBrushPower,1500,,
SideBrushType,2,SIDE_BRUSH_VORWERK_REV1,
SmartBatt Data Version,2048
SmartBatt Device Chemistry,LION
SmartBatt Device Name,F164A1028
SmartBatt Manufacturer Name,Panasonic
SmartBatt Mfg Year/Month/Day,2095,10,6
SmartBatt Serial Number,14592
SmartBatt Software Version,1280
Software,2,0,0,46,28146
UI Board Hardware,0,0,
UI Board Software,1,3,
UI Name,Davinci
UI Version,1.0.0
VacuumPwr,80,,
VacuumPwrEco,65,,
WallSensorType,1,WALL_SENSOR_ORIG,
WheelPodType,1,WHEEL_POD_ORIG,
As you can see, the return from python is not complete, um...then how to display the full info? Thanks in advance.
I know some electronics and robotics, but I cannot predict what exact could happen, so I have some ideas to check only ;)
1) I wonder to know what did you get when call recieve again. I think it could help.
2) set exact bytes to recieve in read() method.
it is described here,
TL;DR below:
While True:
bytesToRead = ser.inWaiting()
ser.read(bytesToRead)
3) Try to initialize Serial object with timeout = None - maybe it just waits, or default is too small ;)
I will edit that when you check that sth not working, and if I will have new idea.
Regards and sorry for my English.
I have a python script that I want to use to configure some XBee modules. It works perfectly find when connect to a computer via an xbee development board, but fails when connect to a raspberry pi via the slice of pi board.
I have narrowed down the problem to it failing to enter the command mode, after sending the +++ the xbee never sends the OK message. Here is the relevant code:
...
CC = '+'
GT = '1.1' # Tried different values here
...
def startCommandMode(self):
self.emptyBuffer() # Tried with and without this line
sleep(self.GT) # Tried with and without this line
self.ser.write(self.CC + self.CC + self.CC)
sleep(self.GT)
return self.getReply() == 'OK'
...
def getReply(self):
count = 0
reply = ''
while True:
char = self.ser.read()
if char == '\r':
break
if len(char) == 0:
return None
reply += char
return reply
The full source is available on github if needed.
I know it is not a problem with the xbee module, the raspberry pi or the slice of pi board as it works perfectly fine if I try it manually using "picocom -lc /dev/ttyAMA0".
Some things to check:
Are you getting anything in response?
Have you enabled flow-control on the XBee? Make sure D6 and D7 are set to 0 since the Raspberry Pi serial port doesn't have flow control.
Is the Python code configured for flow control? It might be waiting for a CTS signal that is never asserted.
Can you try using the XBee Development Board on the Raspberry Pi's USB port?
Use the following:
....
if args.common:
args.at = ['ID', 'CH', 'MY', 'DL', 'DH', 'AP'] + args.at
xbee = XBee(args.port, args.baud);
sleep(2)
xbee.CC = args.CC
xbee.GT = args.GT
....
....
IMHO I thick Rpi need more time to initialize serial port, thats why I am using this delay
. Also is applicable for transparent mode so add a delay after port init.
I hope this will Ok for you. For me it is solved.
BR.
Manel.