分享

利用pexpect模拟ssh连接

 BIGDATA云 2018-07-31

Pexpect 是 Don Libes 的 Expect 语言的一个 Python 实现,是一个用 来启动子程序,并使用正则表达式对程序输出做出特定响应,以此实现与其自 动交互的 Python 模块。 Pexpect 的使用范围很广,可以用来实现与 ssh、ftp 、telnet 等程序的自动交互;可以用来自动复制软件安装包并在不同机器自动 安装;还可以用来实现软件测试中与命令行交互的自动化

让我们实现自己的自动化蠕虫通过暴力破解目标的用户凭据。因为 SSH 客户端 需要用户的交互,我们的脚本必须等待和匹配期望的输入,在发送进一步的输 入命令之前。考虑一下以下的情景,为了连接我们的 IP 地址为 127.0.0.1 的 SSH 机器,首先应用程序要求我们确认 RSA 密钥,在这种情况下,我们必须 回答“yes”才能继续。接着应用程序要求我们输入密码。最后,我们执行我们 的命令“uname -a”来确定目标机器的运行版本。

我们将充分利用名为 Pexpect 的第三方 Python 模块(可以到 http://pexpect. 下载)。Pexpect 有和程 序交互的能力,并寻找预期的输出,然后基于预期做出响应,这使得它成为自 动暴力破解 SSH 用户凭证的一个极好的工具。

检查 connect()函数,这个函数接收用户名,主机名和密码,并返回一个 SSH 连接,从而得到大量的 SSH 连接。利用 Pexpect 模块,并等待一个预期 的输出。有三个预期的输出会出现---一个超时,一个信息提示这个主机有一个 新的公共密钥,或者是一个密码输入提示。如果结果是超时, session.expect()函数将会返回 0,接下来的选择语句警告这个并在返回之前打 印一个错误信息。如果 child.expect()函数捕捉到一个 ssh_newkey 信息,他 将返回 1.这将迫使函数发送一个消息“yes”来接受这个新 key。接下来,函数 在发送密码之前将等待密码提示。

# coding=utf-8

import pexpect

PROMPT = [pexpect.TIMEOUT, '#', '>>>', '>', '\$']

def send_command(child, cmd):
    child.sendline(cmd)
    child.expect(PROMPT)
    print(child.before)

def connect(user, host, password):
    ssh_newkey = 'Are you sure you want to continue connecting'
    connStr = 'ssh ' + user + '@' + host
    child = pexpect.spawn(connStr)
    print('[+] Attempt Once')
    ret = child.expect([pexpect.TIMEOUT, ssh_newkey, '[P|p]assword:'])
    if ret == 0:
        print('[-] Error Connecting')
        return
    if ret == 1:
        print('[+] Confirm Connecting')
        child.sendline('yes')
    if ret == 2:
        child.sendline(password)
        print('[+] Sending Password')
    ret = child.expect(PROMPT)
    if ret > 0:
        print('[+] Connect Successfully')
        return child


def main():
    host = '115.88.24.44'
    user = 'root'
    password = 'xxx'
    print('[+] Start to connect')
    child = connect(user, host, password)
    if child:
        print('[+] Connect Successfully')
        send_command(child, 'll')
    else:
        print('[-] Connect failed')


if __name__ == '__main__':
    main()

如上代码实现了模拟SSH连接的过程。

成功运行的结果:

[+] Start to connect
[+] Attempt Once
[+] Sending Password
[+] Connect Successfully
[+] Connect Successfully
 ll
total 28
drwx------  3 root root 4096 Mar  1  2016 ./
drwxr-xr-x 22 root root 4096 Nov 27  2015 ../
-rw-------  1 root root 2604 Sep 12 14:27 .bash_history
-rw-r--r--  1 root root 3106 Feb 20  2014 .bashrc
drwx------  2 root root 4096 Jan 30  2015 .cache/
-rw-r--r--  1 root root  140 Feb 20  2014 .profile
-rw-------  1 root root 1123 Mar  1  2016 .viminfo
root@iZ28c6kdbwlZ:~

运行失败的结果:

[+] Start to connect
[+] Attempt Once
[+] Sending Password
[-] Connect failed

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多