Python IRC Client - python

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'

Related

How to save list, dict, int into file, and assign back from file

I have an PYQT5 UI with that allow user to store values into list, int, and qttextedit (allow user to write as code editor.
Then i save existing values into txt file, so after user changed values can always come back and reload from the local file. The problem i face is when i assign back, it became a letter by letter, even the code assign back into UI will have \n. I also tried turn them into a list, but result still bad.
So i think save into a txt is a bad idea, I looked for pickle but not sure if it can be used or how to use in this case.
score = 22
ocount = 88
scenario = {something here already}
...
usercode = 'var game = 0;\n if (game > 3){gid = 22}'
#List, int, dict, str store to txt file
with open(configName + ".txt", 'w') as f:
f.write(repr(score) + "\n" + \
repr(ocount) + "\n" + \
repr(option) + "\n" + \
repr(option_ans) + "\n" + \
repr(matchname) + "\n" + \
repr(scenario) + "\n" + \
repr(_Options) + "\n" + \
repr(_Optionselected) + "\n" + \
repr(eInfo) + "\n" + \
repr(sVar) + "\n" + \
repr(cusotm) + "\n" + \
repr(survey1) + "\n" + \
repr(survey_ans) + "\n" + \
repr(eInfoName) + "\n" + \
repr(sVarName) + "\n" + \
repr(tempcode) + "\n" + \
repr(usercode))
The value output as below:
2
1
['q1_a1', 'q1_a2', 'q2_a1']
['q1_a1_ans', 'q1_a2_ans', 'q2_a1_ans']
['log1', 'log2']
{'log1': 'if (q1_a1) scores.team1 - 1q1_a1_ans== "23234"){\nproduct_ids = [11,22];\n}', 'log2': 'if (scores.team2 != 11\nproduct_ids = [33,2];\n}'}
['var q1_a1 = 11;', 'var q1_a2 = 11122;', 'var q2_a1 = 2;']
['var q1_a1_ans = 22;', 'var q1_a2_ans = 222;', 'var q2_a1_ans = 2;']
['123']
['321']
['cam1']
['q1_a1', 'q1_a2', 'q2_a1']
['q1_a1_ans', 'q1_a2_ans', 'q2_a1_ans']
['123']
['321']
'+ + \nelse if (\nelse if (\nelse if (\nelse if ('
'var has_answer = function (answer) {\n return indexOf(answer) >= 0;\n };'
#Load back
tmp=[]
f = open("lo.txt", "r")
Lines = f.readlines()
for x in Lines:
tmp.append(x)
score = tmp[0]
ocount = tmp[1]
etc...
Result:
#try change to list
['[', "'", 'q', '1', '_', 'a', '1', "'", ',', ' ', "'", 'q', '1', '_', 'a', '2', "'", ',', ' ', "'", 'q', '2', '_', 'a', '1', "'", ']', '\n']
use exec() to execute string as code
var = ['score', 'option', 'tempcode', 'usercode']
f = open("lo.txt", "r")
Lines = f.readlines()
for i in range(0, len(Lines)):
exec(f'{var[i]} = {Lines[i]}')
# check type
exec(f'print({var[i]}, type({var[i]}))')
output
2 <class 'int'>
['q1_a1', 'q1_a2', 'q2_a1'] <class 'list'>
+ +
else if (
else if (
else if (
else if ( <class 'str'>
var has_answer = function (answer) {
return indexOf(answer) >= 0;
}; <class 'str'>
lo.txt
2
['q1_a1', 'q1_a2', 'q2_a1']
'+ + \nelse if (\nelse if (\nelse if (\nelse if ('
'var has_answer = function (answer) {\n return indexOf(answer) >= 0;\n };'
Or write them in json instead, make sure list is still list.

Port Scanner - Can't Add All Opened Ports To A Variable (List)

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)

string.lower() in contents.lower() not working correctly

My function looks up WHOIS requests using sockets and proxies.
Sometimes there is an issue with a proxy and it returns no data so I check to see if the data contains the initial domain request and if it does, return the result.
However sometimes this returns TRUE even when there's nothing in the string data.
I have also tried to do len(data) > 25, etc but for some reason it can still return true.
if domain.lower() in data.lower():
obj = WhoisEntry(domain, data)
logger.debug('WHOIS success ' + domain + ': ' + data)
return {
'expiration_date': str(obj.expiration_date),
'status': str(obj.status),
'registrar': str(obj.registrar)
}
Full code
def whois_tcp(domain):
whois_servers = [ 'whois.verisign-grs.com', 'whois.internic.net', 'whois.crsnic.net' ]
attempts = 0
while attempts < 15:
attempts = attempts + 1
logger.debug('WHOIS attempt '+domain+': '+str(attempts))
whois_host = random.choice(whois_servers)
proxy = random.choice(proxies) # global variable from config.py
proxy = proxy.split(':')
try:
s = socks.socksocket()
s.setproxy(socks.PROXY_TYPE_SOCKS5, proxy[0], int(proxy[1]))
s.connect((whois_host, 43))
s.send(domain + '\n\r\n')
data = ''
buf = s.recv(1024)
while len(buf):
data += buf
buf = s.recv(1024)
s.close()
#if domain.lower() not in data.lower():
# raise Exception(domain, 'Domain not found in WHOIS: '+data)
# continue
if domain.lower() in data.lower():
obj = WhoisEntry(domain, data)
logger.debug('WHOIS success ' + domain + ': ' + data)
return {
'expiration_date': str(obj.expiration_date),
'status': str(obj.status),
'registrar': str(obj.registrar)
}
except Exception, e:
logger.error('WHOIS Lookup Failed: '+str(e))
return None
What am I doing wrong?
1.Try:
if str(domain).lower() in str(data).lower():
...
2.Check whether the value of domain variable is None or ''.
I added code to write each whois response to file and noticed that it was in fact including whois results
file = open('./whois_records/'+domain, 'w')
file.write(data)
file.close()
Not sure why this line of code wasn't outputting the data string in the log file:
logger.debug('WHOIS success ' + domain + ': ' + str(data))
I have found that different whois servers are giving me different results for lookups.
For example: bpi-group.com
1. whois.verisign-grs.com: **FREE**
2. whois.gandi.net: **TAKEN**
Additionally I need to use different whois server for different TLDs (com/net/org/info/biz)
Currently now using:
- tld.whois-servers.net
Code is still not perfect but is working better and original problem has been solved:
def whois_tcp(domain):
ext = tldextract.extract(domain)
if ext.suffix == 'org':
whois_servers = [ 'org.whois-servers.net' ]
elif ext.suffix == 'biz':
whois_servers = [ 'biz.whois-servers.net' ]
elif ext.suffix == 'info':
whois_servers = [ 'info.whois-servers.net' ]
elif ext.suffix == 'com':
whois_servers = [ 'com.whois-servers.net' ]
elif ext.suffix == 'net':
whois_servers = [ 'net.whois-servers.net' ]
else:
whois_servers = [ 'whois.verisign-grs.com', 'whois.internic.net', 'whois.crsnic.net' ]
attempts = 0
result = None
while attempts < 15:
attempts = attempts + 1
logger.debug('WHOIS attempt '+domain+': '+str(attempts))
whois_host = random.choice(whois_servers)
proxy = random.choice(proxies) # global variable from config.py
proxy = proxy.split(':')
try:
s = socks.socksocket()
s.setproxy(socks.PROXY_TYPE_SOCKS5, proxy[0], int(proxy[1]))
s.connect((whois_host, 43))
s.send(domain + '\n\r\n')
data = ''
buf = s.recv(1024)
while len(buf):
data += buf
buf = s.recv(1024)
s.close()
file = open('./whois_records/'+domain, 'w')
file.write(data)
file.close()
# if domain.lower() not in data.lower():
# raise Exception(domain, 'Domain not found in WHOIS: '+data)
# continue
if str(domain).lower() in str(data).lower():
obj = WhoisEntry.load(domain, data)
logger.debug('WHOIS success ' + domain + ': ' + str(data))
return {
'expiration_date': str(obj.expiration_date),
'status': str(obj.status),
'registrar': str(obj.registrar)
}
except Exception, e:
logger.error('WHOIS Lookup Failed: '+str(e))
return None

Python IRC Client

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.

Scripting Python for Linux commands

I have a question. I have been really trying to learn Python. For a project, I want to make an ncurses GUI for my backup server. My backup server runs rdiff-backup, and I want to have the ncurses take in variable names and plug them into my script. I have been trying to do a lot of reading so I don't ask dumb questions.
Here is my function for running the script:
def runScript():
# Cannot concatenate 'str' and 'list' objects
#script = rdiff + rdiffArgs
script = rdiff + ' ' + rdiffVerbosity + ' ' + rdiffStatistics \
+ ' ' + clientName + '#' + clientHost + '::' + clientDir \
+ ' ' + serverDir
os.system(script)
What I originally thought would be neat was to add all the variables into a list, so I could just run say
script = rdiff + rdiffArgs
Is there a better way to do this without all the space concatenation?
Thanks for your assistance
EDIT: Let me post the whole script so far. I wasn't very clear and I really appreciate your help and patience
#!/usr/bin/env python
import os
import smtplib
# Global variables
rdiff = '/usr/bin/rdiff-backup'
rdiffVerbosity = '-v5'
rdiffStatistics = '--print-statistics'
emailSmtp = 'smtp.gmail.com'
smtpPort = '465'
emailUsername = 'reports'
emailPassword = '3kc9dl'
emailTo = 'user#domain.com'
emailFrom = 'internal#domain.com'
serverName = 'root'
serverHost = 'SV-Datasafe'
serverDir = '/srv/backup/SV-Samba01'
clientName = 'root'
clientHost = 'SV-Samba01'
clientDir = '/srv'
rdiffArgs = rdiffArgs = [rdiffVerbosity, rdiffStatistics, \
clientName + '#' + clientHost + '::' \
+clientDir + ' ' + serverDir]
time = ''
dateStamp = datetime.now()
def sendEmail():
subject = dateStamp + clientName
body = clientDir + ' on ' + clientHost + ' backed up to ' + serverName + \
' in the directory ' + serverDir + ' on ' + dateStamp
message = """\
From: %s
To: %s
Subject: %s
%s
""" % (emailFrom, emailTo, subject, body)
deliverEmail = smtplib.SMTP(emailSmtp, port=smtpPort)
deliverEmail.login(emailUsername, emailPassword)
def runScript():
# Cannot concatenate 'str' and 'list' objects
#script = rdiff + rdiffArgs
script = rdiff + ' ' + rdiffVerbosity + ' ' + rdiffStatistics \
+ ' ' + clientName + '#' + clientHost + '::' + clientDir \
+ ' ' + serverDir
os.system(script)
# TODO:: Logging
you can use format specifiers
def runScript():
script = "%s %s %s#%s %s::%s %s" %(rdiff,rdiffVerbosity,rdiffStatistics,clientName,clientHost,clientDir,serverDir)
os.system(script)
or say your rdiffArgs is already in a list
rdiffArgs = [rdiffVerbosity,rdiffStatistics,clientName,clientHost,clientDir,serverDir]
you can join them with a space
rdiffArgs = ' '.join(rdiffArgs)
lastly, just so you might want to know, you can import rdiff in your script , since rdiff-backup is written in Python
from rdiff_backup.Main import Main as backup
task=['/etc', '/tmp/backup']
backup(task)
the above backs up /etc/ to /tmp/backup. That way, you don't have to make system call to rdiff-backup. Of course, this is up to you. making system call is sometimes easier
try to use subprocess module and pass arguments as list e.g.
client = clientName + '#' + clientHost + '::' + clientDir
cmd = [rdiff, rdiffVerbosity, rdiffStatistics, client , serverDir]
p = Popen(cmd ", shell=True)
print os.waitpid(p.pid, 0)[1]
or if have args already as list use something like this
cmd = [rdiff] + args
You join paths using os.path.join
You concatenate strings like so: "".join(['a', 'b']) or ", ".join(['c', 'd'])
Which part is difficult? I am not sure I understand the question 100%
Is this it?
script = rdiff + " ".join(rdiffArgs)

Categories

Resources