sockect.gethostbyaddr in a for loop read from a file - python

Trying to feed a text file list through socket.gethostbyaddr and I seem to be stuck on a data type issue.
when try to loop through the list I'm getting no output except an Exception error on my last test line
This is just a small script to resolve ip to name if one exists. To test my opened file is just:
1.1.1.1
2.2.2.2
10.1.1.1
with my local hosts having an entry for the first two lines to a "test1"or "test2" name
just running socket.gethostbyaddr('1.1.1.1') returns "test1" as the host so I know that part is correct for testing
import subprocess
import socket
tstout = open('testout.txt','w+')
with open("testip.txt", "r") as ins:
for l in ins:
line = str(l)
try:
tstout.write (socket.gethostbyaddr(line))
except Exception as e:
print (e)
tstout.close()
subprocess.Popen([r'c:\Windows\notepad.exe',r'c:\scripts\testout.txt'])
Was expecting the output file to have the resolve results written to it, any pointers where I messed this up is appreciated
Simplified to:
import socket
tstout = open('testout.txt','w+')
with open("testip.txt", "r") as ins:
for l in ins:
l = str(l)
# print(l)
tstout.write (socket.gethostbyaddr(l))

Related

file.write() isn't writing to text file

I'm trying to send a file over a socket. Everything seems to be working properly except for the file not writing properly. I snipped the code down to the major issue but can send the full server and client code if necessary.
if inst == "send":
try:
print ("Receiving...")
l = s.recv(1024)
with open('torecv.py', 'wb') as f:
print ("Writing...")
newFile = l.decode("UTF-8")
f.write(newFile)
f.close()
print ("Done Receiving")
except:
pass
The output returns:
Receiving...
Writing...
and newFile saves the correct data which says to me that it is running f.write is the problem because "torecv.py" is empty.
I'm pretty new to python so go easy on me. Thanks!

Simple Python SMTP Enumeration script

I am trying to write a simple Python SMTP enumeration script, which reads usernames from a text file (filename supplied as the second argument - sys.argv[2]), and checks them against an SMTP server (hostname or ip supplied as the first argument - sys.argv[1]. I found something that is kind of close, and tweaked it a bit, like so:
#!/usr/bin/python
import socket
import sys
users = sys.argv[2]
for line in users:
line = line.strip()
if line!='':
users.append(line)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((sys.argv[1], 25))
fn = s.makefile('rwb')
fn.readline()
fn.write('HELO testing.com \r\n')
fn.flush()
fn.readline()
for user in users:
fn.write('VRFY %s\r\n' % user)
fn.flush()
print '%s: %s' % (user, fn.readline().strip())
fn.write('QUIT\r\n')
fn.flush()
s.close()
However, when I run the script (for example):
./smtp-vrfy.py 192.168.1.9 users.txt
It results in an error:
File "./smtp-vrfy.py", line 10, in
users.append(line)
AttributeError: 'str' object has no attribute 'append'
What am I doing wrong? How can I fix it? Perhaps there is an easier way to accomplish what I'm trying to do?
users is a file name, but you're not reading it. Instead, see what happens:
>>> users = "users.txt"
>>> for line in users:
... print(line)
...
u
s
e
r
s
.
t
x
t
You probably want:
with open(users) as f:
for line in f:
# ...
Even better:
filename = sys.argv[2]
with open(filename) as f:
users = [line.strip() for line in f.readlines() if line]

sending large text file line by line over network with twisted

I am using twisted and python to send some large text file over network, I would like to use UDP and multicast, What solution would be the best to do it, I need sample code cause I am already confused, When I try to do it I get error 24 from python which says too many open files, could you help me to resolve this issue?
here is part of my code:
if (options.upt != None):
print "UPGRADE is initiating"
sourceFile = open(options.upt, "r")
reactor.listenMulticast(1888, UpgradeReciever("Control Listener"), listenMultiple=True)
#with open(options.upt) as sourceFile:
for line in sourceFile:
upgradeSenderObj = UpgradeSender(line, "224.0.0.8", 1888)
reactor.listenMulticast(1888, upgradeSenderObj, listenMultiple=True)
reactor.run()
I have also tried to read the whole file and put in list and then call each element of list (which are in fact lines of my file) by twisted, but still got the similar problem, here is my updated code:
if (options.upt != None):
print "UPGRADE is initiating"
sourceFile = open(options.upt, "r")
reactor.listenMulticast(1888, UpgradeReciever("Control Listener"), listenMultiple=True)
dataContainer = list(sourceFile)
print dataContainer
for i in range(len(dataContainer)):
upgradeSenderObj = UpgradeSender(dataContainer[i], "224.0.0.8", 1888)
reactor.listenMulticast(1888, upgradeSenderObj, listenMultiple=True)
reactor.run()

Python AttributeError: 'str' object has no attribute 'namelist'

I am trying to create a very simple log parser script in python. Everything is going as planned except the script on the target machine is returning this error (the script works on a unix machine though quite fine):
for name in root.namelist():
Attribute Error: 'str' object has no attribute 'namelist'
Python versions appear to be the same (2.7.3 on both machines). Any ideas?
Script itself:
import zipfile
import os
import re
string1 = "searchstring" # raw_input("usrinput: ")
try:
root = zipfile.ZipFile("/home/testuser/docs/testzip.zip", "r")
except:
root = "testfolder/"
for name in root.namelist():
if name.find(".") > 0:
f = root.open(name)
searchlines = f.readlines()
for i, line in enumerate(searchlines):
regex1 = "(.*)" + re.escape(string1) + "(.*)"
if re.match (regex1, line):
for l in searchlines[i-4:i+4]: print l,
print
This is because root = "testfolder/" it doesn't have any namelist as its attribute.
Type of root is string
Which in turn looking at your code means, root = zipfile.ZipFile("/home/testuser/docs/testzip.zip", "r") generated an exception
in exception block try to use except Exception, ex: and then print ex.message to understand the type of exception being generated
This is because, namelist() is only available for a zipfile, not for a string.
This happens when the zip file cannot be opened. Check the path where the zip file is located.
Try this and see the output:
try:
root = zipfile.ZipFile("/home/testuser/docs/testzip.zip", "r")
except Exception, msg:
print msg
root = "testfolder/"
When I tried with a valid zip file, the program worked fine.

Python shell freezes on reading (fasta) file

I am going to start of by showing the code I have thus far:
def err(em):
print(em)
exit
def rF(f):
s = ""
try:
fh = open(f, 'r')
except IOError:
e = "Could not open the file: " + f
err(e)
try:
with fh as ff:
next(ff)
for l in ff:
if ">" in l:
next(ff)
else:
s += l.replace('\n','').replace('\t','').replace('\r','')
except:
e = "Unknown Exception"
err(e)
fh.close()
return s
For some reason the python shell (I am using 3.2.2) freezes up whenever I tried to read a file by typing:
rF("mycobacterium_bovis.fasta")
The conditionals in the rF function are to prevent reading each line that starts with a ">" token. These lines aren't DNA/RNA code (which is what I am trying to read from these files) and should be ignored.
I hope anyone can help me out with this, I don't see my error.
As per the usual, MANY thanks in advance!
EDIT:
*The problem persists!*
This is the code I now use, I removed the error handling which was a fancy addition anyway, still the shell freezes whenever attempting to read a file. This is my code now:
def rF(f):
s = ""
try:
fh = open(f, 'r')
except IOError:
print("Err")
try:
with fh as ff:
next(ff)
for l in ff:
if ">" in l:
next(ff)
else:
s += l.replace('\n','').replace('\t','').replace('\r','')
except:
print("Err")
fh.close()
return s
You didn't ever define e.
So you'll get a NameError that is being hidden by the naked except:.
This is why it is good and healthy to specify the exception, e.g.:
try:
print(e)
except NameError as e:
print(e)
In cases like yours, though, when you don't necessarily know what the exception will be you should at least use this method of displaying information about the error:
import sys
try:
print(e)
except: # catch *all* exceptions
e = sys.exc_info()[1]
print(e)
Which, using the original code you posted, would have printed the following:
name 'e' is not defined
Edit based on updated information:
Concatenating a string like that is going to be quite slow if you have a large file.
Consider instead writing the filtered information to another file, e.g.:
def rF(f):
with open(f,'r') as fin, open('outfile','w') as fou:
next(fin)
for l in fin:
if ">" in l:
next(fin)
else:
fou.write(l.replace('\n','').replace('\t','').replace('\r',''))
I have tested that the above code works on a FASTA file based on the format specification listed here: http://en.wikipedia.org/wiki/FASTA_format using Python 3.2.2 [GCC 4.6.1] on linux2.
A couple of recommendations:
Start small. Get a simple piece working then add a step.
Add print() statements at trouble spots.
Also, consider including more information about the contents of the file you're attempting to parse. That may make it easier for us to help.

Categories