show user 'processing' animation in python - python

i just wrote an extremely long script that takes a list of URLs and runs a series of API calls, processes them etc.
Unfortunately for majority of the calls, response is empty (to give scale, i get result for ~100 / 4000 urls )
I'm wondering if there is a way to show in terminal (or powershell) some kind of animation to indicate that the process is still running. Currently - i have the standard blinking underscore.
I was thinking of something like alterating between \ - / |
i definitely don't want to trash the console with printing too much.
does anyone know if something like that is possible ?

This is one way you can do it in PowerShell.
$progress = '\', '|', '/', '-'
$i = 0
[console]::Write('Doing something...')
while($true) {
$char = $progress[$i++ % $progress.Count]
[console]::Write("$char$([char]0x8)")
Start-Sleep -Milliseconds 300
}
Relevant docs:
Console.Write(String)
Modulus %
Index operator [ ]

Related

Python - How to fix CWE-117: Improper Output Neutralization for Logs

I have tried using clean = message.replace('\n', '').replace('\r', '').
But it still fails the veracode scan.
Is there any better way to do it?
Also I read about ESAPI Python but not getting any good documentation to fix this issue.
ESAPI Python unfortunately is an extremely long dead project. I don't have any Python alternatives, but the library hasn't had a commit since August 9, 2010.
I'm not familiar with Python web frameworks, but I do teach regularly about secure programming.
Every time you make a function call, you need to ask yourself the question:
"Am I passing this off of to an interpreter?"
If the answer is "yes," then you need to encode to ensure that THAT function is going to treat the input purely as data and not executable code.
In this particular case, if your logging has the potential to be interpreted by a browser (which is common) you'd also want to encode for HTML. However if your environment never uses html-based logging and is always raw text, this could be considered "mitigated" or a "false positive" depending on how your company has agreed to those terms.
Also, I like the practice of wrapping any user input with a unique delimiter. You can use square brackets, but I like strong visual cues in my logs.
Picture: [USERACTION] + userId + ' ►' + encode(userInput) + '◀'
Or even:
[USERACTION] + userId + ' ( ͡ʘ ͜ʖ ͡ʘ)' + encode(userInput) + '<:::::[]=¤ (▀̿̿Ĺ̯̿̿▀̿ ̿)'
Anything that helps make it obvious that someone has tampered with your logs is good. The louder the better!

Working with strings in Python: Formatting the information in a very specific way

OBS: I am working on Python 3.5.2 and I use the standard Shell and IDLE
Hi everyone, I think one of the most difficult tasks I have when programming with python is dealing with strings. Is there someone who can help?
One of the problems I face frequently is transforming the string so I can use it properly. For instance:
#consider I have the following string I want to work with:
my_input = 'insert 3 ["psyduck", 30]!!!insert 10 ["a nice day at the beach", 100]!!!find 3!!!find 10'
How can I transform this string in a way that, with the results, I would be able to do the following:
1 - Separate the following substrings into variables like this:
command = 'insert'
node = '3' #or the int 3
list = '["psyduck", 30]'
2 - Or any other solution that will somehow enable me to do this in the end:
listOfCommands = [['insert', '3', '["psyduck", 30]'], ['insert', '10', '["a nice day at the beach", 100]'], ['find', '3'], ['find', '10']]
I need this list in order to do the following:
for entry in listOfCommands:
if entry[0] == 'insert':
#I will execute a part of the program
elif entry[0] == 'update':
#execute something else
elif entry[0] == 'find':
#execute something else
The problem is that I do not know exaclty what is going to appear (the number of commands or the size of the information I will have to add) in the input. I just know that it will always obey these exact formats:
[A command, a 'node' where I have to store the information or update it, the information I have to store or update] or [A command, a 'node' I have to find or delete] and the blocks will be separated by '!!!'
I can work my way around the main program but in order to be able to make it run properly, I need to have this input formatted in this really specific way.
Maybe something like this will work:
commands = my_input.split('!!!')
my_commands = [c.split(' ', 2) for c in commands]
The second argument of the split methods tells it how many times you want it to split the string.

Use Powershell to retrieve number from a sequence using web request

I have a very specific problem I have been trying to work out. I'm using a PowerShell script to name newly imaged computers during the imaging proceess, and I need to grab a newly generated number from a sequence. I use SCCM 2012 R2 for this, btw
For example, I have the script naming our computers by our convention using wmi query:
if ($ComputerVersion -eq "ThinkPad T400")
{
$OSDComputerName = "T400xxxx-11"
$TSEnv = New-Object -COMObject Microsoft.SMS.TSEnvironment
$TSEnv.Value("OSDComputerName") = "$OSDComputerName"
}
I set the $ComputerVersion variable, using WMI query, like so:
$ComputerVersion = (Get-WmiObject -Class Win32_ComputerSystemProduct | Select-Object Version).Version
So, the crux of my question is I want to set another variable, probably something simple
like $num, for the next number available to label our computers. This number will be replacing the "xxxx". I'll be doing that by:
if ($ComputerVersion -eq "ThinkPad T400")
{
$OSDComputerName = "T400" + $num + "-11"
$TSEnv = New-Object -COMObject Microsoft.SMS.TSEnvironment
$TSEnv.Value("OSDComputerName") = "$OSDComputerName"
}
This number is being generated by a linux server we have, and its already running some python script to dish out the next available number in the sequence. I can post that python script if needed, but it's 133 lines.
What I need to know is how to call for that web request via PowerShell, and set that returned number (the next available) as a new variable.
I've never used web-services or web-requests before and any help would be greatly appreciated. Thanks in advance!
Depends what the web request returns and whether or not you need to process any return data, but if it simply returns the number you could do this:
$webClient = New-Object System.Net.WebClient
$num = $webClient.downloadstring("http://yourwebservice.com/buildnumber")

Printing in Duplexpage a word document

I am trying to automate the task of printing two copies at double page of ~30 Word document (*.doc). I want to send the program converted to .exe (I plan it just for Windows computers) using py2exe. I know that I can manually check the options but I will not be able to do so on the 20 or so computer where it will be used, as well as I cannot install in this computers new software (That's why I want to convert it into .exe).
I copied this solution to print, but I can't adapt it to do what I want:
from win32com import client
import time
word = client.Dispatch("Word.Application")
filename=input("What files do you want to print?")
def printWordDocument(filename):
"""Given a name of a file prints it. TODO: Add double page."""
word.Documents.Open(filename)
word.ActiveDocument.PrintOut()
time.sleep(2)
word.ActiveDocument.Close()
word.Quit()
I couldn't find any option to print in double pages, or at least automatically, the only option of double page of PrintOut method is ManualDuplexPrint which in the documentation says: "True to print a two-sided document on a printer without a duplex printing kit.", but I don't want to make it even easier to print all the set of documents. And make a program portable to other computers, without modifying the Word documents (I don't create them).
Any other way to do it? Or any other option to do it?
UPDATE
I am not able to code in visual-basic (yet), but if I get a template or some hints I think I will manage to make something adapted to my conditions.
I have ended doing a macro, but this just works for my own computer and not for all the computers where should work.
Sub Test()
'
' Test Macro
' Print in double page and 2 copies
'
ActivePrinter = "Xerox WC 24 PCL"
Application.PrintOut FileName:="", Range:=wdPrintAllDocument, Item:= _
wdPrintDocumentWithMarkup, Copies:=2, Pages:="", PageType:= _
wdPrintAllPages, Collate:=True, Background:=True, PrintToFile:=False, _
PrintZoomColumn:=0, PrintZoomRow:=0, PrintZoomPaperWidth:=0, _
PrintZoomPaperHeight:=0
End Sub

procmal recipe to pass values to my Python script

I have never used procmail before but I believe (from my R&D) that it is likely my best choice to crack my riddle. Our system receives an email, out of which I need 3 values, which are:
either a 4-digit or 5-digit integer from the SUBJECT line. (we will refer to as "N")
email alias from REPLY-TO line (we will refer to as "R")
determine the type of email it is, by which I mean to say a "case" or a "project". (we will refer to as "T") This value would be parsed out of the SUBJECT line.
If any one could help me with that recipe, I would be most appreciative.
The next thing I need to do is:
send these 3 values to a Python script (can I do this directly from procmail? pipe? something else?)
delete the email messages
I need to accept these emails from only 4 domain names, such as:
(#sjobeck.com|#cases.example.com|#messages.example.com|#bounces.example.com)
Last, is to pipe these 3 values in to the second script, and some advice as to the best syntax to do so. Any advice here is most appreciative. Would this be something like this:
this-recipe $N $T $R | second-script.py
Or exactly how would that look? Or is this not a procmail issue and a Python issue? (if it is, that's fine, I'll handle it over there.)
Thanks so much!
Jason
Procmail can extract those values, or you can just pass the whole message to Python on stdin.
Assuming you want the final digits and you require there to be 4 or 5, something like this:
R=`formail -zxReply-to: | sed 's/.*<//;s/>.*//'`
:0
* ^From:.*#(helpicantfindgoogle\.com|searchengineshateme\.net|disabled\.org)\>
* ^Subject:(.*[^0-9])?\/[0-9][0-9][0-9][0-9][0-9]?$
| scriptname.py --reply-to "$R" --number "$MATCH"
This illustrates two different techniques for extracting a header value; the Reply-To header is extracted by invoking formail (this will extract just the email terminus, as per your comment; if you mean something else by "alias" then please define it properly) while the trailing 4- or 5-number integer from the Subject is grabbed my matching it in the condition with the special operator \/.
Update: Added an additional condition to only process email where the From: header indicates a sender in one of the domains helpicantfindgoogle.com, searchengineshateme.net, or disabled.org.
As implied by the pipe action, your script will be able to read the triggering message on its standard input, but if you don't need it, just don't read standard input.
If delivery is successful, Procmail will stop processing when this recipe finishes. Thus you should not need to explicitly discard a matching message. (If you want to keep going, use :0c instead of just :0.)
As an efficiency tweak (if you receive a lot of email, and only a small fraction of it needs to be passed to this script, for example) you might want to refactor to only extract the Reply-To: when the conditions match.
:0
* ^From:.*#(helpicantfindgoogle.com|searchengineshateme\.net|disabled\.org)\>
* ^Subject:(.*[^0-9])?\/[0-9][0-9][0-9][0-9][0-9]?$
{
R=`formail -zxReply-To: | sed 's/.*<//;s/>.*//'`
:0
| scriptname.py --reply-to "$R" --number "$MATCH"
}
The block (the stuff between { and }) will only be entered when both the conditions are met. The extraction of the number from the Subject: header into $MATCH works as before; if the From: condition matched and the Subject: condition matched, the extracted number will be in $MATCH.

Categories

Resources