import socket
import struct
def get_default_gateway_linux():
with open("/proc/net/route") as fh:
for line in fh:
fields = line.strip().split()
if fields[1] != '00000000' or not int(fields[3], 16) & 2:
continue
return socket.inet_ntoa(struct.pack("<L", int(fields[2], 16)))
def getNetworkIp():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('bt', 0))
return s.getsockname()[0]
print "Your Machine IP has been detected as "+getNetworkIp()
print "Your Gateway IP has been detected as "+get_default_gateway_linux()
the above code neither shows any error nor any output when executed in backtrack 5 R3
please help me regarding this code!
Your 2 print statements are tabbed/spaced. Remove them and it will work as I have confirmed this to work on CentOS 6.5:
def getNetworkIp():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('localhost',0))
return s.getsockname()[0]
print "Your Machine IP has been detected as "+getNetworkIp()
print "Your Gateway IP has been detected as "+get_default_gateway_linux()
This may be too simple to be true, but the last two lines are part of getNetworkIp(), since they are indented as such.
I even get an indentation error from Python when I try this.
Note that when I move those last 2 print statements out to column 0, I get another error, because I get a 'name or service not known' error ... but that's probably an old Linux/Python problem, or need root.
Anyway, try un-indenting those last two print statements.
Related
I'm brand new to Python (as of last week) and I'm still getting to grips with the basics so please excuse any ignorance I display.
As part of my homework I have been asked to make a basic port scanner and one of the functions I have to include is the retrieval of a list of sockets on the current machine. I have been looking around and managed to piece together a piece of code that allows me to enter the IP of the machine I wish to scan but I want to try and make it so it automatically scans whichever machine it is running on.
elif (userChoice == "4"):
print("You selected " + userChoice)
try:
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) # s will be equal to the command looking for the IPV4 addresses
except socket.error:
sys.exit("Failed to create socket.") # error handling message to be printed to the console should a socket failed to be created
print("Socket created")
hostAddress = input("Please enter host address to scan - example 'www.server.com': ")
print ("You entered " + hostAddress )
try:
remoteIP = socket.gethostbyname(hostAddress)
except socket.gaierror:
sys.exit("Hostname could not be resolved exiting")
ret = input("Hit return to go back to the menu")
continue
print("IP address of " + hostAddress + ' is ' + remoteIP)
This is my code so far. If anyone could help me out or tell me if I'm even going in the right direction with this I would be very grateful.
Also, with me being a noob, if anyone has any suggestions for good reading materials to help me get to get to grips with the basics I would very much appreciate it.
Thanks.
To check open ports on remote server-
# For input hostAddress
remoteIP = socket.gethostbyname(hostAddress)
for port in range(1,1025):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((remoteIP, port))
if result == 0:
print("Port %s: Open"%port)
sock.close()
=> Port 80: Open
So I'm working on a simple port scanner in python for a class (not allowed to use the python-nmap library), and while I can get it to work when passing a single IP address, I can't get it to work using a range of IPs.
This is what I have:
#!/usr/bin/env python
from socket import *
from netaddr import *
# port scanner
def port_scan(port, host)
s = socket(AF_INET, SOCK_STREAM)
try:
s = s.connect((host, port))
print "Port ", port, " is open"
except Exception, e:
pass
# get user input for range in form xxx.xxx.xxx.xxx-xxx.xxx.xxx.xxx and xx-xx
ipStart, ipEnd = raw_input ("Enter IP-IP: ").split("-")
portStart, portEnd = raw_input ("Enter port-port: ").split("-")
# cast port string to int
portStart, portEnd = [int(portStart), int(portEnd)]
# define IP range
iprange = IPRange(ipStart, ipEnd)
# this is where my problem is
for ip in iprange:
host = ip
for port in range(startPort, endPort + 1)
port_scan(port, host)
So when I run the code, after adding print statements below
host = ip
print host # added
and then again after
port_scan(port, host)
print port # added
I end up with the following output:
root#kali:~/Desktop/python# python what.py
Enter IP-IP: 172.16.250.100-172.16.250.104
Enter port-port: 20-22
172.16.250.100
20
21
22
172.16.250.101
20
21
22
...and so on
Thanks in advance everyone!
I appreciate any help that I can get!
code picture for reference, slightly different
output picture for reference
The problem turned out to be an issue with using the netaddr.IPRange, as suggested by #bravosierra99.
Thanks again everyone!
I'm new to Python programming and I'm trying to create a server and a client. I still want to be able to type something from the keyboard so i can close the server from the server by typing 'exit'. I've taken samples codes from various sites to get to where I'm at in socket programming and this code.
However, whenever I run the code I get the following error message:
The host name of this machine is 127.0.0.1
The IP address of the host is 127.0.0.1
Server now awaiting client connection on port 2836
im right before the select
Traceback (most recent call last):
File "/root/Server_2.py", line 42, in <module>
inputready, outputready, exceptready = select.select(input, [], [])
TypeError: argument must be an int, or have a fileno() method.
>>>
I was reading around that to get passed this (in Windows) is to remove the sys.stdin because Windows only accepts sockets. I'm trying to write this code in Linux. I've tried all sorts of things to try to get it to work and I'm all out of resources and ideas to try. Below is the server code:
import socket #import socket module
import select
import sys
host = "127.0.0.1"
print ("The host name of this machine is " + host)
hostIP = socket.gethostbyname(host) # get host IP address
print ("The IP address of the host is %s" % (hostIP))
port = 2836 # Reserve the port for the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((hostIP, port)) # This server to a port
s.listen(4) # Now wait for client connection
print("Server now awaiting client connection on port %s" % (port))
#WINDOWS ONLY ACCEPTS SOCKETS FOR SELECT(), no standard in
input = [s, sys.stdin]
running = 1
while running:
print("im right before the select")
# when there's something in input, then we move forward
# ignore what's in output and except because there's nothing
# when it comes to sockets
inputready, outputready, exceptready = select.select(input, [], [])
print("i'm here na")
# check who made a response
for x in inputready:
if x == s:
print(s)
#handle the server socket
client, address = s.accept()
print("connection comming in")
input.append(client)
elif x == sys.stdin:
# handle standard input
stuff = sys.stdin.readline()
if stuff == "exit":
running = 0
else:
print("you typed %s" % (stuff))
else:
#handle all other sockets
data = x.recv(1024)
print("i received " + data)
if data:
if data == "exit":
x.close()
input.remove(x)
running = 0
else:
x.send(data)
print("I am sending %s" % (data))
else:
x.close()
input.remove(x)
s.close()
Any help or ideas would be greatly appreciated. Thanks!!
Well I know you asked this 7 years ago, but I had similar questions so I would figure I answer you. I'm still working and bugfixing a program that has the same functionality, but one thing I do know is that the lists that are the arguments in select.select() need to be file descriptors (ints).
So if you have this block
input = [s, sys.stdin]
running = 1
while running:
print("im right before the select")
# when there's something in input, then we move forward
# ignore what's in output and except because there's nothing
# when it comes to sockets
inputready, outputready, exceptready = select.select(input, [], [])
The first thing I'd say is change your read list to not be input. You'll likely get some clashing with the input() function, which may cause confusing bugs. After that, you want the values to be file descriptors. So that first line should be
inputSockets = [s.fileno(), sys.stdin.fileno()]
Then when checking which socket is ready to ready, you would want to do it like this
for x in inputready:
if x == s.fileno():
# Read from your s socket
elif x == sys.stdin().fileno():
# Read from stdin
else:
'''
Here you would want to read from any other sockets you have.
The only problem is your inputSockets array has ints, not socket
objects. What I did was store an array of actual socket objects
alongside the array of file descriptors. Then I looped through the
list of sockets and found which socket's .fileno() matched x. You could
probably be clever and use a dict() with the filenos as key and socket as
value
'''
I just came across this while writing a unix domain socket (UDS) interface. The server socket id is used to accept incoming client connections. That is pretty much all it does. Once the client is accepted, reading uses its own file descriptor. Something like this works:
conn = None
inputReady, Null, Null = select.select(inputSockets, [], [])
for x in inputReady:
if x == s.fileno():
# accept incoming connect and add to poll list
conn, addr = s.accept()
inputReady.append(conn.fileno())
elif x = sys.stdin.fileno():
# read whole line and remove newline
cmd = sys.stdin.readline()[:-1]
...
elif conn and x == conn.fileno():
data = conn.recv(msglen)
if data:
....
else:
# connection has ended, remove from poll list and close
if conn.fileno() in inputReady:
inputReady.remove(conn.fileno())
conn.close()
I made a simple TCP fuzzer in Python. I need it to be able to receive some response and if I didn't get the response, break the loop. My code is this:
import socket
from time import sleep
import sys
ip = raw_input ("please insert host ip: ")
port = input ("please insert port to fuzz: ")
packet = raw_input ("what string would you like to fuzz with? : ")
multi = input ("in what jumps would you liike to multiply the string ? (10 = A*10) : ")
host = ip, port
s = socket.socket()
char = packet * multi
a = 1
try:
while a > 0:
s.connect((host))
s.send(packet)
sleep(1)
print 'fuzzing param %s' % (packet)
packet = char + packet
s.close()
except (Exception):
print "Connection lost for some reason"'
But when I run the program I get this error:
please insert host ip: 10.0.0.138
please insert port to fuzz: 80
what string would you like to fuzz with? : A
in what jumps would you liike to multiply the string ? (10 = A*10) : 2
fuzzing param A
Connection lost
which is weird because it just suppose to reconnect in an endless loop , (i know the server didn't crush)
The remote endpoint simply hung up, probably because the data you send doesn't match the format it expects.
You can either create a new connection every time the remote end hangs up, or send a data in the format that the remote end expects. For example, if the remote end is an HTTP server, you may want to send the request line first, and then the fuzzed part, like this:
GET / HTTP/1.0
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
When you fuzz testing (and in general) it is very important to handle errors. You should expect that something will get wrong when you are sending Gibberish to your server. So I suggest that you wrap the calls with try ... except ... finally: s.close() clause. And print debug messages to see when you are fail to send and start see why - You don't know how the server react to what you send, and you might just have killed the server after the first call...
I am looking at trying to create a python server, which allows me to run root commands on a Centos Server remotely, I would also like the server to be able to respond with the result's of the command.
I have found another question on here which has a basic python server, however it throws a error, the code is:
#!/usr/bin/python
import os
import socket
print " Loading Bindings..."
settings = {}
line = 0
for each in open('/root/actions.txt', 'r'):
line = line + 1
each = each.rstrip()
if each <> "":
if each[0] <> '#':
a = each.partition(':')
if a[2]:
settings[a[0]] = a[2]
else:
print " Err # line",line,":",each
print " Starting Server...",
port = 12345
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("", port))
print "OK."
print " Listening on port:", port
while True:
datagram = s.recv(1024)
if not datagram:
break
print "Rx Cmd:", datagram
if settings.has_key(datagram):
print "Launch:", settings[datagram]
os.system(settings[datagram]+" &")
s.close()
When i run using python vzctl.py. I get the following error:
File "vzctl.py", line 9
each = each.rstrip()
^
SyntaxError: invalid syntax
Does anyone have any idea of the error, and if it would be possible to add the function of the server responding with the output of the command.
You can see the source of this script at : How can I have a PHP script run a shell script as root?
Thanks,
Ashley
you need to keep indentation at the same level for each nested statement throughout your code.
On a different note: why not using TwistedMatrix?