使用 Python 和 Pexpect 到 return localhost 散列密码

Using Python and Pexpect to return localhost hashed password

我正在学习如何通过一本书进行渗透测试。其中一项练习使用此脚本:

import pexpect

PROMPT = ['# ', '>>> ', '> ', '$ ']

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)
    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 main():
    host = 'localhost'
    user = 'root'       import pexpect

PROMPT = ['# ', '>>> ', '> ', '$ ']

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)
    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 main():
    host = 'localhost'
    user = 'root'
    password = 'g'
    child = connect(user, host, password)
    send_command(child, 'cat /etc/shadow | grep root')

if __name__ == '__main__':
    main()
    password = 'g'
    child = connect(user, host, password)
    send_command(child, 'cat /etc/shadow | grep root')

if __name__ == '__main__':
    main()

我查看了 Ubuntu 文档以了解如何为服务器创建密钥,因此我在终端中使用了这些命令:

mkdir ~/.ssh
chmod 700 ~/.ssh
ssh-keygen -t rsa

然后我开始使用 service ssh start

启动 ssh 服务器

接下来,我运行脚本。 return 我的散列根密码并不像书中所说的那样。相反,我收到一个 OpenSSH 弹出窗口,要求输入 root 密码,以及以下输出:

Traceback (most recent call last):
  File "local.py", line 38, in <module>
    main()
  File "local.py", line 34, in main
    child = connect(user, host, password)
  File "local.py", line 27, in connect
    child.expect(PROMPT)
  File "/usr/lib/python2.7/dist-packages/pexpect/__init__.py", line 1418, in expect
    timeout, searchwindowsize)
  File "/usr/lib/python2.7/dist-packages/pexpect/__init__.py", line 1433, in expect_list
    timeout, searchwindowsize)
  File "/usr/lib/python2.7/dist-packages/pexpect/__init__.py", line 1535, in expect_loop
    raise TIMEOUT(str(err) + '\n' + str(self))
pexpect.TIMEOUT: Timeout exceeded.
<pexpect.spawn object at 0x7f2ca63ca7d0>
version: 3.2
command: /usr/bin/ssh
args: ['/usr/bin/ssh', 'root@localhost']
searcher: <pexpect.searcher_re object at 0x7f2ca63ca850>
buffer (last 100 chars): "\r\nPermission denied, please try again.\r\r\nroot@localhost's password: "
before (last 100 chars): "\r\nPermission denied, please try again.\r\r\nroot@localhost's password: "
after: <class 'pexpect.TIMEOUT'>
match: None
match_index: None
exitstatus: None
flag_eof: False
pid: 4562
child_fd: 3
closed: False
timeout: 30
delimiter: <class 'pexpect.EOF'>
logfile: None
logfile_read: None
logfile_send: None
maxread: 2000
ignorecase: False
searchwindowsize: None
delaybeforesend: 0.05
delayafterclose: 0.1
delayafterterminate: 0.1

老实说,我仍然是 python 的新手,尽管我已经玩了几个星期了。如果这是一个愚蠢的问题,我深表歉意。是的,我的密码只是 "g"。

尝试以 root@localhost 身份通过 SSH 连接到计算机时出现错误。在命令的输出中发现了您的错误

buffer (last 100 chars): "\r\nPermission denied, please try again.\r\r\nroot@localhost's password: "
before (last 100 chars): "\r\nPermission denied, please try again.\r\r\nroot@localhost's password: "

这是您尝试使用错误的 username/password 组合登录计算机时会遇到的典型错误。

从终端尝试直接通过 SSH 连接到该框以查看 1) 是否允许 root ssh,以及 2) username/password 组合是否确实正确。


将来,paramiko 是 Python 的 SSH 库,可以通过 SFTP 登录机器、运行 命令和 read/write 文件。显然,这只是从书本上学习,但考虑用 paramiko 编写真正的东西。

下面是相同示例在 paramiko 中的样子:

import paramiko

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
    client.connect('localhost', username='root', password='g')
    stdin, stdout, stderr = client.exec_command('/bin/cat /etc/shadow')
    # Now, you can read from stdout (if the command succeeded), or stderr (if it failed)
    shadow_file_contents = stdout.readlines()
    if shadow_file_contents:
        print '/etc/shadow: {0}'.format(''.join(line for line in shadow_file_contents if 'root' in line))
    else:  # No contents in the file. Show the user why...
        print 'errors: {0}'.format(''.join(stderr.readlines()))
except (paramiko.BadAuthenticationType) as why:  # Invalid un/pw
    print 'Unable to login using given username/password to this host'