_socketobject' object has no attribute 'bing' - python

First I wanna say I am new to python I mostly use to do programming in java so forgive me if the answer is obvious but I am having the error (_socketobject' object has no attribute 'bing') when I run my script but I cant see anything wrong with it....
import socket
import sys
import threading
import paramiko
host_key = paramiko.RSAKey
(filename='/home/moonman/Desktop/test_rsa.key')
class Server (paramiko.ServerInterface):
def __init__(self):
self.event = threading.Event()
def check_channel_request(self, kind, chanid):
if kind == 'session':
return paramiko.OPEN_SUCCEEDED
return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED
def check_auth_password(self, username, password):
if (username == 'moonman') and (password == 'lover23567'):
return paramiko.AUTH_SUCCESSFUL
return paramiko.AUTH_FAILED
try:
global sock
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bing(('192.168.1.13' , 22))
sock.listen(1)
print '[+] Listening for Connection ...'
except Exception, e:
print '[-] Cant start listening ): ' + str(e)
try:
client, addr = sock.accept()
print '[+] Just got a reverse connection from ' + str(addr)
t = paramiko.Transport(client)
t.load_server_moduli()
t.add_server_key(host_key)
server = Server()
t.start_server(server=server)
global chan
chan = t.accept(1)
print chan.recv(1024)
chan.send("Connection Understood! Loud and clear!!")
except:
print "[-] Connection just died"
pass

Socket object has no attribute as bing. I guess you meant sock.bind which binds the socket to the address you defined.
Try this:
sock.bind(('192.168.1.13' , 22))

Related

How can I use a local variable declared in one function and implement it to another function? (Without global variables or calling the function)

import socket, sys
def create_socket(): # Creates a socket which connects two or more computers together
host = ""
port = 9999
socket_ = socket.socket()
try:
host
port
socket_
except socket.error as msg:
print("Socket Creation Error: " + str(msg))
return host, port, socket_
def bind_Socket(): # Binds the Socket and listening for connections
host, port, socket_ = create_socket()
try:
host
port
socket_
print("Binding the Socket: " + str(port))
socket_.bind((host, port))
socket_.listen(5)
except socket.error as msg:
print("Socket Creation Error: " + str(msg) + "Retrying....")
bind_Socket()
return host, port, socket_
def socket_accept(): # Establishes a connection with a client (socket must be listening)
host, port, socket_ = bind_Socket()
conn, address = socket_.accept()
send_command(conn)
print("Connection successful... " + "IP: " + address[0] + "\n" + "Port: " + address[1])
def send_command(conn): # Sends command to client
host, port, socket_ = bind_Socket()
cmd = ""
while (cmd != "Quit"):
cmd = input("Enter a command: ")
if(len(str.encode(cmd)) > 0):
conn.send(str.encode(cmd))
client_response = str(conn.recv(1024,"UTF-8"))
print(client_response, end="")
else:
conn.close()
socket_.close()
sys.exit()
def main():
create_socket()
bind_Socket()
socket_accept()
main()
The problem is when I call the bind_Socket() in main() It will print out "Binding the Socket: 9999" twice because it's also being called in the function socket_accept(). I just want to know how to use the same variables declared in one function and implement it in another without using global variables or calling the function like I did.
Functions can return objects to be used by other functions as arguments.
Set main up like this:
def main():
_, _, socket_ = bind_Socket()
socket_accept(socket_)
Then update _accept to accept args:
def socket_accept(socket_):
conn, address = socket_.accept()
....
Thus passing the socket object to the accept method.

Python Socketserver client timeout

I have a socketserver in Python which has to handle multiple clients using the select.select method, as seen in the code below:
import socket
import select
class Server:
def __init__(self):
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.bind(('localhost', 2000))
self.socket_list = [self.server]
self.addresses = ['localhost']
self.commands = [""]
self.running = True
self.server.listen(10)
def listen(self):
while self.running:
read, write, error = select.select(self.socket_list, [], self.socket_list, 0)
for sock in read:
if sock == self.server and self.running:
try:
conn, address = self.server.accept()
conn.settimeout(30)
self.socket_list.append(conn)
self.addresses.append(address[0])
self.commands.append("")
except:
self.shutdown()
break
elif self.running:
try:
packet = sock.recv(60)
if not packet:
self.close_conn(sock)
index = self.socket_list.index(sock)
self.commands[index] += packet
if '\n' in self.commands[index]:
#handle command
except:
self.close_conn(sock)
def close_conn(self, conn):
#close client conn
def shutdown(self):
#shutdown server
if __name__ == "__main__":
Server().listen()
The problem i currently have is that the client's connection should be closed after 30 seconds, but that doesn't happen, even though i declared that by using conn.settimeout(30). I haven't found any explanation yet as to why this happens.
Note: comments were used to replace parts of the code that didn't mater to the problem.

Python Server NameError: global name 'SocketError' is not defined

I wanted to make a connection between a sever and a client, so the server sends a string to the client.
Here is the Server:
import socket
def Main():
host = '190.176.141.23'#ip changed
port = 12345
while True:
s = socket.socket()
s.bind((host,port))
s.listen(1)
c, addr = s.accept()
print "Connection from: " + str(addr)
command = c.recv(1024)
if command == 'GIVETEXT':
c.send('test')
try:
c.close()
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
except SocketError as e:
if e.errno != errno.ECONNRESET:
raise
pass
if __name__ == '__main__':
Main()
And here is the Client I made:
import socket
class Client(object):
def __init__(self, *args):
self.s = socket.socket()
def sent(self, host, port):
self.s.connect((host, port))
self.s.send('GIVETEXT')
self.Text = self.s.recv(1024)
print self.Text
self.s.close
return self.Text
Needless to say, that I executed the method in another piece of code, and it worked. But after that the server crashed, with the error message:
NameError: global name 'SocketError' is not defined
It is socket.error; not SocketError. Change your except line to:
except socket.error as e:

Can a Server listens to a UDP messages without IP configured

Please look at the following python code.
I created a Server class to listen on port 10000 to receive UDP broadcast messages.
If IP address is configured in the system, it can receive UDP broadcast messages. If no ip address configured, it cannot receive any messages.
Could you tell me why?
import socket
import sys
class Server:
class Handler:
def handle(self, message):
pass
def __init__(self, serialNo):
self.serialNo = serialNo
def _setAddress(self, socket, message, address):
self.message = message
self.address = address
self.socket = socket
def send(self, message):
self.socket.sendto(message, self.address)
def getSerialNo(self):
return self.serialNo
def __init__(self, port, handler):
self.ss = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.ss.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.ss.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
self.handler = handler
try:
self.ss.bind(('<broadcast>', port))
except:
self.ss.close()
raise RuntimeError("Create socket error")
self.ss.setblocking(1)
def loop(self):
while True:
try:
print "Listening for broadcast..."
message, address = self.ss.recvfrom(8192)
print "Got request from %s:%s" % (address, message)
self.handler._setAddress(self.ss, message, address)
self.handler.handle(message)
except (KeyboardInterrupt, SystemExit):
raise
except:
sys.exc_info()[0]
After referring to pydhcp client code, I made following changes:
import socket
import sys
import select
class Server:
class Handler:
def handle(self, message):
pass
def __init__(self, serialNo):
self.serialNo = serialNo
def _setAddress(self, socket, message, address):
self.message = message
self.address = address
self.socket = socket
def send(self, message):
self.socket.sendto(message, self.address)
def getSerialNo(self):
return self.serialNo
def __init__(self, port, handler):
self.ss = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.ss.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.ss.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
self.handler = handler
try:
self.ss.bind(("0.0.0.0", int(port)))
except:
self.ss.close()
raise RuntimeError("Create socket error")
def loop(self):
while True:
try:
print "Listening for broadcast..."
data_input,data_output,data_except = select.select([self.ss],[],[], 60)
if (data_input != []):
(message, address) = self.ss.recvfrom(2048)
print "Got request from %s:%s" % (address, message)
self.handler._setAddress(self.ss, message, address)
self.handler.handle(message)
else:
print "no data within 60 seconds"
except (KeyboardInterrupt, SystemExit):
raise
except:
sys.exc_info()[0]
Now it can receive the broadcasting packets, but it cannot work on RedHat.

Python SocketServer.TCPServer errno 10054

I'm running a python server using the socketserver module in python 2.7. OmniPeek packet analysis tool shows the TCP handshake completes,
but the server immediately sends a reset packet killing the connection.
Simplified server code which shows the problem is:
from threading import Lock, Thread, Condition
import SocketServer
import socket
import sys
import time
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def __init__(self, state, *args, **keys):
try:
state['lock'].acquire()
state['client_count'] += 1
finally:
state['lock'].release()
self.state = state
SocketServer.BaseRequestHandler.__init__(self, *args, **keys)
def handle(self):
self.state['lock'].acquire()
count = self.state['client_count']
self.state['lock'].release()
while True:
try:
self.state['lock'].acquire()
running = self.state['running']
self.state['lock'].release()
if not running:
break;
time.sleep(1) # do some work
except Exception as msg:
print msg
print "ThreadedTCPRequestHandler shutting down..."
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
def handler_factory(state):
def createHandler(*args, **keys):
return ThreadedTCPRequestHandler(state, *args, **keys)
return createHandler
if __name__ == "__main__":
lock = Lock()
cv = Condition(lock)
state = {'running': True, 'client_count': 0, 'lock': lock, 'cv': cv}
server = ThreadedTCPServer(('localhost', 12345), handler_factory(state))
server_thread = Thread(target=server.serve_forever)
server_thread.daemon = True
server_thread.start()
print "Server loop running in thread:", server_thread.name
# wait for a client to connect
cv.acquire()
while state['client_count'] == 0 and state['running']:
cv.wait(1.0)
# print msg
cv.release()
# substitute real work here...
time.sleep(5)
lock.acquire()
state['running'] = False
lock.release()
server.shutdown()
and the client code:
import socket
if __name__ == "__main__":
try:
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'ip: {} port {}'.format('10.4.2.54', 12345)
client.connect(('10.4.2.54', 12345))
while True:
data = client.recv(4096)
if len(data) == 0:
break;
print 'data: {}'.format(data)
client.shutdown(socket.SHUT_RDWR)
client.close()
except Exception as msg:
print msg
The server code is based off python 2.7 docs serversocket Mixin example, and seems pretty straightforward, but...
Thanks
not sure what your expected behaviour is but if you make a couple of changes, you'll be able to see that it can work
replace your handle method
def handle(self):
while True:
try:
data = self.request.recv(1024).strip()
if len(data) != 0:
print data
time.sleep(1) # do some work
self.request.send('test data')
except Exception as msg:
print msg
break
print "ThreadedTCPRequestHandler shutting down..."
and client(inside main):
try:
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'ip: {} port {}'.format('localhost', 1232)
client.connect(('localhost', 1232))
client.send('test')
n = 0
while True:
data = client.recv(4096)
if len(data) != 0:
print 'data: {}'.format(data)
time.sleep(1)
n += 1
client.send('keep-alive' + str(n) + '\n')
print 'here'
client.shutdown(socket.SHUT_RDWR)
client.close()
except Exception as msg:
print msg
I just modded it to send stuff and print stuff. But it doesn't crash.
I think there is an issue with your self.state['lock'].acquire() and release() calls. I took out the 'running' check as it's not really used except at the end of the server code.
Also, without any action, sockets will time out.
Once again, I'm not claiming to have 'fixed' your problem...and I'm not sure exactly what you are looking for...just helping you brainstorm!
Apologies - red herring. The problem is only occurring under VM when server is running under guest and client is running under host. TCP reset packet never sent when both client and server are running either on host or guest

Categories

Resources