Python communication between Arduino and RaspberryPi - python

I developed a tiny webserver on Python. Its aim is to translate an URL's parameters (such as http://192.168.0.17:6066/?rly=7&status=1&port=ttyUSB0) in an command (here RLY71) and write it on a serial port (here /dev/ttyUSB0), where the Arduino is connected.
Here is the WebServer code (many many "print" for debugging purpose) :
__author__ = 'deadbird'
import time
import BaseHTTPServer
from urlparse import urlparse, parse_qs
import serial
from time import sleep
HOST_NAME = '192.168.0.17'
PORT_NUMBER = 6066
class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_HEAD(s):
s.send_response(200)
s.send_header("Content-type", "text/html")
s.end_headers()
def do_GET(s):
port = -1
status = -1
rly = -1
"""Respond to a GET request."""
s.send_response(200)
s.send_header("Content-type", "text/html")
s.end_headers()
s.wfile.write("<html><head><title>Piscine</title></head>")
parameters = parse_qs(urlparse(s.path).query)
if parameters.has_key('rly'):
rly = parameters['rly'][0]
if parameters.has_key('status'):
status = parameters['status'][0]
if parameters.has_key('port'):
port = parameters['port'][0]
if port != -1 and status !=-1 and rly !=-1:
#ser = serial.Serial("/dev/ttyUSB0")
#ser.write("RLY11\n")
#ser.close()
try:
print "All parameters ok, sending command\n"
print "Opening port: {0}".format(port)
ser = serial.Serial("/dev/{0}".format(port), 9600, timeout=1)
print "Opened port \'{0}\'".format(ser.name)
if ser.isOpen():
print "Port successfully opened"
print "isWritable = {0}".format(ser.writable())
else:
print "Cannot open port :("
command = "RLY{0}{1}".format(rly, status)
print "Command = \'{0}\'".format(command)
print "Writing command on serial port"
written = ser.write("RLY{0}{1}\n".format(rly, status))
print "Bytes written = {0}".format(written)
print "Reading result"
ret = ser.readline()
if len(ret) == 0:
s.wfile.write("NOTHING DONE")
else:
print ret
s.wfile.write(ret)
ser.flushOutput()
ser.flushInput()
ser.close()
except (serial.SerialException, serial.SerialTimeoutException) as e:
s.wfile.write(e)
s.wfile.write("</body></html>")
if __name__ == '__main__':
server_class = BaseHTTPServer.HTTPServer
httpd = server_class((HOST_NAME, PORT_NUMBER), MyHandler)
print time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER)
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
print time.asctime(), "Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER)
This work perfectly on a Mac with PySerial installed. When I run the very same script on a RaspberryPi, nothing happens. For example, when I use the URL http://192.168.0.17:6066/?rly=7&status=1&port=ttyUSB0, the result on the console is the following:
192.168.0.16 - - [19/Apr/2014 20:59:28] "GET /?rly=7&status=1&port=ttyUSB0 HTTP/1.1" 200 -
All parameters ok, sending command
Opening port: ttyUSB0
Opened port '/dev/ttyUSB0'
Port successfully opened
isWritable = True
Command = 'RLY71'
Writing command on serial port
Bytes written = 6
Reading result
192.168.0.16 - - [19/Apr/2014 20:59:30] "GET /favicon.ico HTTP/1.1" 200 -
I tried chmown-ing the port to user "pi", chmod-ing it to 777, nothing changes.
I ran some more tests. I wrote this stripped down version if the script:
import serial
ser = serial.Serial("/dev/ttyUSB0")
ser.write("RLY11\n")
ser.close()
When I run it as a .py file, is fails. But when I run it from a command-line using python interactive shell (ie: line per line), it works! I have absolutely no idea of what to do, can someone help?

Found out what was wrong, but can't explain why. Now I open the serial port at the very beginning and close it right after httpd.server_close(). Now it works perfectly, but I cannot explain the reason.

Related

Port Scanner written in python does not display output normally

So I tried to write a port scanner in python3
Here is my code:
import sys #allows us to enter command line arguments, among other things
import socket
from datetime import datetime
if len(sys.argv) == 2:
target = socket.gethostbyname(sys.argv[1]) #Translate a hostname to IPv4
else:
print("Invalid amount of arguments.")
print("Syntax: python3 scanner.py <ip>")
sys.exit()
#Add a banner
print("-" * 50)
print("Scanning target "+target)
print("Time started: "+str(datetime.now()))
print("-" * 50)
try:
for port in range(50,85):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.setdefaulttimeout(1)
result = s.connect_ex((target,port)) #returns error indicator
print("Checking port {}".format(port))
if result == 0:
print("Port {} is open".format(port))
s.close()
except KeyboardInterrupt:
print("\nExiting program.")
sys.exit()
except socket.gaierror:
print("Hostname could not be resolved.")
sys.exit()
except socket.error:
print("Couldn't connect to server.")
sys.exit()
using Kali Linux 2020.2, with the newest version of python,
I executes python3 scanner.py google.com
It is expected that the scanner will display "Checking port 50", "Checking port 51" one by one during the scanning process.
And if it find any one of the ports is open, it shows "Port xx is open" after the "Checking port xx"
However, my scanner was stuck as the initial banner.
And eventually when it has completed the scanning, it displays all the output in one go.
Can anyone please tell me how can I solve this problem?
Just switch the following lines in your code:
result = s.connect_ex((target,port)) #returns error indicator
print("Checking port {}".format(port))
becomes:
print("Checking port {}".format(port))
result = s.connect_ex((target,port)) #returns error indicator

Python Port Scanner Stuck In Loop

I've been following a guide on how to make a simple port scanner, I am trying to scan my own IP but it gets stuck in a loop and prints no ports. It's hard to figure out at it gives no errors and gets stuck in a loop.
Any help would be greatly appreciated.
import socket
import subprocess
import sys
from datetime import datetime
#clears the shell screen
subprocess.call('clear', shell=True)
#ask for input
remoteServer = raw_input("Please enter a host to scan:")
remoteServerIP = socket.gethostbyname(remoteServer)
#print a banner saying we are scanning
print "-" * 60
print "now scanning your host...", remoteServerIP
print "-" * 60
#Check what time the scan started
t1 = datetime.now()
# Using the range function to specify which ports (1 - 1025)
#Errors.
try:
for port in range(1, 1025):
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
result = sock.connect_ex((remoteServerIP, port))
if result == 0:
#if the socket is listening it will print out the port
print("Port{}:\t Open".format(port))
sock.close()
except KeyboardInterrupt:
print "You pressed ctrl+c"
sys.exit()
except socket.gaierror:
print 'Hostname could not be resolved to IP. Exiting'
sys.exit()
except socket.error:
print "couldn't connect to server"
sys.exit()
# checking the time again
t2 = datetime.now()
#calculates the differnce of time, to see how long it took to run the script
total = t2 - t1
#printing the info to screen
print "scanning compelte in :", total
You can use sock.timeout(0.1) so it will no wait for connection.
I put print port to see which port is scanned.
You can try with 8.8.8.8 - without sock.timeout(0.1) it hang on first port.
Maybe you have good secured computer and it blocks connections to close ports.
import sys
from datetime import datetime
import socket
#ask for input
remoteServer = raw_input("Please enter a host to scan: ")
remoteServerIP = socket.gethostbyname(remoteServer)
#print a banner saying we are scanning
print "-" * 60
print "now scanning host ...", remoteServerIP
print "-" * 60
#Check what time the scan started
t1 = datetime.now()
# Using the range function to specify which ports (1 - 1025)
#Errors.
try:
for port in range(1, 1025):
print port
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.settimeout(0.1)
result = sock.connect_ex((remoteServerIP, port))
if result == 0:
#if the socket is listening it will print out the port
print("Port {:4d}: Open".format(port))
sock.close()
except KeyboardInterrupt:
print "You pressed ctrl+c"
sys.exit()
except socket.gaierror:
print 'Hostname could not be resolved to IP. Exiting'
sys.exit()
except socket.error:
print "couldn't connect to server"
sys.exit()
# checking the time again
t2 = datetime.now()
#calculates the differnce of time, to see how long it took to run the script
total = t2 - t1
#printing the info to screen
print "scanning compelte in:", total
BTW:
You can compare your results with results from tools like nmap
See scapy - python module to work with network packages. (book: Black Hat Python)
At least on my machine (Ubuntu 16.something) it does work. Output:
Please enter a host to scan:localhost
------------------------------------------------------------
now scanning your host... 127.0.0.1
------------------------------------------------------------
Port21: Open
Port22: Open
Port25: Open
Port80: Open
Port139: Open
Port443: Open
Port445: Open
Port631: Open
scanning compelte in : 0:00:00.047478
However, it only scans ports 1-1024, while ports go up to 65535.
To make it scan all the ports, change for port in range(1, 1025): to for port in range(1, 65536):

python processes script not returning the same answer as direct bash command

hey first time question asker hope this is the correct format
i have a python scirpt which is trying to basically to use a bash command in this case telnet
this is the script
import subprocess
proc = subprocess.Popen(['/bin/bash'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
stdout = proc.communicate('telnet 192.168.1.67 5555')
print (stdout)
i have a script on my other machine listening on port 5555
and the calling the script in bash returns
Connection closed by foreign host.
("Trying 192.168.1.67...\nConnected to 192.168.1.67.\nEscape character is '^]'.\n", None
and my other computer recognizes a connection but it closes the connection immediately
while when i run the command
telnet 192.168.1.67 5555
it works fine and keeps the connection open
my question is how to i write a script which dose the same thing as the command "telnet 192.168.1.67 5555" and keeps the connection open?
You can use socket — Low-level networking interfac
See the Python module of the week about socket.
Python 2 Example:
import socket, select, string, sys
if(len(sys.argv) < 3) :
print 'Usage : python telnet.py hostname port'
sys.exit()
host = sys.argv[1]
port = int(sys.argv[2])
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
# connect to remote host
try :
s.connect((host, port))
except :
print 'Unable to connect'
sys.exit()
print 'Connected to remote host'
while 1:
socket_list = [sys.stdin, s]
# Get the list sockets which are readable
read_sockets, write_sockets, error_sockets = select.select(socket_list , [], [])
for sock in read_sockets:
#incoming message from remote server
if sock == s:
data = sock.recv(4096)
if not data :
print 'Connection closed'
sys.exit()
else :
#print data
sys.stdout.write(data)
#user entered a message
else :
msg = sys.stdin.readline()
s.send(msg)

Problems with a chat program written in Python and PyGTK

I am new to python and I am currently working on a chat room program in Python (still in progress...). I have also made a GUI for my program. Initially, I made two py files, one for the GUI and one for the chatting function. They both worked perfectly when separated. After, I combined the two files. I faced the following two problems:
One of my threads (target = loadMsg) is used to wait for the host's msg and print it out on the screen. The problem is that it delays for one msg every time. For example, I sent a "1" to the host and the host should return a "1" immediately. But, the "1" I received didn't appear on my screen. Then I send a "2" to the host and the host should reply a "2" immediately. Then, my screen shows a "1" but the "2" is still missing until the host reply a "3" to me, after I send a "3" to the host. Where is the problem?
This is a technical problem. I was testing the stability of the chat room and I found that about 10% of my msg disappeared during the transmission and this situation occurs randomly. How can I fix such a problem?
Sorry for my poor English. I hope someone can help me with it.T_T
Here is my code for your reference:
---Client
import pygtk,gtk
import logging
from threading import *
import socket
DEBUG = 1
HOST = ''
PORT = 8018
TIMEOUT = 5
BUF_SIZE = 1024
class Base():
def reload(self):
try:
buf = self.sock.recv(BUF_SIZE)
print buf
self.addMsg(buf)
except:
pass
def reload_butt(self,widget):
try:
self.thread = Thread(target=self.reload)
self.thread.start()
except:
pass
def loadMsg(self):
try:
while True :
buf = self.sock.recv(BUF_SIZE)
print buf
self.addMsg(buf)
except:
self.sock.close()
def sendMsg(self,widget):
if DEBUG : print "Send Msg"
if self.entry.get_text() : self.sock.send(self.entry.get_text())
self.entry.set_text("")
def addMsg(self,string):
if DEBUG : print "Try to add Msg"
if self.entry.get_text() :
iter = self.buffer1.get_iter_at_offset(-1)
self.buffer1.insert(iter,("\n Username: "+string))
self.entry.set_text("")
self.adj = self.scrolled_window.get_vadjustment()
self.adj.set_value( self.adj.upper - self.adj.page_size )
if DEBUG : print "Add msg ok"
def destroy(self,widget):
if DEBUG : print "Destroy function called"
self.sock.close()
gtk.main_quit()
def __init__(self,sock):
if DEBUG : print "Initializing..."
self.sock = sock
self.win=gtk.Window()
self.win.connect("destroy",self.destroy)
self.vbox=gtk.VBox()
self.win.add(self.vbox)
self.view=gtk.TextView()
self.view.set_editable(False)
self.buffer1=self.view.get_buffer()
self.scrolled_window=gtk.ScrolledWindow()
self.scrolled_window.set_policy(gtk.POLICY_AUTOMATIC,gtk.POLICY_AUTOMATIC)
self.scrolled_window.add(self.view)
self.vbox.add(self.scrolled_window)
self.entry=gtk.Entry()
self.entry.connect("activate",self.sendMsg)
self.enter=gtk.Button("Enter")
self.enter.connect("clicked",self.sendMsg)
self.reload=gtk.Button("Reload")
self.reload.connect("clicked",self.reload_butt)
self.hbox=gtk.HBox()
self.hbox.add(self.entry)
self.hbox.pack_start(self.reload,False,False)
self.hbox.pack_start(self.enter,False,False)
self.vbox.pack_start(self.hbox,False,False)
self.win.show_all()
if DEBUG : print "Finish initializing"
def main(self):
try :
gtk.main()
except :
print "Error!!!"
def main() :
try :
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST, PORT))
print ('Connecting to '+ str(HOST) +' ' + str(PORT))
base=Base(sock)
thread1=Thread(target=base.loadMsg)
thread2=Thread(target=base.main)
thread2.start()
thread1.start()
except :
print "Err0r!!!"
sock.close()
main()
---host (an echo host)
import socket
HOST = ''
PORT = 8018
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(5)
conn, addr = s.accept()
print 'Connected by', addr
try :
print "Start!"
while True:
data = conn.recv(1024)
print data
reply = data # echo
if not reply : break
if reply== "!q" :
conn.close()
break
conn.send(reply)
conn.close()
except :
print "Error!!!!!"
conn.close()
I would seriously recommend to use the gio library (part of glib). Using that library, you connect functions to the socket operations such as when data is available, or when data can be written to the socket. The library will call these function when necessary, and you don't need a wait loop. Which is more CPU-friendly.
http://jcoppens.com/soft/howto/gtk/chat_socket.php contains an example of communications between a C program and Python, using gio, which might be useful to you.
This way, you can start monitoring the sockets after the GUI has started, and you do not need threads to attend the communications.

IOS smallSocket and python

I'm working on an IOS app.
I'm starting with a python server on mac that should connect to an iphone and print data sent from iphone.
the connection seems to be established but python print infinite " b " " as data... I don't know why.
the strange thing is that it happens also with cocoaAsynchronousSocket
this is the server
#!/usr/bin/python
import time
import socket
import sys
addr = sys.argv[1]
port = 4444
if not addr :
print ("No host address specified, plese specify an address", files=sys.stderr)
sock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
print ("connecting...")
try:
sock.connect ((addr, port))
except socket.error:
print ("unable to connect to", addr)
sys.exit(0)
print ("Connected to", addr)
while 1:
data = sock.recv(0)
data2 = sock.recv(1)
# if not data: break
print (data)
print (data2)
and this is some code that i use to create the connection
- (IBAction)openPressed:(id)sender {
socket = [Socket socket];
[socket listenOnPort:4444];
[socket acceptConnection];
[socket writeString:#"connection accepted"];
}
Why did u add this line:
data = sock.recv(0)
Besides that, your sever, while client might be a better name, seems good.
If it doesn't print what you expect, I suggest that you use some sniffer tools, like wireshark, to check what it really receives.

Categories