stdin.write 在 paramiko ssh 登录期间回显密码

stdin.write echos password during paramiko ssh login

TechJS 提供的脚本:(https://whosebug.com/users/5252192/techjs) in their answer on (How to run sudo with paramiko? (Python)) 非常适合我。

但是,在我添加后它会在命令行中显示密码,我知道这不是一个好主意。我从 stdin.write() 想象它,但我不知道如何以不同的方式做到这一点。

谁能建议一种更安全的存储和输入服务器密码的方法?我还是个新手,很想在这些情况下学习正确的密码安全协议:)

非常感谢所有的帮助!

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)

经过大量研究,我相信我有一个可以接受的答案,但是请持怀疑态度,因为我不是该领域的专家。已通知您。

这也没有解决 stdin 的打印问题,但我刚刚删除了 print() 函数来解决这个问题。此答案仅适用于密码安全部分。

tl:dr 这是答案https://alexwlchan.net/2016/11/you-should-use-keyring/ 但我会更详细地解释并在下面提供我的代码示例,这些代码用于存储和使用密码,但从不直接发送密码。

长答案: Python 有一个专门为此目的构建的包,称为 keyring()。它允许您以相对安全的方式存储和调用密码。它依赖于您的登录凭据,因此不幸的是,如果有人获得了您帐户的访问权限,他们将可以访问此信息,但如果没有这些信息,理论上您应该是安全的(或者我想尽可能安全)

Keyring() 加上一个名为 getpass() 的包允许用户将密码输入到他们的系统中,而无需将其提交为纯文本,从而防止通过文件共享等方式意外泄露。

这是我编写的一个非常简单的脚本,可以自动提示您完成选择并存储密码,而无需以纯文本格式存储密码

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()

(如果您使用的是 Python 2 那么它需要是 raw_input() )

这是在一个完全不同的脚本中完成的,所以你不需要将它们放在一起,运行一个脚本来设置密码,然后在你的主脚本中调用相应的密码非常简单那个点向前。

passwd = keyring.get_password('<system you inputed>','<username you inputed>')

大功告成!

p.s。我个人在我的 PATH 上放置了一个 bash 文件,运行 是这个脚本,这样如果我需要创建密码,它可以从机器内的任何目录完成,从而加强良好的安全程序.