【问题标题】:Find out if asked for a password when looping over hosts using subprocess.Popen使用 subprocess.Popen 在主机上循环时找出是否要求输入密码
【发布时间】:2018-08-09 08:56:01
【问题描述】:

我正在循环访问多个主机(大约 400 个)以从系统中获取一些信息。他们中的大多数人都有 ssh 密钥,所以那里没有问题。只有少数人没有 ssh 密钥并返回密码。现在我想检测何时要求我输入密码,终止 ssh 进程并继续到下一个主机。

这是 ssh 部分的代码

def get_os_info(hostname, command, user=None):
remote = "%s" % hostname if user is None else "%s@%s" %(user, hostname)
ssh = subprocess.Popen(["ssh", remote, command],
                       shell=False,
                       stdout=subprocess.PIPE,
                       stderr=subprocess.PIPE)
result = ssh.stdout.readlines()
if result == []:
    error = ssh.stderr.readlines()
    print >>sys.stderr, "ERROR: %s" % error
    return None
else:
    return result

我无法使用 paramiko。

【问题讨论】:

    标签: python ssh subprocess


    【解决方案1】:

    不要尝试检测密码,而是避免提示输入密码,查看批处理模式(使用 Open SSH):

    ssh -oBatchMode=yes
    

    旨在防止从脚本调用时提示输入密码。现在你只需要检测是否连接。

    (尽管正如您在底部的评论所暗示的那样,使用 paramiko 在技术上可能是更好的解决方案)

    【讨论】:

    • 我把 ssh 部分改成了:ssh = subprocess.Popen(["ssh", "-o BatchMode=yes", remote, command], shell=False, stdout=subprocess.PIPE, stderr =subprocess.PIPE)并且有效。谢谢
    猜你喜欢
    • 2018-02-23
    • 1970-01-01
    • 2016-07-20
    • 2015-07-09
    • 2012-06-10
    • 1970-01-01
    • 2013-07-26
    • 2015-07-07
    • 2014-05-30
    相关资源
    最近更新 更多