使用Python和Pexpect返回localhost哈希密码

时间:2015-01-06 20:38:17

标签: python ubuntu ssh pexpect traceback

我正在学习如何用书进行测试。其中一个练习使用此脚本:

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服务器

接下来,我运行脚本。它不会像书中所说的那样返回我的哈希根密码。相反,我得到一个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”。

1 个答案:

答案 0 :(得分:0)

尝试以root @ localhost身份登录到计算机时出错。您的错误可在命令的输出中找到

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: "

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

从终端尝试SSH直接进入框中以查看是否允许1)root ssh,以及2)用户名/密码组合是否实际上是正确的。


将来,paramiko是一个用于Python的SSH库,可以通过SFTP登录计算机,运行命令和读/写文件。显然,这只是从一本书中学习,但考虑用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'