using python to ssh fully into server - python

I've been trying to automate ssh'ing into my server however cannot find a way to fully automate the process. To be specific, getting around this input has been the struggle: root#example's password:
My code:
import subprocess
import time
server_ip = 'server'
pwd = b'password'
p = subprocess.Popen(['ssh', 'root#{}'.format(server_ip)],
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
if p == "root#example's password: ":
p.communicate(input= "{}".format(pwd))
else:
time.sleep(2)
if p == "root#example's password: ":
p.communicate(input= "{}".format(pwd))
else:
pass
What it returns:
Pseudo-terminal will not be allocated because stdin is not a terminal.
root#example's password:
user#computer ~ % Permission denied, please try again.
root#example's password:
Permission denied, please try again.
root#example's password:
root#example: Permission denied (publickey,password).
I know my code is very scuffed but it is the furthest I've got to getting in and submitting the password entry request.
Any help is appreciated!

if p == "root#example's password: ": can never be true; p is a subprocess.Popen object, not a string.
You can get a string by reading from the object's standard output, but of course, ssh prints the prompt message on the tty, so you can't easily capture it from Python.
Notice also that without an encoding keyword argument or text=True, you can't send or receive strings; the output you receive will be a b'...' byte string which cannot be compared to a regular string.
... But even if you managed to sort out these problems, taking it from there to a fully working interactive SSH session is still quite some distance to go. I would definitely recommend that you try pexpect or Paramiko instead of rolling your own, especially if you are new to Python.
Tangentially, else: pass is completely unnecessary; there is no reason to add an else: block in the first place if you don't have anything useful to put in it.
And
As "{}".format(pwd) is a really hairy way to write what can be more easily expressed as pwd, or str(pwd) if it's not already a string.

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.

Python Subprocess SSH closes connection

I have a function that uses the subprocess module to connect to a server via SSH.
# python 3
def foo():
menu = ["1 = one.com",
"2 = two.com",
"3 = three.com"
]
for item in menu:
print(item)
choice = input("Which host?: ")
if choice == "1":
user = "users-name"
host = "one.com"
port = "22"
subprocess.Popen(['ssh', user + '#' + host, '-p', port])
elif
...
...
foo()
When I run the script, it connects to the server but then terminates the connection after I press any key. It just kind of, drops the connection silently and goes back to typing on localhost.
Is subprocess not meant to handle a concurrent connection? I am merely asking it to connect and do nothing else. Advice, tips, suggestions?
There could be multiple answers to this, but assuming your command line, configuration and credentials are all correct and the ssh call on its own would succeed, the problem is (also a assuming a bit what happens in your code, or if the above example is more or less complete) following:
You fork and execute ssh (that's what Popen did), but your parent process (script) continues to run and eventually finishes, and when it does, it also clobbers the child it started, hence dropping you back to your hosts console even though you might have seen the other machine's prompt.
If I understands your intention correctly, you can do the following:
child = subprocess.Popen(['ssh', user + '#' + host, '-p', port])
child.wait()
Or just use a different method of starting your ssh such as check_call() that will hand control over to the child process and wait until its done..
Hope this helps.
Now when I see the above snippet, I cannot resits to give some unsolicited style advice/hints that can hopefully make your life a bit easier. I would just have a list of choices:
choices = [("one.com", "one_com_user", "one_com_port"), ...]
And generate the menu entries out of that... based on your input (converted to int, e.g. as entered), you could use choices[entered] to call ssh as wanted with corresponding arguments in the list and handle IndexError / out of range values with whatever response you wanted to do in case user specified unknown value.
That would make your code more concise (no conditional clauses), as well as easier to read and maintain (all hosts information in one place).
And one more regarding sshcall. You can skip concatenating strings and stick to list of arguments as you otherwise already do. ..., user + '#' + host, ... and ..., '-l', user, host, .... Should work with (hopefully) most ssh clients.

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