pexpect to pass password to a script - python

I'm trying to run a code which will trigger a script.
The script evaluates something and uploads the results to a site for which it prompts password from user. Need to automate this with a generic user.
I have
import subprocess
p=subprocess.Popen(cmd,cwd=path)
p.wait()
When this runs, it evaluates something and prompts for password.
How to give this password using pexpect?
Is there any other solution to it?

By using the spawn class
p = ['cmd','to','run']
child = pexpect.spawn(' '.join(p), cwd='/path/to/dir')
# Now you give a regex of the expected password prompt
# usually use 'pass.*'
# but for a general case use '.*'
child.expect('.*')
child.sendline('abc123') # your secure password
child.wait()

Related

stdin.write echos password during paramiko ssh login

The script provided by TechJS: (https://stackoverflow.com/users/5252192/techjs) in their answer on (How to run sudo with paramiko? (Python)) works perfectly for me.
However, it echos the password in the command line after my additions and i know that's not a good idea. I imagine its from the stdin.write() but i have no idea how to do it differently.
Can anyone suggest a more secure way of storing and inputting the server password? I'm still pretty new and would love a good lesson on proper password security protocol in these situations :)
Thanks so much to any and all help!
import paramiko
import re
import <passwords file> #did chmod 400 for this file
ssh_client= None
server_address='<removed for security>'
server_username='<removed for security>'
server_pass = <password file>.<this server password from passwords file>
command = "<removed for security>"
def main(command, server_address, server_username, server_pass):
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=server_address,
username=server_username,
password=server_pass)
session = ssh.get_transport().open_session()
session.set_combine_stderr(True)
session.get_pty()
session.exec_command("sudo bash -c \"" + command + "\"")
stdin = session.makefile('wb', -1)
stdout = session.makefile('rb', -1)
stdin.write(server_pass + '\n')
stdin.flush()
print(stdout.read().decode("utf-8"))
except Exception as e:
print("The following error has occurred during your requested process")
print(e.message)
finally:
if ssh:
session.close()
ssh.close()
if __name__ == '__main__':
main(command, server_address, server_username, server_pass)
After a lot of research I believe I have an acceptable answer, however please take this with skepticism as I am NOT an expert in this field. You have been advised.
This also did NOT fix the printing of the stdin problem, but i have just removed the print() function all together to remove the issue. This answer is for the password security part ONLY.
tl:dr here is the answer https://alexwlchan.net/2016/11/you-should-use-keyring/
but i will explain in more detail and provide examples below of my code used to store and use passwords while never plain texting them.
LONG ANSWER:
Python has a package that is build for this purpose specifically called keyring(). It allows you to store and call on passwords with relative security. It works off of your login credentials so unfortunately if someone gains access to your account they will have access to this information, but without that you should theoretically be secure (or as secure as one can be i guess)
Keyring() plus a package called getpass() allow for a user to input a password into their system without committing it to plain text and thus preventing accidental leaking through file sharing or the like.
Here is a very simple script I wrote to automatically prompt you through your choices and store the password without ever needing to store it in plain text
import keyring
import getpass
def main():
system = input('System:')
username = input('Please input username:')
keyring.set_password(system,username,getpass.getpass())
print('The password for ' +username+' in '+system+' has been set.\nPlease do not misplace, you will not be able to recover at this point.\nFor misplaced passwords, please resubmit new entry with the same details, it will overwrite the previous entry.')
if __name__=='__main__':
print('Please input the system in which the password will be used,\nand corresponding username.')
main()
(if you're using Python 2 then it needs to be raw_input() )
This is done in an entirely different script so you DO NOT NEED TO HAVE THEM TOGETHER, run one script to set the password, then to call on the corresponding password is very simple in your main script from that point forward.
passwd = keyring.get_password('<system you inputed>','<username you inputed>')
And you're done!
p.s. I personally have placed a bash file on my PATH that runs this script so that if i ever need to create a password it can be done from any directory within the machine, and thus reinforcing good security procedures.

Querying database on different Windows credentials in Python/cmd [duplicate]

I've managed to get the cmd being opened by python. However, using runas administrator comes with a password check before cmd.exe is executed.
I'm using this to open cmd...
import subprocess
subprocess.call(["runas", "/user:Administrator", "cmd.exe"])
I'm looking for a way to automatically enter the password into the runas.exe prompt which opens when i run the code. Say if i were to create var = "test" and add it after import subprocess how would i make it so that this variable is passed to and seen as an input to the runas.exe?
The solution would require only python modules which are in version 3.4 or higher.
Update
I have found some code which appears to input straight into runas.exe. However, the apparent input is \x00\r\n when in the code the input is supposed to be test I am fairly certain that if i can get the input to be test then the code will be successful.
The code is as follows :
import subprocess
args = ['runas', '/user:Administrator', 'cmd.exe']
proc = subprocess.Popen(args,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
proc.stdin.write(b'test\n')
proc.stdin.flush()
stdout, stderr = proc.communicate()
print (stdout)
print (stderr)
Although not an answer to your question, this can be a solution to your problem. Use psexec instead of runas. You can run it like this:
psexec -u user -p password cmd
(or run it from Python using subprocess.Popen or something else)
This piece of code actually works (tested on a Windows 2008 server). I've used it to call runas for a different user and pass his password. A new command prompt opened with new user context, without needing to enter password.
Note that you have to install pywin32 to have access to the win32 API.
The idea is:
to Popen the runas command, without any input redirection, redirecting output
read char by char until we encounter ":" (last char of the password prompt).
send key events to the console using win32 packages, with the final \r to end the password input.
(adapted from this code):
import win32console, win32con, time
import subprocess
username = "me"
domain = "my_domain"
password ="xxx"
free_console=True
try:
win32console.AllocConsole()
except win32console.error as exc:
if exc.winerror!=5:
raise
## only free console if one was created successfully
free_console=False
stdin=win32console.GetStdHandle(win32console.STD_INPUT_HANDLE)
p = subprocess.Popen(["runas",r"/user:{}\{}".format(domain,username),"cmd.exe"],stdout=subprocess.PIPE)
while True:
if p.stdout.read(1)==b":":
for c in "{}\r".format(password): # end by CR to send "RETURN"
## write some records to the input queue
x=win32console.PyINPUT_RECORDType(win32console.KEY_EVENT)
x.Char=unicode(c) # remove unicode for python 3
x.KeyDown=True
x.RepeatCount=1
x.VirtualKeyCode=0x0
x.ControlKeyState=win32con.SHIFT_PRESSED
stdin.WriteConsoleInput([x])
p.wait()
break

Python 2.7: passing values to getpass

On Windows (specifically Win Server 2008 R2), I need to repeatedly execute an existing python script that comes with our product repeated. The intention of this script was to be called occasionally and the input is expected to be manual. However, I end up having to call this script hundreds of times.
So, I'm trying to automate the calls to this script (and other related scripts) with an additional python script. Where I'm getting hung up is that the "out of the box" script I am calling uses getpass.getpass() for password input.
In my automation script, I've tried using subrocess pipe.communicate to pass the password values to the base script. But I can't get it to work. Here's the relevant code in my automation script:
p = Popen(coreScriptCmd, stdout=PIPE, stdin=PIPE, stderr=STDOUT)
x = p.stdout.readline().rstrip()
print x #for debugging
x = p.communicate(args.pwd1+"\n"+args.pwd2)[0].rstrip()
print x #for debugging
As I said though, this doesn't work when the subprocess being called is using getpass.getpass() to ask for it's input. Here's the if statement in the core code where I'm running into trouble:
elif cmd == 'update-user':
if 'password1' not in globals():
password1 = getpass.getpass(mgmtusername + " password:")
if 'dbpassword' not in globals():
dbpassword = getpass.getpass(dbusername + " password:")
checkAccessDb(hostname, database, mgmtusername, password1, dbusername, dbpassword)
Does anyone have any suggestion on how to programmaticly pass values to getpass() in the subscript?
Alright, so I'm not sure what the original script looks like. But, in the case that it will still need to be usable from the command line, I would recommend this.
I would modify the original script to accept an argument. For example, let's say that the getpass is inside a function like this...
def run_script():
paswd = getpass.getpass("Please enter the password:")
Try modifying it to something like this:
def run_script(cmdlin = True):
if cmdlin:
paswd = getpass.getpass("Please enter the password:")
else:
# get password using another method
The other method could be anything you choose, pass it as an argument, grab it from a file, etc..
Once it is setup like this, just call it passing in "cmdlin" argument as false.
Edit: Using the subprocess module you should be able to use communicate to send the password over
Also, I found the pexpect library that might help in your situation
This could be possible because of your code
x = p.stdout.readline().rstrip() . stdout.readline() is a blocking call and it will block as long as there is nothing to output. Try commenting out that line and see if it works.Also sharing the content of "coreScriptCmd" would help to find the root cause in a better way.

Python subprocess.Popen usage with a login script fails

I'm trying to do a login script using python that will attempt to login with the shell command login -q MyUsername and try multiple passwords. I can already generate the passwords needed but when I try to login using the code below, the login command responds that I entered the wrong username although I know I'm writing it correctly. To clarify: I'm creating a script to login using the shell command login when I already know the username but not the password. The code below shows what I'm doing (iterating over the passwords).
for password in passwordList:
p = Popen(["login","-q","MyUsername"], stdin=PIPE, stdout=PIPE) #The username MyUsername is correct, 100% sure
print repr(p)
stdout_value = p.communicate(password)[0] #
print(str(stdout_value))
if repr(stdout_value).startswith('Login incorrect\nlogin: '):
print "ERROR"
else:
print "GOOD"
break
If I type in the command login -q MyUsername directly into the terminal, I get prompted to write my password whereas using the script returns 'Login Incorrect'. I'm also confused as how Popen works and how to write to stdout.
Thanks in advance!
(Other question: Is there an easier way to do this? (Attempt to login using multiple passwords) I'm using login because it has no lockdown and the user data can't be accessed if it is not by the superuser).
login might read/write directly from/to terminal (tty) outside of process' stdin/stdout. You could use pexpect instead, read the first reason in its docs Q: Why not just use a pipe (popen())?:
import pexpect
output, rc = pexpect.run("login -q MyUsername",
events={"(?i)password: ": "password"},
withexitstatus=True)
Is there an easier way to do this?
Read the hashes from /etc/passwd, /etc/shadow and check those using crypt.crypt(). Or use a specialized tool to test for weak passwords such as "John the Reaper".

How to automate shell input with python?

I am automating some tasks with python, but have hit a bit of a roadblock. One of the tasks I am automating requires user input in the shell.
The requirement is that you to run the command with an email address as a parameter (simple enough), and then you are asked to authenticate with the password for that email address. How can you simulate user input to provide the password?
There are also some menus afterwards which ask options, for which the input need just be to repeatedly hit enter. How is this simulated? Keeping in mind that this window will not always have focus..
I'm not sure what you're asking in the second part, but subprocesses can be controlled with the pexpect module. For example:
#!/usr/bin/env python
import pexpect
import sys
# Get email and password somehow
#email = ...
#password = ...
# Start the subprocess
child = pexpect.spawn('mycommand %s' % email)
# redirect output to stdout
child.logfile_read = sys.stdout
# Assumes the prompt is "password:"
child.expect('password:')
child.sendline(password)
# Wait for the process to close its output
child.expect(pexpect.EOF)
Looks like you are thinking in a wrong way. You just need to send some bytes via pipe to recipient (shell script in your case) and this can be done with subprocess.
I guess you can use expect for this.

Categories

Resources