Using nmap library in Python program - python

I have a simple Python program which uses nmap library to do port scanning.
from optparse import OptionParser
import nmap
from threading import *
screenLock=Semaphore(value=1)
def nmapScan(thost,tport):
x=nmap.PortScanner()
x.scan(thost,tport)
state=x[thost]['tcp'][int(tport)]['state']
print "[*]" + thost + "tcp/"+tport+" "+state
def main():
parser=OptionParser('usage %prog -H <target host> -p <target port>')
parser.add_option('-H',dest='thost',type='string',help='specify target host')
parser.add_option('-p',dest='tports',type='string',help='specify target port[s] seperated by comma')
(options,args)=parser.parse_args()
thost=options.thost
tports=options.tports
tports=tports.split(',')
if (thost==None)|(tports==None):
print parser.usage
exit(0)
for i in tports:
nmapScan(thost,i)
main()
When i run the program, i get the following error.
akshayrajmacbookpro$ python nmapScanner.py -H 192.168.1.60 -p 80,443
Traceback (most recent call last):
File "nmapScanner.py", line 28, in <module>
main()
File "nmapScanner.py", line 26, in main
nmapScan(thost,i)
File "nmapScanner.py", line 10, in nmapScan
state=x[thost]['tcp'][int(tport)]['state']
File "build/bdist.macosx-10.11-intel/egg/nmap/nmap.py", line 555, in __getitem__
KeyError: '192.168.1.60'
I tried using url instead of ip in the command line. But I get the same error. Being new to Python, I am not able to understand and resolve this.

x (instance of nmap.PortScanner) does not contain those keys. To be able to iterate the scan results you can do this:
for host, result in x._scan_result['scan'].items():
print "[*]" + thost + "tcp/" + tport + " " + result['status']['state']
It's best if you looked at the docs or source code of python-nmap to see what other useful info is available e.g. Service name and version that is listening on that port.
More info here: https://bitbucket.org/xael/python-nmap/src/f368486a2cf12ce2bf3d5978614586e89c49c417/nmap/nmap.py?at=default&fileviewer=file-view-default#nmap.py-381

The host does not exist in the result of the scan as a "Key" for the Dictionary that forms a part of the data thrown up by scan data. That is probably, in my opinion, the reason for the error. Thanks

Related

psutil.AccessDenied when using StanfordCoreNLP in Pycharm? [duplicate]

This question already has answers here:
psutil.AccessDenied Error while trying to load StanfordCoreNLP
(3 answers)
Closed 2 years ago.
# coding=utf-8
from stanfordcorenlp import StanfordCoreNLP
nlp = StanfordCoreNLP(r'/Users/silas/stanford-corenlp/', lang='zh')
sentence = '清华大学位于北京。'
print nlp.word_tokenize(sentence)
print nlp.pos_tag(sentence)
print nlp.ner(sentence)
print nlp.parse(sentence)
print nlp.dependency_parse(sentence)
nlp.close()
I'm using Mac. Java, NLKT, and Stanforcorenlp toolkit are all ready. When I'm testing the project, the error came out.
Traceback (most recent call last):
line 5, in <module>
nlp = StanfordCoreNLP(r'/Users/silas/stanford-corenlp/', lang='zh')
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/stanfordcorenlp/corenlp.py", line 79, in __init__
if port_candidate not in [conn.laddr[1] for conn in psutil.net_connections()]:
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/psutil/__init__.py", line 2120, in net_connections
return _psplatform.net_connections(kind)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/psutil/_psosx.py", line 255, in net_connections
cons = Process(pid).connections(kind)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/psutil/_psosx.py", line 347, in wrapper
raise AccessDenied(self.pid, self._name)
psutil._exceptions.AccessDenied: psutil.AccessDenied (pid=25422)
I guess it is because the Pycharm project isn't running under a root user. But how can I configure the IDE to fix the problem?
Unfortunately, if you look at the psutil project in _psosx.py, under net_connections, line 243 says..
Note: on macOS this will fail with AccessDenied unless the process is owned by root.
That means that you'll need to run as root by doing something like sudo pycharm.sh.
If you don't want to run your entire IDE as root, there's a few examples on SO on how you can run a specific script with super-user privileges. For instance see Debugging in pyCharm with sudo privileges.
This problem seems to be specific to Mac OS X which would not allow Python to check the current port.
Comment this portion of code of corenlp.py file:
if self.port is None:
for port_candidate in range(9000, 65535):
if port_candidate not in [conn.laddr[1] for conn in psutil.net_connections()]:
self.port = port_candidate
break
if self.port in [conn.laddr[1] for conn in psutil.net_connections()]:
raise IOError('Port ' + str(self.port) + ' is already in use.')
Replace by this line:
self.port = 9999
Source: https://github.com/Lynten/stanford-corenlp/issues/26#issuecomment-445507811
Another solution is to run StanfordCoreNLP with a sudo command line.

Cambrionix PowerPad15S is not showing connected devices in Ubuntu

I am using Cambrionix PowerPad15s for my devices but while running their first code which is to find all the device connected to the usb i am having some issue in jsonrpc file(Which is provided by the company itself).
I have to import this-
from cbrxapi import cbrxapi
This code is to get all the connected device in the usb port and save in result variable-
result = cbrxapi.cbrx_discover("local")
Rest of the code is-
if result==False:
print "No Cambrionix unit found."
sys.exit(0)
unitId = result[0]
handle = cbrxapi.cbrx_connection_open(unitId)
nrOfPorts = cbrxapi.cbrx_connection_get(handle, "nrOfPorts")
cbrxapi.cbrx_connection_close(handle)
print "The Cambrionix unit " + unitId + " has " + str(nrOfPorts) + " ports."
The error I am facing in is
Traceback (most recent call last):
File "cbrx_api_quickstart.py", line 9, in
result = cbrxapi.cbrx_discover("local")
File "/usr/local/share/cbrxapi/jsonrpc-0.1/jsonrpc.py", line 936, in call
return self.__req(self.__name, args, kwargs)
File "/usr/local/share/cbrxapi/jsonrpc-0.1/jsonrpc.py", line 908, in __req
raise RPCTransportError(err)
jsonrpc.RPCTransportError: [Errno 111] Connection refused
The product I am using is Cambrionix
Sorry for not explaining properly. I am still in learning phase..
Found the solution-
I have to install one more file to my system to get the code working..
$ sudo apt-get install avahi-daemon
And I need to ensure that one more script is running on my system.
install_service.sh in /usr/local/share/cbrxd/setup

pyvmomi deploy ovf templte

I am trying to deploy a ovf image in vcenter using the code in below link:
[https://github.com/vmware/pyvmomi-community-samples/blob/master/samples/deploy_ovf.py][1]
python vm_deploy.py -s ‘vcneter_url’ -u ‘username’ -p ‘password’ -v ‘.vmdk path’ -f ‘.ovf path’
But it is failing with below traceback:
Traceback (most recent call last):
File "orig.py", line 218, in <module>
exit(main())
File "orig.py", line 185, in main
objs = get_objects(si, args)
File "orig.py", line 150, in get_objects
resource_pool_obj = cluster_obj.resourcePool
AttributeError: 'vim.Folder' object has no attribute 'resourcePool'
Im not able to get much help on this error online other than below link:
[https://github.com/vmware/pyvmomi-community-samples/issues/201][1]
I can see dir(cluster_obj) has no resourcePool in it but not sure how to get this working.
This script work only if you have manually created a resource pool in your architecture.
However, with a little modification you can target the default resourcePool of a specific Host.
Replace, in get_objects function, this (~line 140) :
# Get cluster object.
cluster_list = datacenter_obj.hostFolder.childEntity
if args.cluster_name:
cluster_obj = get_obj_in_list(args.cluster_name, cluster_list)
elif len(cluster_list) > 0:
cluster_obj = cluster_list[0]
else:
print "No clusters found in DC (%s)." % datacenter_obj.name
hosts = datacenter_obj.hostFolder.childEntity
resource_pool = hosts[0].resourcePool
# Generate resource pool.
resource_pool_obj = cluster_obj.resourcePool
By this :
for computeResource in datacenter_obj.hostFolder.childEntity :
if computeResource.name == 'ip or hostname here':
resource_pool = computeResource.resourcePool
break
The datacenter_obj is given, in the script that you gave, with something lik this :
datacenter_obj = si.content.rootFolder.childEntity[0]
0 is the first Datacenter found.
I hope it will help you, even if the answer comes a little late

Trying to make a dynamic host file for ansible in python

This is my first post here, so if there are any questions or if something is unlcear, don't hesitate to ask.
I am trying to use a dynamic host file so I can build multiple vagrant machines without having to manage the host file first. This is what I found online:
#!/usr/bin/env python
# Adapted from Mark Mandel's implementation
# https://github.com/ansible/ansible/blob/devel/plugins/inventory/vagrant.py
import argparse
import json
import paramiko
import subprocess
import sys
def parse_args():
parser = argparse.ArgumentParser(description="Vagrant inventory script")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--list', action='store_true')
group.add_argument('--host')
return parser.parse_args()
def list_running_hosts():
cmd = "vagrant status --machine-readable"
status = subprocess.check_output(cmd.split()).rstrip()
hosts = []
for line in status.split('\n'):
(_, host, key, value) = line.split(',')
if key == 'state' and value == 'running':
hosts.append(host)
return hosts
def get_host_details(host):
cmd = "vagrant ssh-config {}".format(host)
p = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
config = paramiko.SSHConfig()
config.parse(p.stdout)
c = config.lookup(host)
return {'ansible_ssh_host': c['hostname'],
'ansible_ssh_port': c['port'],
'ansible_ssh_user': c['user'],
'ansible_ssh_private_key_file': c['identityfile'][0]}
def main():
args = parse_args()
if args.list:
hosts = list_running_hosts()
json.dump({'vagrant': hosts}, sys.stdout)
else:
details = get_host_details(args.host)
json.dump(details, sys.stdout)
if __name__ == '__main__':
main()
However, when I run this I get the following error:
ERROR! The file inventory/vagrant.py is marked as executable, but failed to execute correctly. If this is not supposed to be an executable script, correct this with `chmod -x inventory/vagrant.py`.
ERROR! Inventory script (inventory/vagrant.py) had an execution error: Traceback (most recent call last):
File "/home/sebas/Desktop/playbooks/inventory/vagrant.py", line 52, in <module>
main()
File "/home/sebas/Desktop/playbooks/inventory/vagrant.py", line 45, in main
hosts = list_running_hosts()
File "/home/sebas/Desktop/playbooks/inventory/vagrant.py", line 24, in list_running_hosts
(_, host, key, value) = line.split(',')
ValueError: too many values to unpack
ERROR! inventory/vagrant.py:4: Expected key=value host variable assignment, got: argparse
does anybody know what I did wrong? Thank you guys in advance!
I guess the problem is that vagrant status command will work only inside a directory with a Vagrantfile, or if the ID of a target machine is specified.
To get the state of all active Vagrant environments on the system, vagrant global-status should be used instead. But global-status has a drawback: it uses a cache and does not actively verify the state of machines.
So to reliably determine the state, first we need to get the IDs of all VMs with vagrant global-status and then check these IDs with vagrant status ID.

Robot Framework Keyword with Python: Error with unmatched string or IP. How to fix this?

I am trying to write a keyword for Robot Framework as #Brayan Oakley suggesed in Question :
How to write python function to test the matched strings (to use for Robot framework keyword)?
My Python file:
import os,re
def check_IP():
cmd = ' netstat -ano '
output = os.popen(cmd).read()
match1 = re.findall('.* (1.1.1.1).*',output)
mat1 = ['1.1.1.1']
if match1 == mat1:
print "IP addr found"
if match1 != mat1:
raise Exception('No matching IP...')
check_IP()
I am trying to match a IP address in "netstat -ano" command. If its matches, I am getting "IP addr found" message as expected.
But if IP address is not found I am getting exception as expected, but with below error messages.
C:\Users\test\Desktop>python check.py
Traceback (most recent call last):
File "check.py", line 13, in <module>
check_IP()
File "check.py", line 11, in check_IP
raise Exception('No matching IP...')
Exception: No matching IP...
C:\Users\test\Desktop>
Any clue to fix this please?
The code is doing precisely what you told it to do. You are running the code outside of the context of robot, and this is how python treats exceptions.
If you don't want to see the stack trace, catch the exception and print whatever message you want.
try:
check_IP()
except Exception as e
print str(e)
Of course, you'll want to remove all that code if you use check_IP as a keyword.
Use the Following Robot File:
*** Settings ***
Documentation Test Stability Tests
Library Network.py
*** Test Cases ***
Test: Test Robot File
Check Network Status
Use the following Python File
import os, re
def check_network_status():
cmd = ' netstat -ano '
output = os.popen(cmd).read()
match1 = re.findall('.* (1.1.1.1).*',output)
mat1 = ['1.1.1.1']
if match1 == mat1:
print("IP Address found")
elif match1 != mat1:
raise AssertionError("IP Address not Found")
Note: Do not call the function in the Python file.
Just create classes and function inside python file(if you want to in future).
They would automatically be called off at the run time.

Categories