import socket, sys, string
if len(sys.argv) !=4 :
print "Usage: ./supabot.py <host> <port> <channel>"
sys.exit(1)
irc = sys.argv[1]
port = int(sys.argv[2])
chan = sys.argv[3]
sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sck.connect((irc, port))
sck.send('NICK supaBOT\r\n')
sck.send('USER supaBOT supaBOT supaBOT :supaBOT Script\r\n')
sck.send('JOIN ' + " " + chan + '\r\n')
data = ''
while True:
data = sck.recv(1024)
if data.find('PING') != -1:
sck.send('PONG ' + data.split() [1] + '\r\n')
print data
elif data.find('!info') != -1:
sck.send('PRIVMSG ' + chan + ' :' + ' supaBOT v1 by sourD ' + '\r\n')
print data
elif data.find('!commands') != -1:
nick = data.split('!')[ 0 ].replace(':',' ')
if nick == "s0urd":
sck.send('PRIVMSG ' + chan + ' :' + ' no commands have been set ' + '\r\n')
else:
sck.send('PRIVMSG ' + chan + ' :' + ' youre not my master ' + '\r\n')
print data
elif data.find('PRIVMSG') != -1:
message = ':'.join(data.split (':')[2:])
if message.lower().find('darkunderground') == -1:
nick = data.split('!')[ 0 ].replace(':',' ')
destination = ''.join (data.split(':')[:2]).split (' ')[-2]
function = message.split( )[0]
print nick + ' : ' + function
arg = data.split( )
print sck.recv(1024)
my nick in IRC is s0urd but when I type !commands I get "youre not my master" but my nick is s0urd. Maybe I did the whole nick thing wrong, I don't know, but any help would be appreciated, thanks.
line 26
nick = data.split('!')[ 0 ].replace(':',' ')
That's going to replace the : with a space (), and thus the resulting string will be "s0urd ", not "s0urd". You probably meant this instead:
nick = data.split('!')[ 0 ].replace(':','')
Note the lack of space between the '' being passed as the replacement string.
Related
This question already has answers here:
How do I terminate a script?
(14 answers)
Closed 4 months ago.
I want to print out an error code "DAT_GRESKA" or "GRESKA" in other input and then make the code do nothing but in my case it is taking me back and asking me to redo the input because its false. How do I make it to stop but without using exit() or quit().
import csv
def unos_csv():
ucsv = input("Unesi CSV datoteku: ")
if ucsv == 'raspored1.csv' or ucsv == 'raspored2.csv':
ucsv = str(ucsv)
return ucsv
else:
print('DAT_GRESKA')
return main()
def ime_predmeta():
subname = input("Unesi kod predmeta: ")
if subname.isupper():
return subname
else:
print("GRESKA")
return main()
def obrada():
file = open(unos_csv(), "r")
reader = csv.reader(file, delimiter=',')
predmet = ime_predmeta()
with open(predmet + '.txt', 'a')as a:
for row in reader:
danu_nedelji = int(row[0])
dejan = row[3].split('[')[1].split(']')[0]
if predmet in row[3]:
t1 = row[1]
t2 = row[2]
h1, m1 = t1.split(':')
h2, m2 = t2.split(':')
t11 = int(h1) * 60 + int(m1)
t22 = int(h2) * 60 + int(m2)
tkon = t22 - t11
tkon = str(tkon)
if danu_nedelji == 0:
a.write("Monday" + ' ' + row[1] + ' ' + row[2] + ' ' + tkon + ' ' + dejan + '\n')
elif danu_nedelji == 1:
a.write("Tuesday" + ' ' + row[1] + ' ' + row[2] + ' ' + tkon + ' ' + dejan + '\n')
elif danu_nedelji == 2:
a.write("Wednesday" + ' ' + row[1] + ' ' + row[2] + ' ' + tkon + ' ' + dejan + '\n')
elif danu_nedelji == 3:
a.write("Thursday" + ' ' + row[1] + ' ' + row[2] + ' ' + tkon + ' ' + dejan + '\n')
elif danu_nedelji == 4:
a.write("Friday" + ' ' + row[1] + ' ' + row[2] + ' ' + tkon + ' ' + dejan + '\n')
a.close()
def main():
obrada()
if __name__ == '__main__':
main()
I think you misunderstand how the return statement works.
The reason that your program "continues" ... it doesn't continue -- you specifically invoke your main program another time. If you simply want to go back to the calling location and continue, use
return
You used
return main()
which is a command to invoke main again, wait until it's done, and send that value back to whatever called the function.
I want to telnet huawei switch with python script to read some basic staff like "display int brief" result. I know basic huawei command and some programming.
I can telnet cisco router with python script.
Here is my attempt so far
import telnetlib
import datetime
now = datetime.datetime.now()
host = "myhost" # your router ip
username = "user" # the username
password = "pass"
tn = telnetlib.Telnet(host,23,6)
tn.read_until("Username:")
tn.write(username+"\n")
tn.read_until("Password:")
tn.write(password+"\n")
tn.write("display int description"+"\n")
#tn.write("sh run"+"\n")
tn.write("quit"+"\n")
output = tn.read_all()
fp = open("sw_hu.txt","w")
fp.write(output)
fp.close()
I would use pexpect library then open connection with pexpect.spawn('telnet ip_address') module documentation is great start. If you now commands then it is mostly combination off sendline, expect and before.
child = pexpect.spawn ('telnet %s' % dev_name)
try:
i = child.expect_exact(['Password:', 'Username:'])
except (pexpect.EOF, pexpect.TIMEOUT):
return False
if i == 1:
child.sendline(user_name)
child.expect_exact('Password:')
child.sendline(passw)
else:
child.sendline(passw)
if child.expect_exact(['>', 'Wrong', pexpect.TIMEOUT], timeout=5):
child.close()
return False
child.sendline('sup')
i = child.expect_exact(['Password:', '>', 'Unknown', 'not set'])
if i == 1:
child.sendline('')
elif i == 2 or i == 3:
child.close()
return False
else:
child.sendline(ena)
if child.expect_exact(['>', 'Password', 'failed']):
child.close()
child.sendline('tftp %s put %s %s.backup.txt' % (TFTP, conf_name, name))
child.expect_exact(['>', 'successfully'])
if 'Unable' in child.before:
....
....
Edit: Added partial example to backup config (it is python 2.x and old Huawei router)
if w['router_type'] == "cisco":
tn.read_until("Username:")
tn.write(user.encode('ascii')+"\n"
#tn.write(user +"\n")
if password:
tn.read_until("Password:")
tn.write(password.encode("ascii") + "\n")(indent)
tn.write("terminal length 0\n")
tn.write("show version\n")
tn.write("show running-config view full\n")
tn.write("exit\n")
tn_output = tn.read_all()
print ("Logging out Router ") + w['host_name'] + ("_") + w['router_type'] + (".....")
flag = 1
if w['router_type'] == "huawei":
tn.read_until("Username:")
tn.write(user + "\n")
if password:
tn.read_until("Password:")
tn.write(password + "\n")
tn.write("screen-length 0 temporary\n")
tn.write("dis version\n")
tn.write("dis current-configuration\n")
tn_output = tn.read_until("return")
tn.write("quit\n")
print ("Logging out Router ") + w['host_name'] + ("_") + w['router_type'] + (".....")
flag = 1
if w['router_type'] == "MAIPU":
tn.read_until("login:")
tn.write(user + "\n")
if password:
tn.read_until("password:")
tn.write(password + "\n")
tn.write("more off\n")
tn.write("show version\n")
tn.write("show running\n")
tn.write("logout\n")
tn_output = tn.read_all()
flag = 1
print ("Logging out Router ") + w['host_name'] + ("_") + w['router_type'] + (".....")
print ("\n Count: " )+ str(v_count) + ("---\n")
if flag:
if v_count==0:
saveoutput = open ("BACKUP/" + HOST + ".txt" , "w")
saveoutput.write(tn_output)
print ("Saving new file ") + HOST + ("......")
elif v_count == 1:
previous_file = open("BACKUP/" + HOST + ".txt")
temp_file = previous_file.read()
if str(temp_file) != str(tn_output):
saveoutput = open ("BACKUP/" + HOST + "_v2.txt" , "w")
saveoutput.write(tn_output)`enter code here`
print ("Saving new file " )+ HOST + ("......")
elif v_count > 1:
previous_file = open("BACKUP/" + HOST + "_v" + str(v_count) + ".txt")
temp_file = previous_file.read()
if str(temp_file) != str(tn_output):
saveoutput = open ("BACKUP/" + HOST + "_v" + str(v_count + 1) + ".txt" , "w")
print ("Saving new version of file ") + HOST + ("......")`enter code here`
My code won't display the opened_ports list containing all opened ports.
(I think it doesn't even add values to it. (Maybe overwriting?))
I already tried a few things but nothing will work.
BTW: Is there a way to sort the "Port x is closed."?
Output:
...
Port 97 is closed.
Port 100 is closed.
All opened ports within the selected range:
[]
Code:
import socket, threading, time
from queue import Queue
print_lock = threading.Lock()
target = input('Target:' + ' ')
workers = input('Workers:' + ' ')
first_port = input('First port:' + ' ')
last_port = input('Last port:' + ' ')
if first_port == 'min':
first_port = 1
if last_port == 'max':
last_port = 65536
print('\n' + 'Scanning...' + '\n')
def scan(port):
soccer = socket.socket(socket.AF_INET, socket. SOCK_STREAM)
try:
connection = soccer.connect((target, port))
with print_lock:
print('Port' + ' ' + str(port) + ' ' + 'is opened.')
time.sleep(5)
opened_ports = opened_ports + port
connection.close()
except:
with print_lock:
print('Port' + ' ' + str(port) + ' ' + 'is closed.')
def thread():
while True:
worker = queue.get()
scan(worker)
queue.task_done()
queue = Queue()
opened_ports = []
for x in range(int(workers)):
threader = threading.Thread(target = thread)
threader.daemon = True
threader.start()
for worker in range(int(first_port), int(last_port)):
queue.put(worker)
queue.join()
print('\n' + 'All opened ports within the selected range:' + '\n' + '\n' +
str(opened_ports))
Just change opened_ports = opened_ports + port to opened_ports.append(port)
Trying to get a self updating speedometer and clock working for my truck using gps. So far I have been able to get the read out that I want using easygui and msgbox but it is not self updating which will not help much on either application. Below is the code. Any help would be much appreciated, I know this is pretty ugly and probably not correct but I am new to python.
import gps
from easygui import *
import sys
# Listen on port 2947 (gpsd) of localhost
session = gps.gps("localhost", "2947")
session.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE)
while True:
try:
report = session.next()
if report['class'] == 'TPV':
if hasattr(report, 'time'):
hour = int(report.time[11:13])
hourfix = hour - 7
if hourfix < 12:
time = 'Current Time Is: ' + report.time[5:7] + '/' + report.time[8:10] + '/' + report.time[0:4] + ' ' + str(hourfix) + report.time[13:19] + ' am'
else:
hourfix = hourfix - 12
time = 'Current Time Is: ' + report.time[5:7] + '/' + report.time[8:10] + '/' + report.time[0:4] + ' ' + str(hourfix) + report.time[13:19] + ' pm'
if report['class'] == 'TPV':
if hasattr(report, 'speed'):
speed = int(report.speed * gps.MPS_TO_MPH)
strspeed = str(speed)
currentspeed = 'Current Speed Is: ' + strspeed + ' MPH'
msgbox(time + "\n" + currentspeed, "SPEEDO by Jono")
except KeyError:
pass
except KeyboardInterrupt:
quit()
except StopIteration:
session = None
print "GPSD has terminated"
When I run the script:
import socket
from time import strftime
time = strftime("%H:%M:%S")
irc = 'irc.tormented-box.net'
port = 6667
channel = '#tormented'
sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sck.connect((irc, port))
print sck.recv(4096)
sck.send('NICK supaBOT\r\n')
sck.send('USER supaBOT supaBOT supaBOT :supaBOT Script\r\n')
sck.send('JOIN ' + channel + '\r\n')
sck.send('PRIVMSG #tormented :supaBOT\r\n')
while True:
data = sck.recv(4096)
if data.find('PING') != -1:
sck.send('PONG ' + data.split() [1] + '\r\n')
elif data.find ( 'PRIVMSG' ) != -1:
nick = data.split ( '!' ) [ 0 ].replace ( ':', '' )
message = ':'.join ( data.split ( ':' ) [ 2: ] )
destination = ''.join ( data.split ( ':' ) [ :2 ] ).split ( ' ' ) [ -2 ]
if destination == 'supaBOT':
destination = 'PRIVATE'
print '(', destination, ')', nick + ':', message
get = message.split(' ') [1]
if get == 'hi':
try:
args = message.split(' ') [2:]
sck.send('PRIVMSG ' + destination + ' :' + nick + ': ' + 'hello' + '\r\n')
except:
pass
I get this is the error:
get = message.split(' ')[1]
IndexError: list index out of range
How can I fix it?
This means that message has no spaces in it, so when it's split by a space, you get a list containing a single element - you are trying to access the second element of this list. You should insert a check for this case.
EDIT: In reply to your comment: how you add the check depends on the logic of your program. The simplest solution would be something like:
if ' ' in msg:
get = message.split(' ')[1]
else:
get = message
Try
get = message.split(" ",1)[-1]
Example
>>> "abcd".split(" ",1)[-1]
'abcd'
>>> "abcd efgh".split(" ",1)[-1]
'efgh'