I have been working on a small toolkit for awhile now as a way to learn basic python. part of this toolkit is the code that follows this explanation. It is a basic network enumeration script, to simply ping all ip addresses in your local subnet. However I am having an issue implementing a few pieces.
first the code
ip1=raw_input()
if ip1 == None:
ip="192.168.0.x"
else:
ip=ip1
ipend="1"
while ipend != 255:
ip.replace("x", ipend)
attempt=subprocess.Popen(["ping.exe", ip], stdout=subprocess.PIPE).communicate()[0]
if ("unreachable" in attempt):
pass
else:
print "The host at ", ip, "is UP!"
ipend += 1
if ipend == "255":
subprocess.stop
raw_input("Thank you for using PTK. Please press enter to exit.")
enum()
so my first issue, I believe is in my str.replace function, I am attempting to and an int to a str and due to this it seems to be unable to create, ping, and print the correct ip. I'm unsure if converting the entire string to a floating int would work, however its a thought I'm toying with. as previously stated I am very basic with python and am working on learning so please forgive me if this a stupid question with a simple fix.
This line doesn't actually do anything. You need to assign the result to something.
ip.replace("x", ipend)
ipend is a string, incrementing a string won't work. Make it a int and convert it to a str in the replace function.
ipend += 1
And it's usually better to use a for loop if you can, so you're safe from messing up and creating a infinite loop.
for ipend in range(1,256): #Range won't actually give you the last number here.
#Do stuff
Related
As part of a piece of python work I have to ask for a first name and surname, then repeat it three times if it is correct. When I try it Python puts a syntax error on the colon. What do I need to do to correct it?
Basically whats going on
I've already tried removing the colon, bringing the if line down to one equals, and looking for bracket errors, but I cant find anything.
The colon should be at the end,
if input == yes:
However I cannot see how this can work? Is that the full code? If so, what is the yes variable?
If it was intended to be a string, the line should be,
if input == "yes":
The "" tells Python that it is a string (a word).
A link to Python syntax: https://en.wikipedia.org/wiki/Python_syntax_and_semantics
I'm completely new to Python so all of this is a bit new for me.
I'm trying to create a script in which it by itself thinks of a number and after wards wants the user to guess a number and enter it. It seemed to work but there are wo problems here.
It understands everything however it does not understand the == part.
Because even though the both numbers are the same, it still goes on towards the else statement.
import random
while True:
Thethinker = random.randint(1,10)
Guessnumber = (input("Guess a random number "))
if Guessnumber == Thethinker:
print("Correct")
print(Thethinker)
else:
print("Not correct")
print(Thethinker)
Any help?
Assuming Python 3, input returns a string.
In Python, a string and a number can never be "equal"; you have to transform one or the other. E.g, if you use
Thethinker = str(random.randint(1,10))
then the equality-comparison with another string can succeed.
Your input returns a string instead of an integer. To get an integer do:
int(Guessnumber)
This is better than using str() because then if you ever want to change the numbers, you wouldn't be able to do that without doing the method I suggested
As far as I know, I don't do much Python
Hello everyone I've been practicing with python for a bit now and found a project named Ubbi. Pretty much the whole goal is, is to add a string 'ub' before every vowel. So my question am i even close to cracking this or should i head another route??
def ubbidubbi_word(eword):
ubword = ""
for i in eword:
if i == 'aeoiuy': ubword += 'ub'+eword(i)
else: ubword += eword(i)
return ubword
You're close! However...:
(A) eword(i) would call eword as a function with argument i, which makes no sense; just use i itself, the character you're currently looking at (maybe you're thinking of Javascript here...? but even there the syntax will be different);
(B) i, a single character, will never equal the string 'aeoiuy', as you're checking; rather you should check if i is in that string (and thus a vowel).
I am teaching some neighborhood kids to program in Python. Our first project is to convert a string given as a Roman numeral to the Arabic value.
So we developed an function to evaluate a string that is a Roman numeral the function takes a string and creates a list that has the Arabic equivalents and the operations that would be done to evaluate to the Arabic equivalent.
For example suppose you fed in XI the function will return [1,'+',10]
If you fed in IX the function will return [10,'-',1]
Since we need to handle the cases where adjacent values are equal separately let us ignore the case where the supplied value is XII as that would return [1,'=',1,'+',10] and the case where the Roman is IIX as that would return [10,'-',1,'=',1]
Here is the function
def conversion(some_roman):
roman_dict = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M',1000}
arabic_list = []
for letter in some_roman.upper():
if len(roman_list) == 0:
arabic_list.append(roman_dict[letter]
continue
previous = roman_list[-1]
current_arabic = roman_dict[letter]
if current_arabic > previous:
arabic_list.extend(['+',current_arabic])
continue
if current_arabic == previous:
arabic_list.extend(['=',current_arabic])
continue
if current_arabic < previous:
arabic_list.extend(['-',current_arabic])
arabic_list.reverse()
return arabic_list
the only way I can think to evaluate the result is to use eval()
something like
def evaluate(some_list):
list_of_strings = [str(item) for item in some_list]
converted_to_string = ''.join([list_of_strings])
arabic_value = eval(converted_to_string)
return arabic_value
I am a little bit nervous about this code because at some point I read that eval is dangerous to use in most circumstances as it allows someone to introduce mischief into your system. But I can't figure out another way to evaluate the list returned from the first function. So without having to write a more complex function.
The kids get the conversion function so even if it looks complicated they understand the process of roman numeral conversion and it makes sense. When we have talked about evaluation though I can see they get lost. Thus I am really hoping for some way to evaluate the results of the conversion function that doesn't require too much convoluted code.
Sorry if this is warped, I am so . . .
Is there a way to accomplish what eval does without using eval
Yes, definitely. One option would be to convert the whole thing into an ast tree and parse it yourself (see here for an example).
I am a little bit nervous about this code because at some point I read that eval is dangerous to use in most circumstances as it allows someone to introduce mischief into your system.
This is definitely true. Any time you consider using eval, you need to do some thinking about your particular use-case. The real question is how much do you trust the user and what damage can they do? If you're distributing this as a script and users are only using it on their own computer, then it's really not a problem -- After all, they don't need to inject malicious code into your script to remove their home directory. If you're planning on hosting this on your server, that's a different story entirely ... Then you need to figure out where the string comes from and if there is any way for the user to modify the string in a way that could make it untrusted to run. Hackers are pretty clever1,2 and so hosting something like this on your server is generally not a good idea. (I always assume that the hackers know python WAY better than I do).
1http://blog.delroth.net/2013/03/escaping-a-python-sandbox-ndh-2013-quals-writeup/
2http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html
The only implementation of a safe expression evalulator that I've come across is:
https://pypi.org/project/simpleeval/
It supports a lot of basic Python-ish expressions and is quite restricted in what it allows you to do (so you don't blow up the interpreter or do something evil). It uses the python ast module for parsing, and evaluates the result itself.
Example:
from simpleeval import simple_eval
simple_eval("21 + 21")
Then you can extend it and give it access to the parts of your program that you want to:
simple_eval("x + y", names={"x": 22, "y": 48})
or
simple_eval("do_thing(11)", functions={"do_thing": my_callback})
and so on.
I am trying to automate some telnet actions with python3. So I started to use the build in telnetlib (not pexpect).
Actually everything works so far but I do not understand completly how read_until works - actually the documentation says that you can set a timeout and if the search string is not found the timeout sends back a empty byte value or or if there is another value thats the one which can be stored as a return value!
Does that make sense ?!
If I wanna read_until a certain value - how do I find out that this value was really the one the function read. Also I couldn't find out how to check if the timeout was hit.
My workaround for now is:
output = telnet.read_until(str.encode(hostname), 3)
if re.search(hostname, bytes.decode(output), re.IGNORECASE):
#do something when the output matches the searchstring
else:
#stop the function
but that doesn't make any sense for me, so perhaps you now a better solution
Yes, if your hostname is example.com, read_until will return something like weijwrgnerg hgqwv blather example.com. Except if it hasn't found the hostname after three seconds, it will just spit out whatever it's got by then: weijwrgnerg hg.
So I think you're doing it almost right. You probably want to re.escape your hostname, otherwise it will interpret it as a regex. Alternatively, you could just use Python's .endswith(). And you can do output.decode() to get a string (rather than bytes.decode(output)).