sleep() function (python) - python

if data.find('!google') != -1:
nick = data.split('!')[ 0 ].replace(':','')
try:
gs = GoogleSearch(args)
gs.results_per_page = 1
results = gs.get_results()
for res in results:
sck.send('PRIVMSG ' + chan + " " + res.title.encode("utf8") + '\r\n')
sck.send('PRIVMSG ' + chan + " " + res.url.encode("utf8") + '\r\n')
print
except SearchError, e:
sck.send('PRIVMSG ' + chan + " " + "Search failed: %s" % e + " " + '\r\n')
Ok I'm trying to make the script wait a few seconds before another user can "!google" to prevent users from flooding the channel or the bot, not sure if I should use the sleep() function because that might stop the whole script, I just want to make it wait a few seconds before anyone can use "!google" again.

There is a sleep function inside the time module.
However, to make your script not block, you can call the time function in the time module and store that. If the current time is less than that plus, say, five seconds, don't allow them to use it.
For example:
last_google = 0
# somewhere later in the script where last_google is still in scope...
if data.find('!google') != -1:
if last_google + 5 < time.time():
# throttled
return
last_google = time.time()
# do something here

Related

Python Netmiko OSError: Search pattern never detected in send_command_expect:

I recently started programming with Python. I work as a network engineer and am currently building a program to pull "state dumps" from Ciena devices. I use netmiko to connect to the device.
Now I always get the following error:
OSError: Search pattern never detected in send_command_expect: 5160_1>
"5160_1>" is the hostname / prompt on the switch. I have read that I can give "expect_string" to a "send_command". Unfortunately, this has no effect and I still get this error.
This is the function with which I create the state dump and call the function for the file download.
def create_sd():
for ip in sw_connect_ips:
try:
sw_connection = ConnectHandler(device_type=sw_dev_type, host=ip, username=sw_usr, password=sw_pw)
try:
print('\nconnnected to host > ' + ip + '\n')
hostname = sw_connection.find_prompt()
print('hostname of device > ' + hostname)
sw_connection.send_command('system server sftp enable', expect_string=hostname)
sw_connection.send_command('configuration save', expect_string=hostname)
sw_output = sw_connection.send_command('system state-dump file-name ' + ip + '_sd_timestamp_' + str(date.hour) + '_' + str(date.minute) + '_' + str(date.second), expect_string=hostname + ' ')
filename = ip + '_sd_timestamp_' + str(date.hour) + '_' + str(date.minute) + '_' + str(date.second)
print('got state-dump ' + filename + ' from host > ' + ip)
logging.debug(sw_output)
logging.debug(sw_connection)
sw_connection.disconnect()
try:
sftp_get(filename, ip)
except:
raise Exception('scp failed')
except:
raise Exception('command does not exist on switch > ' + ip)
except:
raise SSHException('unable to connect to switch check username, password and ip address')
I don't know whether all exceptions make so much sense. Maybe someone has a tip for me.
Thanks in advance.
Edit: What is strange in my opinion is that it only occurs with some switches.
in the command with which the state dump is created, I have increased the "send_command" delay factor to 5.
sw_output = sw_connection.send_command ('system state-dump file-name' + ip + '_sd_timestamp_' + str (date.hour) + '_' + str (date.minute) + '_' + str (date.second) , expect_string = hostname, delay_factor = 5)
As a result, I no longer get a netmiko exception and the program runs without problems.

Why is python looping creating double results?

I have 3 lat/lngs and a URL that I am constructing. My output should be 3 URLs, for each lat/lng, I am receiving 6. What do I need to change in my code below to print 3 URLs instead of 6? The try block and first for loops start are error handling, if the script fails, try twice. I am getting 6 values even when the script does not fail.
def main():
for i in range(2):
for attempts in range (1):
try:
for lat, lon, id_, startDate, endDate in zip(latval, lonval, idVal, startDayValStr, endDayValStr):
time_param = '?start='+ startDate +'T'+ "01:00" + 'Z' + '&end='+ endDate + 'T' + "23:00" + 'Z'
hrPrecip = 'https://insight.api.wdtinc.com/hourly-precipitation/' + str(lat)+'/' + str(lon) + time_param + '&unit=inches'
print hrPrecip
except Exception as e:
attempts = i + 1
sleep(30)
print "now trying attempt #" + " " + str(attempts) + " " + "for error" " " + str(e)
print(traceback.format_exc())
logging.exception(e)
msg = "PYTHON ERRORS:\nTraceback info:\n" + traceback.format_exc()
logging.debug("sending error email")
emailserver.email_error_msg(msg)
if __name__ == "__main__":
main()
Output:
https://insight.api.wdtinc.com/hourly-precipitation/44.797207/-95.175648?start=2019-05-13T01:00Z&end=2019-05-13T23:00Z&unit=inches
https://insight.api.wdtinc.com/hourly-precipitation/44.796302/-95.180946?start=2019-05-13T01:00Z&end=2019-05-13T23:00Z&unit=inches
https://insight.api.wdtinc.com/hourly-precipitation/44.778728/-95.23022?start=2019-05-13T01:00Z&end=2019-05-13T23:00Z&unit=inches
https://insight.api.wdtinc.com/hourly-precipitation/44.797207/-95.175648?start=2019-05-13T01:00Z&end=2019-05-13T23:00Z&unit=inches
https://insight.api.wdtinc.com/hourly-precipitation/44.796302/-95.180946?start=2019-05-13T01:00Z&end=2019-05-13T23:00Z&unit=inches
https://insight.api.wdtinc.com/hourly-precipitation/44.778728/-95.23022?start=2019-05-13T01:00Z&end=2019-05-13T23:00Z&unit=inches`
It could be the try: and except: block. failing in the first. I am guessing you do not need the second loop with attempt in range(1). In fact you do not need any loop here.

Using Python 3.4 to Ping a network then report address, dns name, etc.

I wanted to create a Python program that does several things. Ping all addresses in a predefined network, gather the DNS information, write a file with IP address, DNS name, ping fail or pass, date. Then run and email the resulting file to myself once a week, every Friday. I have created this program and will post my own answer. I am new to Python and was able to get this written with the help from other answers posted on this site. Thanks to all those who contributed answers on this site. Hope the answer I post will help someone else.
#!/usr/bin/python3.4
#Above statement makes sure you are using version 3.4
#when multiple versions are installed. has to be the 1st line.
# Import modules
import subprocess
import socket
import errno
import time
import datetime
import ipaddress
today = datetime.date.today()
# define DNS lookup and error handling
# return none,none,none needed otherwise if no DNS record
# the routine errors out and the program stops
def lookup(addr):
try:
return socket.gethostbyaddr(addr)
except socket.herror:
return None, None, None
# Prompt the user to input a network address
# commented out the prompt for input so it can run unattended
# net_addr = input("Enter a network address in CIDR
format(ex.192.168.1.0/24): ")
net_addr = ('192.168.1.0/24')
# Create the network
ip_net = ipaddress.ip_network(net_addr)
# Get all hosts on that network
all_hosts = list(ip_net.hosts())
# Configure subprocess to hide the console window
# removed code due to errors not windows linux
# setup online and offline count variables
offCnt = 0
onCnt = 0
# Open file and or create if it doesn't exist.
# file to be overwritten each time the program is run.
file = open("lab-ip.doc","w")
# For each IP address in the subnet,
# run the ping command with subprocess.popen interface
# Grab the DNS information for each IP address
# Print to console add counters and write to file.
for i in range(len(all_hosts)):
output = subprocess.Popen(['ping', '-c', '2', str(all_hosts[i])],
stdout=subprocess.PIPE).communicate()[0]
name,alias,addresslist = lookup(str(all_hosts[i]))
if "Destination Host Unreachable" in output.decode('utf-8'):
print(str(all_hosts[i]), " Ping Fail", str(name), today)
file.write(str(all_hosts[i]) + " Ping Fail - " + str(name) + " " + str(today) + "\n")
offCnt = offCnt + 1
elif "Request timed out" in output.decode('utf-8'):
print(str(all_hosts[i]), " Ping Fail", str(name), today)
file.write(str(all_hosts[i]) + " Ping Fail - " + str(name) + " " + str(today) + "\n")
offCnt = offCnt + 1
else:
print(str(all_hosts[i]), " Ping Pass", str(name), today)
file.write(str(all_hosts[i]) + " Ping Pass - " + str(name) + " " + str(today) + "\n")
onCnt = onCnt + 1
print ("Pass count = ", str(onCnt))
file.write("Pass count = " + str(onCnt))
print ("Fail count = ", str(offCnt))
file.write(" Fail count = " + str(offCnt))
file.close()
# Import yagmail for the actual sending function
import yagmail
yag = yagmail.SMTP('Gmail-id', 'gmail-pswd')
yag.send('email#email.com', subject = "Lab-ip List",contents = 'lab-ip.doc')
yag.send('email2#email2.com', subject = "Lab-ip List",contents = 'lab-ip.doc')
#end

IRC bot - Give voice to registered nicks

I Recently made a IRC bot, the bot should give voice/+v to registered users. But i can't figure out how?
if data.find(' JOIN :' + channel) !=-1:
selfNick = data.split(":")[1].split("!")[0]
if selfNick != botnick:
rawSend("WHOIS :" + selfNick + "\r\n")
reggetNick = "307 " + botnick + " " + selfNick + " :is a registered nick"
if data.find(reggetNick) !=-1:
# MODE #chan +v selfNick
else:
print ""
else:
print ""
Thanks.
You shouldn't check the data at that point, because you know it's the one that contains " JOIN :", rather than " :is a registered nick".
Instead you should wait for another iteration of whatever loop reads your data, and see if you get that message in there.
Bear in mind that it won't come directly afterwards, because you might have sent your WHOIS while other data was still waiting to be read.

Python: IndexError: list index out of range with IRC Bot

I have been making a Python Twitch IRC Bot and it all works besides one issue. About every 20 mins it will crash with the error:
Traceback (most recent call last):
File "E:\Geekster_Bot\Geekster_Bot Code\Geekster_Bot_Test_Write", line 54, in <module>
user = data.split(':')[1]
IndexError: list index out of range
I have researched this and tried several things. But to not prevail.
I am still very new to python, and done everything i know of. This is the code area containing the issue.
data = irc.recv(1204) #gets output from IRC server
user = data.split(':')[1]
user = user.split('!')[0] #determines the sender of the messages
print data
Its the point the incoming data from the IRC gets split. the ':' is the split because this is what is used in the IRC between the Nickname and IRC Message. But. Even without use, it doesn't crash for around 20 mins. With use, it does the same. No crash until after 20 mins.
Any Ideas?
UPDATE
queue = 0 #sets variable for anti-spam queue functionality
newsmsg = 'whitelist'
irc = socket.socket()
irc.connect((server, 6667)) #connects to the server
#sends variables for connection to twitch chat
irc.send('PASS ' + password + '\r\n')
irc.send('USER ' + nick + ' 0 * :' + bot_owner + '\r\n')
irc.send('NICK ' + nick + '\r\n')
irc.send('JOIN ' + channel + '\r\n')
def queuetimer(): #function for resetting the queue every 30 seconds
global queue
print 'queue reset'
queue = 0
threading.Timer(30,queuetimer).start()
queuetimer()
while True:
def message(msg): #function for sending messages to the IRC chat
global queue
queue = queue + 1
print queue
if queue < 20: #ensures does not send >20 msgs per 30 seconds.
irc.send('PRIVMSG ' + channel + ' :' + msg + '\r\n')
else:
print 'Message deleted'
def socialtimer(): #function for announcing social
global ntimer
z = open('E:\mIRC\Twitter.txt')
SOCIAL = z.read()
message (SOCIAL)
print 'Social Timers Started!'
ntimer = threading.Timer(1200,socialtimer)
ntimer.start()
data = irc.recv(1204) #gets output from IRC server
try: user = data.split(':')[1];
except IndexError: print (data)
user = user.split('!')[0] #determines the sender of the messages
print (data)
Below this is code for the commands i use the bot for. This just uses data.find
Ok from what I see, catching that exception is quite natural and shouldn't be harmful. Once every while, there isn't anything new on the server to pull and so data is an empty string. However, a clearer way to do this might be (also, I took liberty of rewriting some of your code and I'm assuming the last block of your code is also inside while True):
#It's good practice to define functions first, too keep definitions in one place
def queuetimer(): #function for resetting the queue every 30 seconds
global queue
print 'queue reset'
queue = 0
threading.Timer(30,queuetimer).start()
def message(msg): #function for sending messages to the IRC chat
global queue
queue = queue + 1
print queue
if queue < 20: #ensures does not send >20 msgs per 30 seconds.
irc.send('PRIVMSG ' + channel + ' :' + msg + '\r\n')
else:
print 'Message deleted'
def socialtimer(): #function for announcing social
global ntimer
z = open('E:\mIRC\Twitter.txt')
SOCIAL = z.read()
message (SOCIAL)
print 'Social Timers Started!'
ntimer = threading.Timer(1200,socialtimer)
ntimer.start()
queue = 0 #sets variable for anti-spam queue functionality
newsmsg = 'whitelist'
irc = socket.socket()
irc.connect((server, 6667)) #connects to the server
#sends variables for connection to twitch chat
irc.send('PASS ' + password + '\r\n')
irc.send('USER ' + nick + ' 0 * :' + bot_owner + '\r\n')
irc.send('NICK ' + nick + '\r\n')
irc.send('JOIN ' + channel + '\r\n')
queuetimer()
while True:
data = irc.recv(1024) #gets output from IRC server, 1024 is a better number than 1204
#make sure data isn't an empty string
if data != '':
user = data.split(':')[1]
user = user.split('!')[0] #determines the sender of the messages
print (data)
else:
print ("Nothing to get from the server")
By the way, correct syntax for try...except clause is
try:
#do something
except ExceptionName:
#do something else
else:
#do something if no exceptions occurred
finally:
#do something even if an unhandled exception occurs and then rise it
I simply couldn't fit that in my comment. Link to documentation

Categories

Resources