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)