Unsolved Reference IP() and TCP() When Using Scapy - python-2.7

I copied the codes from the example to learn scapy. But realized the IDE showed the error with unsolved reference for IP() & TCP(). Anyone know how to fix this?
Here are the codes:
#! /usr/bin/env python
from scapy.all import *
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
dst_ip = "10.0.0.1"
src_port = RandShort()
dst_port=80
tcp_connect_scan_resp = sr1(IP(dst=dst_ip)/TCP(sport=src_port,dport=dst_port,flags="S"), timeout=10)
if(str(type(tcp_connect_scan_resp))==""):
print("Closed")
elif(tcp_connect_scan_resp.haslayer(TCP)):
if(tcp_connect_scan_resp.getlayer(TCP).flags == 0x12):
send_rst =sr(IP(dst=dst_ip)/TCP(sport=src_port,dport=dst_port,flags="AR"),timeout=10)
print("Open")
elif (tcp_connect_scan_resp.getlayer(TCP).flags ==0x14):
print("Closed")
I'm using Pycharm IDE. Python2.7 and scapy 2.4.0. I searched on stackoverflow and found someone asked the same question before but no answer.....
Here is the error after I tried to run the codes:
/Users/chenneyhuang/PycharmProjects/Scanner/venv/bin/python /Users/chenneyhuang/PycharmProjects/Scanner/TCP.py
Traceback (most recent call last):
File "/Users/chenneyhuang/PycharmProjects/Scanner/TCP.py", line 12, in <module>
tcp_connect_scan_resp = sr1(IP(dst=dst_ip)/TCP(sport=src_port,dport=dst_port,flags="S"), timeout=10)
File "/Users/chenneyhuang/PycharmProjects/Scanner/venv/lib/python2.7/site-packages/scapy/sendrecv.py", line 393, in sr1
s=conf.L3socket(promisc=promisc, filter=filter, nofilter=nofilter, iface=iface)
File "/Users/chenneyhuang/PycharmProjects/Scanner/venv/lib/python2.7/site-packages/scapy/arch/bpf/supersocket.py", line 58, in __init__
(self.ins, self.dev_bpf) = get_dev_bpf()
File "/Users/chenneyhuang/PycharmProjects/Scanner/venv/lib/python2.7/site-packages/scapy/arch/bpf/core.py", line 98, in get_dev_bpf
raise Scapy_Exception("No /dev/bpf handle is available !")
scapy.error.Scapy_Exception: No /dev/bpf handle is available !
Process finished with exit code 1

I answered the same Unsolved Reference issue last week here:
vscode import error: from scapy.all import IP
In short, don't worry about that error, it's a limitation of Pylint (or similar). I propose a workaround in the other question, if you'd like to remove the error/warning.
For the No /dev/bpf handle is available error, have you tried running the script as root? I see that suggested as a solution over on this GitHub issue: https://github.com/secdev/scapy/issues/1343

Related

pyomo mindtpy example program when run becomes unfeasible for binary variable

So I installed pyomo, glpk, and ipopt with anaconda,
When I run the example code here: https://pyomo.readthedocs.io/en/stable/contributed_packages/mindtpy.html
from pyomo.environ import *
model = ConcreteModel()
model.x = Var(bounds=(1.0,10.0),initialize=5.0)
model.y = Var(within=Binary)
model.c1 = Constraint(expr=(model.x-3.0)**2 <= 50.0*(1-model.y))
model.c2 = Constraint(expr=model.x*log(model.x)+5.0 <= 50.0*(model.y))
model.objective = Objective(expr=model.x, sense=minimize)
SolverFactory('mindtpy').solve(model, mip_solver='glpk', nlp_solver='ipopt',tee=True)
model.objective.display()
model.display()
model.pprint()
I get the output that the binary variable has apparently become infeasible:
python minlpex.py
INFO: ---Starting MindtPy---
INFO: Original model has 2 constraints (2 nonlinear) and 0 disjunctions, with
2 variables, of which 1 are binary, 0 are integer, and 1 are continuous.
INFO: NLP 1: Solve relaxed integrality
INFO: NLP 1: OBJ: 1.0 LB: 1.0 UB: inf
INFO: ---MindtPy Master Iteration 0---
INFO: MIP 1: Solve master problem.
WARNING: Empty constraint block written in LP format - solver may error
Traceback (most recent call last):
File "minlpex.py", line 13, in <module>
op.SolverFactory('mindtpy').solve(model, mip_solver='glpk', nlp_solver='ipopt',tee=True)
File "/anaconda3/envs/py36/lib/python3.6/site-packages/pyomo/contrib/mindtpy/MindtPy.py", line 370, in solve
MindtPy_iteration_loop(solve_data, config)
File "/anaconda3/envs/py36/lib/python3.6/site-packages/pyomo/contrib/mindtpy/iterate.py", line 30, in MindtPy_iteration_loop
handle_master_mip_optimal(master_mip, solve_data, config)
File "/anaconda3/envs/py36/lib/python3.6/site-packages/pyomo/contrib/mindtpy/mip_solve.py", line 62, in handle_master_mip_optimal
config)
File "/anaconda3/envs/py36/lib/python3.6/site-packages/pyomo/contrib/gdpopt/util.py", line 199, in copy_var_list_values
v_to.set_value(value(v_from, exception=False))
File "/anaconda3/envs/py36/lib/python3.6/site-packages/pyomo/core/base/var.py", line 173, in set_value
if valid or self._valid_value(val):
File "/anaconda3/envs/py36/lib/python3.6/site-packages/pyomo/core/base/var.py", line 185, in _valid_value
"domain %s" % (val, type(val), self.domain))
ValueError: Numeric value `0.22709088987977885` (<class 'float'>) is not in domain Binary
So I was a little confused, since this was a code provided, I would not expect it to error like this. So I feel like I'm messing something up or I am missing some required library?
Thanks a lot.
Looks like something must be wrong with the conda pyomo install or ipopt install.
When I reinstalled using pip for ipopt and compiling pyomo from github source everything works fine.

Running stem with tor gives "Process terminated: Timed out"

While trying to run Stem's To Russia With Love example, I am getting the following error:
~$ python practice.py
Starting Tor:
Traceback (most recent call last):
File "practice.py", line 49, in <module>
init_msg_handler = print_bootstrap_lines,
File "/usr/local/lib/python2.7/dist-packages/stem/process.py", line 266, in launch_tor_with_config
return launch_tor(tor_cmd, args, torrc_path, completion_percent, init_msg_handler, timeout, take_ownership)
File "/usr/local/lib/python2.7/dist-packages/stem/process.py", line 143, in launch_tor
raise OSError('Process terminated: %s' % last_problem)
OSError: Process terminated: Timed out
I was initially getting the path error that was solved over here. I tried restarting the Ubuntu instance (I am running Ubuntu 14.04 in VirtualBox) just in case if any other running tor was conflicting but its giving the same error. Could anyone please help?
EDIT: My torrc file also seems to be empty right now if this is in any way connected.
It might be failing because you are missing the GeoIP database which is required to use an exit node from a specific country.
Try removing the 'ExitNodes': '{ru}', line from the python script, or since you're on Ubuntu, try sudo apt-get install tor-geoipdb and see if that helps get the connection up and running.
Since it takes time to build the circuits, you can try increasing the timeout a bit as well (though this probably isn't why its failing).
tor_process = stem.process.launch_tor_with_config(
#tor_cmd = '/usr/bin/tor',
timeout = 300,
config = {
'SocksPort': str(SOCKS_PORT),
# 'ExitNodes': '{ru}',
'DataDir': '/tmp/tor',
'Log': [
'NOTICE file /tmp/tor.notice.log',
'ERR file /tmp/tor.log',
],
},
init_msg_handler = print_bootstrap_lines,
)

I don't understand how this "os.join" function is working? I am getting errors constantly and no reading on os functions is helping me

Here's the code
sys.path.append( "../tools/" )
from parse_out_email_text import parseOutText #(its just another .py file that has a function I wrote)
from_sara = open("from_sara.txt", "r")
from_chris = open("from_chris.txt", "r")
from_data = []
word_data = []
temp_counter = 0
for name, from_person in [("sara", from_sara), ("chris", from_chris)]:
for path in from_person:
### only look at first 200 emails when developing
### once everything is working, remove this line to run over full dataset
temp_counter += 1
if temp_counter < 200:
path = os.path.join('..', path[:-1]) #(THIS IS THE PART I CAN'T GET MY HEAD AROUND)
print path
email = open(path, "r")
email.close()
print "emails processed"
from_sara.close()
from_chris.close()
When I run this, it gives me an error as shown below:
Traceback (most recent call last):
..\maildir/bailey-s/deleted_items/101.
File "C:/Users/AmitSingh/Desktop/Data/Udacity/Naya_attempt/vectorize_text.py", line 47, in <module>
email = open(path, "r")
IOError: [Errno 2] No such file or directory: '..\\maildir/bailey-s/deleted_items/101.'
I don't even have this """'..\maildir/bailey-s/deleted_items/101.'""" directory path on my laptop, I tried to change the path by replacing the '..' in the code by the actual path name to the folder where I keep all the files, and nothing changes.
path = os.path.join('..', path[:-1])
This code is part of an online course on machine learning and I have been stuck at this point for 3 hours now. Any help would be really appreciated.
(P.S. This is not a homework question and there are no grades attached to this, its a free online course)
your test data is not there so it cannot find it. you should run start-up code again and make sure the necessary maildir are all there.
Go to tools inside your udacity project directory and run startup.py.
It is about 400 Mb so sit back and relax!
I know this is extremely late, but I found this post after having the exact same problem.
All the answers that I found here and on other sites, even the issue requests in the original github, were just "run startup.py" I already did that. However, it was telling me:
Traceback (most recent call last):
File "K:\documents\Udacity\Mini-Projects\ud120-projects\text_learning\vectorize_text.py", line 48, in <module>
email = open(path, "r")
FileNotFoundError: [Errno 2] No such file or directory: '..\\maildir/bailey-s/deleted_items/101.'
Just like yours. I then found where this file was located and it was indeed on my computer
I added 'tools' to the os.path.join() line as you can see here:
for name, from_person in [("sara", from_sara), ("chris", from_chris)]:
for path in from_person:
### only look at first 200 emails when developing
### once everything is working, remove this line to run over full dataset
temp_counter += 1
if temp_counter < 200:
#path = os.path.join('..', path[:-1]) <---original
path = os.path.join('..','tools', path[:-1])
print(path)
email = open(path, "r")
This worked for me finally. So, I hope it helps anyone else that stumbles on this problem in the future.
Also, I noticed on some examples I found of other repos of the lessons. Their 'tools' folder was named 'utils'.
Here is an example, this is a repo that someone tweaked to use jupyter notebooks to run the lessons So, use the one that you have.
In your Udacity course folder, first go to tools directory, check if you have maildir folder present and if it has got subfolders in it, if they are present then go back to text_learning/vectorize_text.py, find this line of code path = os.path.join('..', path[:-1]), change it to path = os.path.join('../tools/', path[:-1]),
On terminal, cd text_learning , then python vectorize_text.py, this should solve the issue.
If this does not solve the issue, then Go to tools inside your udacity project directory and run startup.py. Wait till the process is complete
Repeat step 1.

Creating a single executable .exe from Python script that uses PuLP

I have been struggling with this for a while. I have used py2exe and cx_freeze to package everything. I am using a 32 bit machine and Everything works fine and the interface opens up and everything just that I know the entire puLP package is not being copied correctly into the package. I know this because the solver does not work. Inside both library zips in the packages created by py2exe and cx_freeze, there are only .pyc files included where PuLP has cbc.exe and other file types that make the solver work.
Is there any work around this? I have tried copying the actual PuLP package into the library.zip as well as into the dist folder and that didn't work.
Here is the setup I used for py2exe:
import sys
from cx_Freeze import setup, Executable
# Dependencies are automatically detected, but it might need fine tuning.
build_exe_options = {"packages": ["pulp"],
"icon": "icon.ico",
"include_files": ["icon.ico","cbc.exe","cbc-32","cbc-64","cbc-osx-64","CoinMP.dll"]}
# GUI applications require a different base on Windows (the default is for a
# console application).
base = None
if sys.platform == "win32":
base = "Win32GUI"
setup( name = "my_app",
version = "0.1",
options = {"build_exe": build_exe_options},
executables = [Executable("my_app.py", base=base)])
I received the following error:
Exception in Tkinter callback
Traceback (most recent call last):
File "Tkinter.pyc", line 1470, in __call__
File "my_app.py", line 796, in <lambda>
File "my_app.py", line 467, in branchAndBound
File "pulp\pulp.pyc", line 1619, in solve
AttributeError: 'NoneType' object has no attribute 'actualSolve'
EDIT
I tried to change the paths to cbc.exe and CoinMP.dll but that didn't really work either. I am probably missing something.
I changed the following inside solvers.py in the PuLP package:
try:
coinMP_path = config.get("locations", "CoinMPPath").split(', ')
except configparser.Error:
coinMP_path = ['/Users/al/Desktop/my_app/build/exe.win32-2.7']
try:
cbc_path = config.get("locations", "CbcPath")
except configparser.Error:
cbc_path = '/Users/al/Desktop/my_app/build/exe.win32-2.7'
try:
pulp_cbc_path = config.get("locations", "PulpCbcPath")
except configparser.Error:
pulp_cbc_path = '/Users/al/Desktop/my_app/build/exe.win32-2.7'
What am I missing or doing wrong?

Installing NodeboxOpenGL on windows

Hello I am trying to install and make use of NodeboxOpenGL, the python library so I can create my own graphs with nodes and edges. But I am running into some trouble,
starting off at NodeBox OpenGL site. I downloaded NodeBox for OpenGL and then pyglet, I then did easy_install nodebox-opengl.
Note I did not do pip install
I installed pyglet from pyglet. So now I am thinking its all ready to go. I did a quick check of my c:\python27\Lib\site-packages\ location just be sure the nodebox folder was there, all seems good.
I tried the sample program that's on the site
from nodebox.graphics import *
from nodebox.graphics.physics import Flock
flock = Flock(40, 0, 0, 500, 500)
flock.sight = 300
def draw(canvas):
background(1)
fill(0, 0.75)
flock.update(cohesion=0.15)
for boid in flock:
push()
translate(boid.x, boid.y)
scale(0.5 + 1.5 * boid.depth)
rotate(boid.heading)
arrow(0, 0, 15)
pop()
canvas.fps = 30
canvas.size = 600, 400
canvas.run(draw)
tried to run it, but i keep getting this error
Traceback (most recent call last):
File "E:\Workspace\ElasticNodes\graph1.py", line 5, in <module>
from nodebox.graphics import *
File "E:\Workspace\ElasticNodes\nodebox\graphics\__init__.py", line 1, in <module>
import bezier
File "E:\Workspace\ElasticNodes\nodebox\graphics\bezier.py", line 10, in <module>
from context import BezierPath, PathElement, PathError, Point, MOVETO, LINETO, CURVETO, CLOSE
File "E:\Workspace\ElasticNodes\nodebox\graphics\context.py", line 29, in <module>
import geometry
File "E:\Workspace\ElasticNodes\nodebox\graphics\geometry.py", line 454, in <module>
from pyglet.gl import \
ImportError: cannot import name pointer
I tried modifying the python script i.e
In your script, add the location of NodeBox to sys.path, before importing it: >>> MODULE = '/users/tom/python/nodebox' >>> import sys; if MODULE not in sys.path: sys.path.append(MODULE) >>> import nodebox
But still the same error.
I am using Python2.7, running on windows. I am not sure what I am doing wrong. Has anyone got any experience with running this library on windows. What am I doing wrong
Maybe this helps you:
In geometry.py del "pointer" import. Replace pointer(data) to POINTER(data)
I also had another error, so maybe you need add import to "shaders.py": from ctypes import c_uint
I am having a similar problem with Linux. The Nodebox-opengl site ( http://www.cityinabottle.org/nodebox/ ) says that python 2.5 or 2.6 must be used, so it is possible that the problem is that you are using 2.7.
EDIT:
Ok, I installed pyglet first, with pip (and or apt-get, I did both) and I don't get a problem with pyglet. But I still do get other problems.