pbcopy in Python to copy to the clipboard on OSX? - python

I am receiving the following error when trying to use pbcopy to add the output to the clipboard. I tried different variations of the command and still no luck.
Does anyone have any ideas where I may have failed?
Error Screenshot:
#!/usr/bin/env python3
# This script creates a secure password using all available key combinations.
import secrets , string, os
def prRed(skk): print("\033[91m {}\033[00m" .format(skk))
chars = string.ascii_letters+string.punctuation+string.digits # Cleaner way of assigning variable
print()
pwd_length = int(input('Enter the length of the desired password: '))
print()
print('[+] ' + 'Your secure password is:')
print()
for n in range(1):
output = ""
for i in range(pwd_length):
next_index = secrets.SystemRandom().randrange(len(chars))
output = output + chars[next_index]
prRed(os.system("echo '%s' | pbcopy" % output))
print()

Related

Removing input() text from console Python3

I want to clear the line of text created after the input() function. I've tried \033[a, \r, end='' but either I'm doing it wrong or it doesn't work. Is there a better way:
Code is:
rawguess = input('Enter a 5 letter word: ')
print('words go here')
I've tried:
rawguess = input('\033[A' + 'Enter a 5 letter word: ' + '\033[A')
print('words go here')
rawguess = input('Enter a 5 letter word: ')
print('\rwords go here')
rawguess = input('Enter a 5 letter word: ')
print('\r', end='')
print('words go here')
And other variations of these three but nothing's worked so far.
I didn't know this before, but apparently Windows now supports Console Virtual Terminal Sequences, which include using ESC [ <n> A to move the cursor up (like on *nix). So we can call the Win32 API with ctypes.windll and enable Virtual Terminal Sequences, which will allow us to use '\x1b[1A'.
import sys
# Only do this on Windows, so that *nix users
# can also run the program without errors
if sys.platform.startswith('win'):
import ctypes
from ctypes.wintypes import *
STD_OUTPUT_HANDLE = -11
ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4
kernel32 = ctypes.windll.kernel32
h = kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
m = DWORD()
kernel32.GetConsoleMode(h, ctypes.pointer(m))
m.value |= ENABLE_VIRTUAL_TERMINAL_PROCESSING
kernel32.SetConsoleMode(h, m)
rawguess = input('Enter a 5 letter word: ')
print('\x1b[1A' + 'words go here')
Well I just found a piece of dark magic allowing you to enable terminal controls in Python:
import subprocess
subprocess.run("", shell=True)
input('Enter a 5 letter word: ')
print('\x1b[1A' + 'words go here ')

How do I break an inner for loop every time a condition is satisfied?

Good afternoon,
Im very new to python coding and Im trying to write a very basic md5 brute force password cracker for a school project.
I am supposed to write a script that will crack a series of MD5 hashed passwords. The passwords must be read in from a text file named “hashes.txt”, with one password on every line. The script should then start generating passwords, starting with single character, and then two characters, etc
My thought process of how to make a brute force cracker is as follows:
import hashlib
import itertools
abc = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!#0123456789"
abc_list = list(abc)
def combo():
md5_hash = ""
file_name = open("hashes.txt", "r")
for password in file_name:
password = password.strip()
#print(password)
for r in range(len(abc_list)):
combinations_object = itertools.combinations(abc_list, r)
combinations_list = list(combinations_object)
#print(combinations_list)
for lis in combinations_list:
glue = "".join(lis)
hash_object = hashlib.md5(glue.encode())
md5_hash = hash_object.hexdigest()
print(glue)
#print(md5_hash)
#print(glue + " " + md5_hash)
if md5_hash == password :
print("Your password is: " + "'" + glue +"' "+ md5_hash)
break
The passwords I am given to crack are:
Z,
AD,
God,
1234,
AbCdE,
Trojan
Every time I run the script it only outputs the password: Z and then runs through the rest without fulfilling the 'if' statement.
I have tried using the 'break' statement under the 'if' but the outcome is the same.
You might benefit from creating and storing the combinations list once (or rather, a generator).
https://stackoverflow.com/a/31474532/11170573
import itertools
def all_combinations(any_list):
return itertools.chain.from_iterable(
itertools.combinations(any_list, i + 1)
for i in range(len(any_list)))
You can change the code as follows:
import hashlib
import itertools
abc = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!#0123456789"
abc_list = list(abc)
combinations_object = all_combinations(abc_list)
def combo():
file_name = open("hashes.txt", "r")
for password in file_name:
password = password.strip()
for comb in combinations_object:
glue = "".join(comb)
hash_object = hashlib.md5(glue.encode())
md5_hash = hash_object.hexdigest()
if md5_hash == password :
print("Your password is: " + "'" + glue +"' "+ md5_hash)
break
When you use break, what you are saying is break the loop I'm currently in.
Notice that your condition is wrapped by three for loops, so it will only break the inner inner loop and keep going with the rest.
What you can do is what Jason Baker sugests in https://stackoverflow.com/a/438869/16627440.
Change that break to return md5_hash and call the function in your print.
if md5_hash == password :
return md5_hash
# Outside your function
print("Your password is: " + "'" + glue +"' "+ combo())

Getting Python code to call a PowerShell script and run it

I could really use some help on this python script that is to call and run existing PowerShell scripts that are in a specific folder. From want I can see on from many of the articles on this site I've read my code seems correct. First a little background I'm trying to write a python script that will take Powershell scripts in a targeted folder and create a menu that can be selected 1, 2, 3 etc. The use makes the selection and that corresponding Powershell script is run. Now the issue is when I place the code on a server and run it with some test PowerShell scripts I get the following error: The term "Filename.ps1" is not recognized as the name of a cmdlet, function, script file, or operable program. And of course the Powershell scripts won't run. A copy of my code is below. Can anyone see any issue.
## ENOC Text Menu Dynamic test
##version 1
## Created By MTDL Marcus Dixon
## Code produce in Notpad++ For python v3.4.4
import os, subprocess, time, pathlib, logging, fnmatch,
re, sys, io
## Directory Enumerator
fileFolderLocationFilter = fnmatch.filter(os.listdir
('C:\\Users\\MTDl\\Documents\\Automation_Scripts\
\ENScripts\\'), "*.ps1")
selectedFile=""
## Menu defined setting veriables
def ENOC_menu():
files = fileFolderLocationFilter
counter = 1
print (20 * "=" , "Enoc Quick Menu" , 20 * "=")
enumFiles = list(enumerate(files))
for counter, value in enumFiles:
str = repr(counter) + ") " + repr(value);
print(str)
str = repr(counter+1) + ") Exit";
print(str)
print (57 * "_")
str = "Enter your choice [1 - " + repr((counter+1))
+ "]:"
choice = int(input("Please Enter a Selection: "))
selectedFiles = enumFiles[choice]
return(selectedFiles[1])
if choice > counter :
choice = -1
elif choice != counter :
print("Please selecte a valid choice")
else:
selectedFiles = enumFiles[choice]
print(selectedFiles[1])
##selectedFiles = selectedFiles[1]
return choice
##initiating loop
loop = True
while loop:
try:
choice = ENOC_menu()
scriptToRun = choice
powershell = 'C:\\WINDOWS\\system32\
\WindowsPowerShell\\v1.0\\powershell.exe'
print ('\n' +'You selected '+ choice
+'\n')
subprocess.call(powershell + ' ' +
choice, shell=True)
except OSError as err:
logger.error(err) ##continue to work on
logging this renders but may be incorrect.
print ('OS error: {0}' .format(err))
except ValueError:
print ('Oops we had an issue try again')
else:
print ('---' + choice + '---' + '\n')

Why can't I open a file from a variable made from several concatenating strings in Python?

So I wrote this code
spec = raw_input("Enter the specimen number: ")
naorimp = raw_input("Native or Implant (N/I)? ")
trial = raw_input("Trial number: ")
typana = raw_input("What do you want to analyze (contact area[CA]/contact pressure[CP])? ")
try :
if typana.lower() == "cp" :
naorimp = naorimp.upper()
TSfilnm = 'pressure'+spec+naorimp.upper()+trial+'.txt'
else :
naorimp = naorimp.upper()
TSfilnm = 'area'+spec+naorimp+trial+'.txt'
TSfile = open(TSfilnm, 'r')
myofilnm = 'accelerometer'+spec+naorim.upper()+trial+'.txt'
print myofilnm
myofile = open(myofilnm, 'r')
except :
print "File could not be found."
print "Please re-run the program."
exit()
print "OK"
I want to open a file based on user's input and several parameters (specimen no., native or implant, trial no., and type of analysis.) The file is already in the same folder as the python file code. But when I run the program I always end up with except statements (File could not be found. Please re-run the program). I have double-checked the real file name and the string inside the TSfilnm variable, and they are the same. However, the TSfile could not be executed.
P.S. The file name in my folder is: pressure3N1.txt, area3N1.txt, accelerometer3N1.txt
You are missing a p in the variable name in this line
myofilnm = 'accelerometer'+spec+naorim.upper()+trial+'.txt'
should be
myofilnm = 'accelerometer'+spec+naorimp.upper()+trial+'.txt'
Also don't use 'except' alone during development, it will only hide errors like in this case. It's better to do something like.
import sys
try:
#Your_code_here
except:
print sys.exc_info()[1]
#Any other code you wanna run

Userfriendly way of handling config files in python?

I want to write a program that sends an e-mail to one or more specified recipients when a certain event occurs. For this I need the user to write the parameters for the mail server into a config. Possible values are for example: serveradress, ports, ssl(true/false) and a list of desired recipients.
Whats the user-friendliest/best-practice way to do this?
I could of course use a python file with the correct parameters and the user has to fill it out, but I wouldn't consider this user friendly. I also read about the 'config' module in python, but it seems to me that it's made for creating config files on its own, and not to have users fill the files out themselves.
Are you saying that the fact that the config file would need to be valid Python makes it unfriendly? It seems like having lines in a file like:
server = 'mail.domain.com'
port = 25
...etc would be intuitive enough while still being valid Python. If you don't want the user to have to know that they have to quote strings, though, you might go the YAML route. I use YAML pretty much exclusively for config files and find it very intuitive, and it would also be intuitive for an end user I think (though it requires a third-party module - PyYAML):
server: mail.domain.com
port: 25
Having pyyaml load it is simple:
>>> import yaml
>>> yaml.load("""a: 1
... b: foo
... """)
{'a': 1, 'b': 'foo'}
With a file it's easy too.
>>> with open('myconfig.yaml', 'r') as cfile:
... config = yaml.load(cfile)
...
config now contains all of the parameters.
I doesn't matter technically proficient your users are; you can count on them to screw up editing a text file. (They'll save it in the wrong place. They'll use MS Word to edit a text file. They'll make typos.) I suggest making a gui that validates the input and creates the configuration file in the correct format and location. A simple gui created in Tkinter would probably fit your needs.
I've been using ConfigParser. It's designed to read .ini style files that have:
[section]
option = value
It's quite easy to use and the documentation is pretty easy to read. Basically you just load the whole file into a ConfigParser object:
import ConfigParser
config = ConfigParser.ConfigParser()
config.read('configfile.txt')
Then you can make sure the users haven't messed anything up by checking the options. I do so with a list:
OPTIONS =
['section,option,defaultvalue',
.
.
.
]
for opt in OPTIONS:
section,option,defaultval = opt.split(',')
if not config.has_option(section,option):
print "Missing option %s in section %s" % (option,section)
Getting the values out is easy too.
val = config.get('section','option')
And I also wrote a function that creates a sample config file using that OPTIONS list.
new_config = ConfigParser.ConfigParser()
for opt in OPTIONS:
section,option,defaultval = opt.split(',')
if not new_config.has_section(section):
new_config.add_section(section)
new_config.set(section, option, defaultval)
with open("sample_configfile.txt", 'wb') as newconfigfile:
new_config.write(newconfigfile)
print "Generated file: sample_configfile.txt"
What are the drawbacks of such a solution:
ch = 'serveradress = %s\nport = %s\nssl = %s'
a = raw_input("Enter the server's address : ")
b = 'a'
bla = "\nEnter the port : "
while not all(x.isdigit() for x in b):
b = raw_input(bla)
bla = "Take care: you must enter digits exclusively\n"\
+" Re-enter the port (digits only) : "
c = ''
bla = "\nChoose the ssl option (t or f) : "
while c not in ('t','f'):
c = raw_input(bla)
bla = "Take care: you must type f or t exclusively\n"\
+" Re-choose the ssl option : "
with open('configfile.txt','w') as f:
f.write(ch % (a,b,c))
.
PS
I've read in the jonesy's post that the value in a config file may have to be quoted. If so, and you want the user not to have to write him/her-self the quotes, you simply add
a = a.join('""')
b = b.join('""')
c = c.join('""')
.
EDIT
ch = 'serveradress = %s\nport = %s\nssl = %s'
d = {0:('',
"Enter the server's address : "),
1:("Take care: you must enter digits exclusively",
"Enter the port : "),
2:("Take care: you must type f or t exclusively",
"Choose the ssl option (t or f) : ") }
def func(i,x):
if x is None:
return False
if i==0:
return True
elif i==1:
try:
ess = int(x)
return True
except:
return False
elif i==2:
if x in ('t','f'):
return True
else:
return False
li = len(d)*[None]
L = range(len(d))
while True:
for n in sorted(L):
bla = d[n][1]
val = None
while not func(n,val):
val = raw_input(bla)
bla = '\n '.join(d[n])
li[n] = val.join('""')
decision = ''
disp = "\n====== If you choose to process, =============="\
+"\n the content of the file will be :\n\n" \
+ ch % tuple(li) \
+ "\n==============================================="\
+ "\n\nDo you want to process (type y) or to correct (type c) : "
while decision not in ('y','c'):
decision = raw_input(disp)
disp = "Do you want to process (type y) or to correct (type c) ? : "
if decision=='y':
break
else:
diag = False
while not diag:
vi = '\nWhat lines do you want to correct ?\n'\
+'\n'.join(str(j)+' - '+line for j,line in enumerate((ch % tuple(li)).splitlines()))\
+'\nType numbers of lines belonging to range(0,'+str(len(d))+') separated by spaces) :\n'
to_modify = raw_input(vi)
try:
diag = all(int(entry) in xrange(len(d)) for entry in to_modify.split())
L = [int(entry) for entry in to_modify.split()]
except:
diag = False
with open('configfile.txt','w') as f:
f.write(ch % tuple(li))
print '-*- Recording of the config file : done -*-'

Categories

Resources