Python + SSH 密码身份验证(没有外部库或公钥/私钥)? [英] Python + SSH Password auth (no external libraries or public/private keys)?

查看:41
本文介绍了Python + SSH 密码身份验证(没有外部库或公钥/私钥)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我知道你可以使用 Pexpect 来解决这个问题,但除了 Python3 提供的库之外,我不想依赖其他库来解决这个问题.

So I'm aware that you can use Pexpect to solve the issue but i'd like to not rely on additional libraries to solve the issue other than those supplied with Python3.

我也知道生成公钥并允许它们在远程主机上是理想的,但这就是我打算使用此脚本的目的(在正确的位置设置密钥等).

I'm also aware the generating public keys and allowing them on the remote host is ideal, but that's sort of what i intend to use this script for (setting up keys in the right place etc).

这是我在 SO 社区的大量帮助下我自己"获得的.我正在检查分叉的子伪终端是否完成了它应该执行的操作.这意味着我可以判断 SSH 是否已完成执行,因为只要 run() 函数正在运行,它就会一直存在.

This is as far as I've gotten on "my own" with a bunch of help from the SO community. I'm sort stuck checking if the forked child pseudo terminal is done executing what it's supposed to or not. Meaning i can tell if the SSH is done executing or not because it will live on for as long as the run() function is operating.

(我的 pid_exists 将返回 True 只要它在 run() 操作中.如果我退出 run() 到很快 SSH 会话将没有足够的时间来做它应该做的事情)

(my pid_exists will return True for as long as it's within the run() operation. And if i exit run() to quickly the SSH session will not have enough time to do what it's supposed to do)

#!/usr/bin/python

import pty, sys
from subprocess import Popen, PIPE, STDOUT
from time import sleep
from os.path import expanduser, abspath
from os import walk, setsid, fork, waitpid, execv, read, write, kill

def pid_exists(pid):
    """Check whether pid exists in the current process table."""
    if pid < 0:
        return False
    try:
        kill(pid, 0)
    except (OSError, e):
        return e.errno == errno.EPERMRM
    else:
        return True

class ssh():
    def __init__(self, host, execute='echo "done" > /root/testing.txt', user='root', password=b'SuperPassword'):
        self.exec = execute
        self.host = host
        self.user = user
        self.password = password
        self.run()

    def run(self):
        command = [
                '/usr/bin/ssh',
                self.user+'@'+self.host,
                '-o', 'NumberOfPasswordPrompts=1',
                self.exec,
        ]

        # PID = 0 for child, and the PID of the child for the parent    
        pid, child_fd = pty.fork()

        if not pid: # Child process
            # Replace child process with our SSH process
            execv(command[0], command)

        while True:
            output = read(child_fd, 1024).strip()
            print(output)
            lower = output.lower()
            # Write the password
            if b'password:' in lower:
                write(child_fd, self.password + b'\n')
                break
            elif 'are you sure you want to continue connecting' in lower:
                # Adding key to known_hosts
                write(child_fd, b'yes\n')
            elif 'company privacy warning' in lower:
                pass # This is an understood message
            else:
                print('Error:',output)

        sleep(5)
        print(pid_exists(pid))

ssh('10.10.10.1')

关于如何获取 Python 打开并通过管道传输给我的伪伪终端的执行过程,我找不到太多(或任何)信息.我可以或应该像这里解释的那样涉及子流程:https://stackoverflow.com/a/12235442/929999 或者是还有别的方法吗?

I can't find much (or any) information on how to get the execution process of the pseudo-pseudo terminal which Python opens and pipes to me. Can I or should I involve subprocess as explained here: https://stackoverflow.com/a/12235442/929999 or is there another way?

推荐答案

sigh.. 多一个 google 就可以免除所有人的麻烦.

sigh.. One more google could have spared everyone the trouble.

os.waitpid(pid, 0)

如何给予子处理密码并同时获取标准输出

这篇关于Python + SSH 密码身份验证(没有外部库或公钥/私钥)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆