Unable to telnet to Windows using socket module in python - python

Im using python3.3 version. I have Windows7 machine, I'm trying to write a program using socket module in python. I'm not to able get login prompt if I use socket module.
import socket
host = '10.155.208.33'
port= 23
s= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host,port))
data=s.recv(1024)
print(data)
>>> b"\xff\xfd%\xff\xfb\x01\xff\xfb\x03\xff\xfd'\xff\xfd\x1f\xff\xfd\x00\xff\xfb\x00"
s.sendall(b'\xff\xfe\x01\xff\xfd\x03\xff\xfc\x18\xff\xfc\x1f') >>> Im not sure whether this correct IAC client reply
data =s.recv(1024)
print(data)
>>>b'' <<< server response is empty.
Im not familar with IAC commands. Can somebody point to correct handshake used for communicating between client and server?
I tried using telnetlib module for python3.3, module doesnt works properly on my windows machine.
Thanks,
Anand

You may safely respond negatively to each IAC negotiation request. That is, for each IAC-DO, reply IAC-WONT. For each IAC-WILL, reply IAC-DONT.
You may find this code helpful:
def read(s):
while True:
data = s.recv(10240)
for do in re.findall('\xff\xfd.', data): # IAC DO cmd
s.send('\xff\xfc'+do[2]) # IAC WONT cmd
for will in re.findall('\xff\xfb.', data): # IAC WILL cmd
s.send('\xff\xfe'+will[2]) # IAC DONT cmd
data = re.sub('\xff[\xfb-\xfe].', '', data)
if data != '':
return data

Related

Writing an external program to interface with wpa_supplicant

I need to interact directly with wpa_supplicant from Python. As I understand it one can connect to wpa_supplicant using Unix sockets and wpa_supplicant control interface (https://w1.fi/wpa_supplicant/devel/ctrl_iface_page.html).
I wrote a simple program that sends a PING command:
import socket
CTRL_SOCKETS = "/home/victor/Research/wpa_supplicant_python/supplicant_conf"
INTERFACE = "wlx84c9b281aa80"
SOCKETFILE = "{}/{}".format(CTRL_SOCKETS, INTERFACE)
s = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
s.connect(SOCKETFILE)
s.send(b'PING')
while 1:
data = s.recv(1024)
if data:
print(repr(data))
But when I run it, wpa_supplicant reports an error:
wlx84c9b281aa80: ctrl_iface sendto failed: 107 - Transport endpoint is not connected
Could someone please provide an example, how you would do a 'scan' and then print 'scan_results'.
Apparently, the type of socket that wpa_supplicant uses (UNIX datagram) does not provide any way for the server to reply. There are a few ways to get around that. wpa_supplicant in particular seems to support replies through a separate socket (found at a path appended at the end of each message).
Weirdly enough, this seems to be a relatively common practice in Linux: /dev/log seems to work in the same way.
Here's a program that does what you asked for:
import socket, os
from time import sleep
def sendAndReceive(outmsg, csock, ssock_filename):
'''Sends outmsg to wpa_supplicant and returns the reply'''
# the return socket object can be used to send the data
# as long as the address is provided
csock.sendto(str.encode(outmsg), ssock_filename)
(bytes, address) = csock.recvfrom(4096)
inmsg = bytes.decode('utf-8')
return inmsg
wpasock_file = '/var/run/wpa_supplicant/wlp3s0'
retsock_file = '/tmp/return_socket'
if os.path.exists(retsock_file):
os.remove(retsock_file)
retsock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
retsock.bind(retsock_file)
replyToScan = sendAndReceive('SCAN', retsock, wpasock_file)
print(f'SCAN: {replyToScan}')
sleep(5)
replyToScanResults = sendAndReceive('SCAN_RESULTS', retsock, wpasock_file)
print(f'SCAN_RESULTS: {replyToScanResults}')
retsock.close()
os.remove(retsock_file)

Simple python telnet client/server example doesn't work

I'm trying to create mockup telnet server (for some functional testing of existing code). Right now I only modified server welcome message and I was trying to read this message using client code, but it read method fails on timeout with no additional info. But with pudb debugger enabled it works most of the time...
I'm using virtualenv, with pudb and telnetsrv installed using pip. Python 2.7.12, ubuntu 16.04.
Server code:
import SocketServer
from telnetsrv.threaded import TelnetHandler
class MyHandler(TelnetHandler):
WELCOME = "HI from custom server"
class TelnetServer(SocketServer.TCPServer):
allow_reuse_address = True
server = TelnetServer(("0.0.0.0", 8023), MyHandler)
server.serve_forever()
Client code:
import telnetlib
HOST = '127.0.0.1'
PORT = 8023
# from pudb import set_trace; set_trace()
tn = telnetlib.Telnet(HOST, PORT)
data = tn.read_until("custom server", timeout=1)
print "Data: " + data
tn.close()
Client output:
$ python client.py
Data:
Client output with pudb enabled (with step-by-step execution)
$ python client.py
Data: HI from custom server
Of course when I execute shell telnet command, it all works fine:
$ telnet 127.0.0.1 8023
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
HI from custom server
Telnet Server>
I'd really appreciate any hints on how to debug this problem. Thanks!
Be sure there is actually connecting going on. To do that put edit your code to add tn.set_debuglevel(100) into your script to look like this:
import telnetlib
HOST = '127.0.0.1'
PORT = 8023
# from pudb import set_trace; set_trace()
tn = telnetlib.Telnet(HOST, PORT)
tn.set_debuglevel(100)
data = tn.read_until("custom server", timeout=1)
print "Data: " + data
tn.close()
This will ensure all the data is printed out so you can see what's going on.
My theory is, that you're not connecting, or that your data isn't actually outputting "custom server" and therefor it won't catch it, or your timeout is too low.

testing client- server on the same computer

I am trying to test socket communication on my laptop using python. However, I'm not sure why the connection is not being established? I keep getting error that the target machine is actively refusing connection. I am trying to use the same computer to run both the client and the server portion. The server is running fine but the client is the one not connecting. I think I have the hostname wrong (127.0.0.1) but not sure what Im supposed to be using? I also tried changing the server hostname to (0.0.0.0) and the IPV4 address for the hostname the client was to connect to but that didn't work either. Any help would be appreciated!
My code(server portion):
import socket
comms_socket =socket.socket()
comms_socket.bind(('127.0.0.1', 50000))
comms_socket.listen(10)
connection, address = comms_socket.accept()
while True:
print(connection.recv(4096).decode("UTF-8"))
send_data = input("Reply: ")
connection.send(bytes(send_data, "UTF-8"))
Client portion:
import socket
comms_socket = socket.socket()
comms_socket.connect(('127.0.0.1',50000))
while True:
send_data = input("Message: ")
comms_socket.send(bytes(send_data, "UTF-8"))
print(comms_socket.recv(4096).decode("UTF-8"))
Your code won't work with python 2.* , because of the differences in input(), raw_input(), bytes, etc. in python 3.* vs python 2.* . You'd have to minimally make the following changes to get it working with python 2.*. Otherwise, use python 3 to run your code:
Server program:
import socket
comms_socket =socket.socket()
comms_socket.bind(('127.0.0.1', 7000))
comms_socket.listen(10)
connection, address = comms_socket.accept()
while True:
print(connection.recv(4096).decode("UTF-8"))
send_data = raw_input("Reply: ") # Use raw_input() instead of input()
connection.send(send_data.encode("UTF-8"))
Client program:
import socket
comms_socket = socket.socket()
comms_socket.connect(('127.0.0.1',7000))
while True:
send_data = raw_input("Message: ")
comms_socket.send(send_data.encode("UTF-8"))
print(comms_socket.recv(4096).decode("UTF-8"))
If you want to use bytes as intended in your specific usecase, you should use bytesarray instead in python 2.6 or higher. Check this: the bytes type in python 2.7 and PEP-358

How to interact with Remote Server using Python Sockets

I am trying to connect to a server using python sockets. I am able to make a connection and fetch the response data. However, I want the socket communication to be interactive from the client side.
For instance, if I use netcat to connect to the server, the communication is interactive:
nc aa.bb.cc.dd 1234
Server greets you
I can enter the input here
Server responds to my input
However, when I make the connection using python sockets, all I receive is the greeting from the Server and program completes execution.
Here is the python code I am using:
#! /usr/bin/python
import os
import sys
import socket
host = "aa.bb.cc.dd"
port = 1234
remote_ip = socket.gethostbyname(host)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((remote_ip, port))
print s.recv(1024)
I want to modify the above python program so that I can send inputs to the Server as well.
Thanks.
Usually you do
input_data = input("Enter something: ")
s.send(bytes(input_data,'utf-8'))
You could use a while loop to get user input, send to server, and get a response continuously.
while True:
print(str(s.receive(1024)))
toSend = input()
s.send(bytes(toSend, "utf-8"))

Receiving files python socket server

I was trying to create a python socket server that could send and receive data, so I created a socket on the server using the code here:
import socket
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('', 1208))
serversocket.listen(5)
(client,(ip,port)) = serversocket.accept()
Then I tried to create a sample connection from my machine by going to command prompt and typing
telnet www.filesendr.com 1208
However, the console simply replies with "Could not open connection to the host, on port 1208...Connection failed." I went back over my code but couldn't identify the problem. Any help would be greatly appreciated.
I think part of the problem is that after you accept the connection you don't do anything else. Once the accept happens, you get to the end of the script, python exits and closes all open file handles (including the socket you just opened). If you want to be able to talk to yourself through telnet, try something like this:
import socket
import select
import sys
port = 1208
listener = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
listener.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
listener.bind(('',port))
listener.listen(128)
newSock, addr = listener.accept()
while True:
r,w,e = select.select([newSock,sys.stdin],[],[])
if newSock in r:
data = newSock.recv(4096)
sys.stdout.write(data)
if sys.stdin in r:
newSock.send(sys.stdin.readline())

Categories

Resources