Im trying to do a socket.gethostbyname from a list of subdomains concatenated with an argument value but am getting an error. Im not sure if the loop isnt working correctly and the first try is just not a valid subdomain+domain. or if it just isnt working at all?
ERROR
Traceback (most recent call last):
File "./attack2.py", line 40, in <module>
print subcheck(returned_list, arguments['--domain'])
File "./attack2.py", line 31, in subcheck
socket.gethostbyname(sub + domain)
socket.gaierror: [Errno -2] Name or service not known
CODE
#!/usr/bin/python
"""
Description:
Basic Domain bruteforcer
Usage:
attack2.py (-f <file>) (-d <domain>) [-t 10] [-v]
attack2.py -h | --help
Arguments:
-f --file File to read potential Sub-domains from. (Required)
-d --domain Domain to bruteforce. (Required)
Options:
-h --help Show this screen.
-p --proxy Proxy address and port. [default: http://127.0.0.1:8080] (Optional)
-t --thread Thread count. (Optional)
-v --verbose Turn debug on. (Optional)
"""
import socket
from docopt import docopt
def fread(dwords):
flist = open(dwords).readlines()
return [s.replace('\n', '.') for s in flist]
def subcheck(subdomain, domain):
for sub in subdomain:
socket.gethostbyname(sub + domain)
return output
if __name__ == "__main__":
arguments = docopt(__doc__, version='0.1a')
print arguments
print fread(arguments['--file'])
returned_list = fread(arguments['--file'])
print subcheck(returned_list, arguments['--domain'])
NEW def subcheck code
def subcheck(subdomain, domain):
for sub in subdomain:
try:
#print "%s %d" % (sub+domain,len(sub+domain))
print socket.gethostbyname(sub + domain)
except:
print "Some error"
NEW OUTPUT
173.194.34.150
173.194.34.137
Some error
Some error
None
domain.google.com and stuff.google.com are invalid domains. Getting rid of those will fix the problem.
None is returned because you aren't returning anything in your subcheck function. So when you invoke it like this:
print subcheck(returned_list, arguments['--domain'])
it will be forced to return, and print None. Remove the print in front of it and you won't see None.
"[Errno -2] Name or service not known" sounds to me like your program cannot reach a DNS server. Can you resolve the names in some other way? e.g. using `dig'. I think if socket.gethostbyname cannot resolve the name, it returns a different error; when I try it, I get: "No address associated with hostname".
Related
What I tried as below which giving me error message.
What I want:
I actually want to ping N number of servers and traceroute it and result should be saved in a text file. No matter if it store in any other format too but it should be easy to understand and read.
Issue:
Error related to Popen is not getting resolved however if you aware of any other method, please welcome to that too. Please help. Thanks in advance.
Note: I am using Windows 10
import subprocess
with open('ip-source.txt') as file:
IP = file.read()
IP = IP.splitlines()
for ip in IP:
with open('output.txt','ab') as out:
out.write(subprocess.Popen("ping " + ip))
===================== RESTART: F:/PingandTracert/Ping.py =====================
Traceback (most recent call last):
File "F:/PingandTracert/Ping.py", line 12, in <module>
out.write(subprocess.Popen("ping " + ip))
TypeError: a bytes-like object is required, not 'Popen'
The below is what you could use to run a ping test, I am using the subprocess module.
You can write the result to a csv file or a text file, depends on how you would like to have it.
import subprocess
def pingTest(host):
process = subprocess.Popen(["ping", "-n", "1",host], stdout=subprocess.PIPE,stderr=subprocess.PIPE)
streamdata = process.communicate()[0]
if not 'Reply from {}'.format(host) in str(streamdata):
return "Ping Failed"
else:
return "Ping Successful"
print(pingTest("ip"))
I am working on a code so that it can handle the error from fabric.local, but some how it always abort with the error and never go into except block.
Here is my code, hopefully can get some idea from you guys
This snippet is trying to get Vagrant ssh port, if the vagrant is not up, bring it up
def findsshport():
with settings(warn_only=True):
try:
print 'greping port'
return (local('vagrant ssh-config {} | grep Port'.format(env.vmId), capture=True))
except:
print 'vagrant not up'
with lcd('%s' % (buildfolder)):
local('vagrant up ext4')
return (local('vagrant ssh-config {} | grep Port'.format(env.vmId), capture=True))
env.user = 'root'
sshPort = findsshport()
env.hosts = ['127.0.0.1:' + sshPort.split()[1]]
Error
[localhost] local: vagrant ssh-config 22921a7 | grep Port
Warning: local() encountered an error (return code 1) while executing 'vagrant ssh-config 22921a7 | grep Port'
Traceback (most recent call last):
File "/home/testing/local/lib/python2.7/site-packages/test123/fabriclogin.py", line 114, in sshlogin
env.hosts = ['127.0.0.1:' + sshPort.split()[1]]
AttributeError: 'NoneType' object has no attribute 'split'
UPDATE
Similar Question and Answer
Can I catch error codes when using Fabric to run() calls in a remote shell?
It seems like it's just a warning from fabric. My understand if you encounter an error on ssh, it doesn't "translate" into a Python error, that's why the exception block doesn't work. Please provide error trace for further analysis.
Martin is correct, that was a warning from fabric.api.local and python exception handling will not treat it as an error. Instead, the error that I seen was from another part of code which the above snippet had returned something invalid.
Instead of using try and except, if else is used with return_code which checking the command exit status.
port = local('vagrant ssh-config {} | grep Port'.format(env.vmId), capture=True)
if port.return_code == 0:
return port
else:
with lcd('%s' % (buildfolder)):
local('vagrant up {}'.format(env.vmId), capture=True)
return (local('vagrant ssh-config {} | grep Port'.format(env.vmId), capture=True))
Your problem is probably here.
with settings(warn_only=True)
Remove this line, and your local call will raise exceptions if the command exits with a non-zero return code.
def task_name():
with settings(warn_only=True):
try:
local("invalid_command")
except:
print("This will never print!")
Lets compare that to;
def task_name():
try:
local("invalid_command")
except:
print("This will print")
I'm really getting mad 'cause of a problem I do not manage to get through while programming a simple and didactic portscanner in python. Here's the code:
def main():
parser = optparse.OptionParser("usage%prog "+\
"-H <target host> -p <target port>")
parser.add_option('-H', dest='tgtHost', type='string', \
help='specify target host')
parser.add_option('-p', dest='tgtPort', type='string', \
help='specify target port[s] separated by comma')
(options, args) = parser.parse_args()
tgtHost = options.tgtHost
tgtPorts = str((options.tgtPort)).replace(",", " ").split()
if (tgtHost is None) | (tgtPorts is None):
print '[-] You must specify a target host and port[s].'
exit(0)
it all works as expected, apart from one thing: the (tgtPorts is None) check does not seem to work, while the tgtHost control works fine. In other words, this is what happens without a specified -H option:
$ python portscanner.py -p 21
[-] You must specify a target host and port[s].
while with the host and without -p here's what happens:
$ python portscanner.py -H 1234
[+] Scan Results for: 0.0.4.210
Scanning port None
Traceback (most recent call last):
File "portscanner.py", line 45, in <module>
main()
File "portscanner.py", line 43, in main
portScan(tgtHost, tgtPorts)
File "portscanner.py", line 29, in portScan
connScan(tgtHost, int(tgtPort))
ValueError: invalid literal for int() with base 10: 'None'
So the script throws an error because it cannot convert None to int, and that's the point of the consistence check. I've already tried to change (tgtPorts is None) in (tgtPorts[0] is None), but nothing changed. Googled for it as well, but noone seems to have had the same problem. Any ideas?
You have a string with the word 'None' in it, not the None object.
You made it a string here:
tgtPorts = str((options.tgtPort)).replace(",", " ").split()
Rather than use str() there, test for options.tgtPort having a true value (e.g. not None or an empty string):
if options.tgtPort:
tgtPorts = options.tgtPort.replace(",", " ").split()
Note that | is bitwise OR, you should really use or instead. I'd test for the options first, then parse:
if not (options.tgtHost and options.tgtPort):
print '[-] You must specify a target host and port[s].'
exit(1)
Here both omitting the options and not specificing a value is an error.
Personally, I'd use the argparse module here and use required arguments, with the ports argument set to nargs='+' to capture one or more values. Error handling is then done by argparse as well.
I am attempting to call a windows command with relevant arguments using python's subprocess . The command is executing and the arguments and their values look to be correct, however It only seems to be working correctly when using the "local mode" -l.
I'm getting an invalid argument/option error when using the remote mode. Could any point out where im going wrong?
Could anyone point out how to format the subprocess.check_ouput() arguments correctly to include the variables given at commandline when executing the script? As you can see ive tryd using string formating, both old and new to try get it working as I cant workout how to add the last domain variable inbetween the filter (/FI) argument value without string formatting.
expected commandline to execute
tasklist /V /S 192.168.1.122 /U 'DOMAIN'\'USERNAME' /P 'PASSWORD' /FI "USERNAME eq 'DOMAIN'\*"
with this commandline example of the script:
hunter.py -d DOMAIN -u USERNAME -p PASSWORD -s servers.txt
This is the error:
ERROR: Invalid argument/option - '/S 192.168.1.122'.
Type "TASKLIST /?" for usage.
Clearly the argument is correct "visually" correct anyway, here is the usage for the tasklist:
Description:
This tool displays a list of currently running processes on
either a local or remote machine.
Parameter List:
/S system Specifies the remote system to connect to.
/U [domain\]user Specifies the user context under which
the command should execute.
/P [password] Specifies the password for the given
user context. Prompts for input if omitted.
/M [module] Lists all tasks currently using the given
exe/dll name. If the module name is not
specified all loaded modules are displayed.
/SVC Displays services hosted in each process.
/APPS Displays Store Apps and their accociated processes.
/V Displays verbose task information.
/FI filter Displays a set of tasks that match a
given criteria specified by the filter.
/FO format Specifies the output format.
Valid values: "TABLE", "LIST", "CSV".
/NH Specifies that the "Column Header" should
not be displayed in the output.
Valid only for "TABLE" and "CSV" formats.
/? Displays this help message.
This is the python code i have so far;
#!/usr/bin/python
"""
Description:
Used for checking users logged into a list of servers.
Usage:
hunter.py [-u <username>] [-p <password>] [-s <FILE>] (-d <domain>)
hunter.py (-d <domain>) (-l)
hunter.py -h | --help
hunter.py --version
Options:
-l --local
-u --username
-h --help Show this screen.
--version Show version.
-p --password
-d --domain
-s --serverfile=FILE
"""
from docopt import docopt
import subprocess
from subprocess import CalledProcessError
def tldomain(serverlist, domain, username, password):
nlist = serverlist
for serverl in nlist:
try:
print subprocess.check_output(["tasklist", "/V", "/S " + serverl, "/U" + domain, "\\" + username, "/P" + password, "/FI", "'USERNAME eq %s\\\*'"]) % domain
except CalledProcessError as e:
print(e.returncode)
def tllocal(domain):
try:
cmd = 'tasklist /V /FI "USERNAME eq {0}\\*"' .format(domain)
subprocess.call(cmd)
except OSError as e:
print e
def getservers(servers):
slist = open(servers).readlines()
return [s.replace('\n', '') for s in slist]
if __name__ == "__main__":
arguments = docopt(__doc__, version='0.1a')
print arguments
if (arguments['--local']) == False:
serverlist = getservers(arguments['--serverfile'])
tldomain(serverlist, arguments['<domain>'], arguments['<username>'], arguments['<password>'])
else:
tllocal(arguments['<domain>'])
Pass in your arguments as separate elements in the list and apply the string formatting to the last element, no the output of the subprocess.check_output() call:
print subprocess.check_output(
["tasklist", "/V", "/S", serverl, "/U", domain + "\\" + username,
"/P", password, "/FI", "USERNAME eq %s\\*" % domain])
Note that I also removed the ' quoting from the last argument, leave that to the subprocess module.
This also assumes that domain is always a non-empty string; if that's not the case, use:
if domain:
domain += '\\'
print subprocess.check_output(
["tasklist", "/V", "/S", serverl, "/U", domain + username,
"/P", password, "/FI", "USERNAME eq %s*" % domain])
e.g. only use the \ backslash when domain is actually specified.
This question already has answers here:
Why does passing variables to subprocess.Popen not work despite passing a list of arguments?
(5 answers)
Closed 1 year ago.
1 import subprocess
2 raw = raw_input("Filename:").lower()
3 ip = raw_input("Host:").lower()
4 cmd = subprocess.call("tcpdump -c5 -vvv -w" + " raw " + " ip ",shell=True)
So this is my script. I everything works besides one key objective, using the raw input.
It allows me to input anything i want, but when it goes to saving the file or using an ip/host doe doesn't actually do anything.
Sure it gives me the packets, but from the localhost not the host i type in.
how i know this isn't working is cause my first raw input is the filename, so i put in test, when i look in the folder were my script is, it produces a file called "raw" meaning, its not actually taking my input only using whats inside my "X"...
So i make a few chances to come to this:
1 import subprocess
2 raw = raw_input("Filename:").lower()
3 ip = raw_input("Host:").lower()
4 cmd = subprocess.call("tcpdump -c5 -vvv -w" + raw + "host" + ip,shell=True)
Which is great because it actually calls for the -w but it saves it now as rawhostip instead of "raw"s input.
for reference this is what the command looks like in the terminal:
tcpdump -c5 -vvv -w savename host wiki2
the only two variabls are savename and wiki2 the rest are needed for the command to work.
with this script i get this error:
import subprocess
raw = raw_input("Filename:").lower()
ip = raw_input("Host:").lower()
cmd = subprocess.call("tcpdump -c5 -vvv -w" + raw, "host" + ip,shell=True)
Error:
Traceback (most recent call last):
File "te.py", line 4, in <module>
cmd = subprocess.call("tcpdump -c5 -vvv -w" + raw, "host" + ip,shell=True)
File "/usr/lib/python2.6/subprocess.py", line 480, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.6/subprocess.py", line 583, in __init__
raise TypeError("bufsize must be an integer")
TypeError: bufsize must be an integer
I am at a lost. Any help will be great, yes I know look at subprocess's doc's on site:X, I have I need a human to teach me, I don't understand what I am reading.
My question is how do I work with these variables.
Don't use shell=True. That should be False.
You are making subtle mistakes with the input. Specifically, if you have two strings:
>>> s1 = 'Hello'
>>> s2 = 'Hi'
>>> s1 + s2
'HelloHi'
Notice, there is no space between Hello and Hi. So don't do this. (Your line 4)
You should do (the good way):
>>> raw = raw_input('Filename: ')
Filename: test
>>> ip = raw_input('Host: ')
Host: 192.168.1.1
>>> command = 'tcpdump -c5 -vvv -w {0} {1}'.format(raw, ip) # the command goes here
>>> subprocess.call(command.split(), shell=False) # call subprocess and pass the command as a list using split
Now it should work.
You should not use the string form ob the subprocess functions. Try:
subprocess.check_call(["tcpdump", "-c5", "-vvv", "-w", raw, "host", ip])