I have compiled a script in python 2.6.5, The script is simply to automate my most used functions for nmap and log the output to a txt file on the desktop.
I haven't written this all myself as i am still only learning python. I found an update script for updating backtrack and used that as a template for indentation and commands and modified it and added some of my own stuff to give me what i needed.
The problem i'm having is with this block
def nmap_target():
try: ip = raw_input(" [>] Enter ip to scan: ")
except KeyboardInterrupt:
print "\n [>] Exiting!\n"
sleep(1)
sys.exit()
print " [>] Attempting targeted scan.\n"
#print ip
if subprocess.Popen("nmap ip >> //root/Desktop/Target.txt && tail /root/Desktop/Target.txt",shell=True).wait() == 0:
print "\n"
print " [>] Targeted scan completed successfully!\n"
menu_main()
else:
print "\n"
print " [>] Nmap scan failed.\n"
The idea behind it is that it asks the user to input an ip address into raw_input() and call it ip, I'm trying to then pass it to nmap using subprocess.Popen("nmap ip as can be seen above.
The problem is its just writing nmap ip rather than printing the ip address and then returning errors, It even tries to scan out of my network, every time i test it i make sure the internet cable is unplugged from my router, This causes a bug with my internet test though, so if you try running the code bellow you may need to hash out the internet_check() option in the menu_main() section if you have your internet unplugged from the router
I have spent 4 days on this now and its driving me mad, At first i thought i needed to convert the number to floating point so i tried that and still the same, I've tried all sorts of things and spent hours trawling the internet looking for an answer to no avail.
I am now convinced its not the command i'm trying that is to blame i think it is the exit statement, I have tried putting "print ip" right after the line where it says "print " [>] Attempting targeted scan.\n" and sure enough the ip address that was entered is displayed on the screen, That proved to me that raw_input() is working. As soon as i move it anywhere bellow that it fails, This suggests to me that it must be either a problem with the exit statement or maybe indentation, I'm not sure though.
I have also tried hashing out the keyboard interrupt as well as the couple of lines bellow, i tried moving the try: and if statements around and even tried other commands instead but it just wont work aaaarrrrrgggghhhhhh
Would i be right in thinking that the ip is being entered into raw_input() and then the file ip that was created that holds the ip address is being destroyed before i can pass it to subprocess.Popen("nmap ip.
Like i mentioned i didn't write this script from scratch and this is my first project like this so i've got a lot to learn, I've been all through the python man pages and looked through all sorts of tutorials but just can't figure this out.
Any help will be much appreciated
i will post the full script if anyone is interested,just as soon as i can figure out how to post code properly
You need to seperate the variable from the string! Try this :D
if subprocess.Popen('nmap '+ip+' >> //root/Desktop/Target.txt && tail /root/Desktop/Target.txt',shell=True).wait() == 0:
Hope it helps!
EDIT - If for some reason python takes the raw input as an integer, convert it to string like so:
if subprocess.Popen('nmap '+str(ip)+' >> //root/Desktop/Target.txt && tail /root/Desktop/Target.txt',shell=True).wait() == 0:
Python doesn't like to concatenate str and int types, or so it tells when my script fails :P I am pretty sure your ip variable will be str type though so the first example should work.
Cheers!
You need to format the string properly or the string ip won't be interpreted at all, i.e. it won't get replaced wth the actual IP. Try something like:
cmd = "nmap ${0} >> [....] root/Desktop/Target.txt".format(ip)
if subprocess.Popen(cmd):
You could also use the % operator:
cmd = "nmap %s >> [....] root/Desktop/Target.txt" % ip
Related
I have a question in regards to comparing files using python. For context, the problem I am having is that I have two firewalls with different configurations (over 14000 lines each on Notepad++) and I need to find the differences and annotate them.
Quick Example -
Firewall 1:
Version: 123
set policy EXPLICIT_DENY ALL
IP address allow 1.2.3.4
IP address allow 4.3.2.1
set policy EXPLICIT_ALLOW NONE
Firewall 2:
Version: 321
set policy EXPLICIT_ALLOW NONE
IP address allow 4.3.2.1
IP address allow 1.2.3.4
set policy EXPLICIT_DENY ALL
A line-by-line comparison would show that all of those lines are incorrect because they do not match side by side, however, the configuration is the same and would not need to be annotated. The only difference would be the Version # in the example. The script below was able to work for my purposes.
Current Script I ran -
'file1 = open("OLD FW.txt",'r')
'file2 = open("NEW FW.txt",'r')
'file3 = open("Results.txt",'r+')
'file1_lines = file1.readlines()
'file2_lines = file2.readlines()
'for position, a in enumerate(file1_lines):
'linematch = False
'for b in file2_lines:
'if a == b:
'linematch = True
'if linematch == False:
'file.3write(f"{position+1}: {a.strip()}\")
'file1.close()
'file2.close()'
The output would show every line from the OLD firewall that does not appear on the NEW firewall. This would effectively let me see what configurations are missing and/or different AND show me what line is is on the original FW.
The issue I figured out after coming up with this is that my current software version at work is only Python 2.7.16 which doesn't support f-strings. I did a little bit of research but am far to novice currently to figure this out in the short time window I have.
Mai question: How do I convert this Python f-string script to something that would work the same in an older version of Python that doesn't support f-strings?
Thanks in advance to anyone who can help me figure this out!
For simple cases like you show, you can use the .format() method.
file.write("{}: {}\n".format(position+1, a.strip()))
I'm playing with an remote console that asks me to return every word it gives.
For example :
>>> car # Remote console gives a word
car # I answer
Ok next word ! # Remote console after checking
>>> house # Remote console gives a second word and is waiting for me
I could manually answer each word the console says. But I'd like to make a script to automate it.
I'm thinking about a loop that would do this job, that is to say :
get the word from the remote console
send that word back to the remote console
I tried it with the pwntools Python library by using the recvline() and sendline() commands. I wrote :
import pwn
import re
c = pwn.remote ("URL", port)
question = str(c.recvline())
c.sendline(question)
c.interactive()
By doing this, the console returns :
Ok next word !
>>> house
That's a start but obviously as there's no loop, the script can't send "house" back. To adapt it, I used while and for loops on the recvline command but without results after many tries. And I must admit I'm getting stuck.
Is there a trick to do it and put each try inside the >>> input of the service ?
Any help would be very appreciated.
Thanks.
I am having an issue where I am trying to use Python's pyshark to read in IP addresses. I was able to print out the IP address of an LLDP packet just fine, using packet.lldp.mgn_addr_ip4. However packet.cdp... does not seem to have an equivalent, besides packet.cdp which returns a sequence of bytes.
I have tried packet.cdp.nrgyz.ip_address and nothing is printed out. I tried every other field from this link as well and nothing will return.
for packet in cap:
try:
if packet.cdp:
print(packet.cdp.nrgyz.ip_address)
elif packet.lldp:
print(packet.lldp.mgn_addr_ip4)
except AttributeError as e:
pass
I'd really appreciate any kind of guidance since not a single one of the fields that says it returns an IPv4 address will print out.
I figured it out. Apparently you can't use cdp.nrgyz(DOT)ip_address, and instead have to use cdp.nrgyz(UNDERSCORE)ip_address. So it becomes cdp.nrgyz_ip_address, even though Wireshark documentation says it should be cdp.nrgyz.ip_address
hi I am new to python and I am trying to telenet to my host connected via Host-only adapter :
My command are
import telnetlib
import time
def call_func():
time1 = 2
connect = telnetlib.Telnet('192.168.1.100',23,3)
connect.write('show version'.encode('ascii'))
time.sleep(time1)
print (connect.read_very_eager().decode('ascii'))
connect.close()
call_func()
However I am not able to read the full output of the show version command. Can someone explain why I am not able to do so?
Output got:
'R1>show version'
You can read about all read_ methods in telnetlib documentation and compare their outputs. It states there, that only read_until() will give you text "until a given byte string". All of the other ones will return only "all data until EOF", "everything that can be without blocking in I/O", "readily available data." etc.
That said, you should use read_until() to be sure you get a full string returned. This in the only method that waits for telnet to return the whole text.
Additional explanation can be found here in a similar question.
I'm sending I'm receiving a JSON message through MQTT in Python, and I would like to start a command line program with what the JSON gives as variables.
The problem with this is that I don't know what values are going to come through and thus this is where I have trouble.
The easiest would be if I knew all the variables that would come through and do something like this:
data = json.loads(msg.payload)
os.system("'command +f ' + data[arg1] + ' +g ' + data[arg2]")
But as mentioned previously, I don't know if they are being passed through, and as such, how can I break it down so that the command line command is build up?
Maybe:
if 'arg1' in data:
command = "+f " + data[arg1]
else:
pass
if 'arg2' in data:
command + "+g " + data[arg2]
else:
pass
Would this work? Is there a better idea?
You can use a for loop to iterate over the json, and construct the command string.
commandArgs = ["+f ","+g "]
commandCount=0
for element in data:
command= command + commandArgs[commandCount] + element
commandCount = commandCount +1
Although you could do this as described it's not something you should do. Running user-inputted commands is one of the most unsecure things a program can do. Scrubbing the commands thoroughly is possible but quite difficult to do comprehensively. The usual approach is to have a table of acceptable commands, match against the table, and then use the entries from that table to populate the command line. Nothing typed by the user ever makes it into the command line with that method.
If you do wish to take user input directly, be extremely careful about scrubbing all special characters, characters outside your preferred locale, double-byte characters, path delimiter characters, etc. Perhaps you could start with the snippet Jeff provided and add a lot of data scrubbing code.
Also, be aware that the probability that whatever you do not code for will eventually be submitted for processing corresponds roughly to the risk of that command. For example, if you fail to catch and remove cat ~/.ssh/* there's a moderately good chance one of your users will execute it or someone will break in and do so. But if you do not catch and remove rm -r /* the chance someone will submit that command approaches certainty.