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

使用Python和Pexpect返回localhost哈希密码,python,ubuntu,ssh,pexpect,traceback,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 =

我正在学习如何用一本书来做五旬斋。其中一个练习使用此脚本:

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
然后,我继续使用
服务ssh start

接下来,我运行脚本。它不会像书上说的那样返回我的哈希根密码。相反,我得到一个OpenSSH弹出窗口,请求根密码,并得到以下输出:

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
回溯(最近一次呼叫最后一次):
文件“local.py”,第38行,在
main()
文件“local.py”,第34行,在main中
child=connect(用户、主机、密码)
文件“local.py”,第27行,在connect中
child.expect(提示)
expect中的文件“/usr/lib/python2.7/dist-packages/pexpect/_-init__;u.py”,第1418行
超时,搜索窗口大小)
expect\u列表中的第1433行文件“/usr/lib/python2.7/dist packages/pexpect/\uuuu init\uuuuuuu.py”
超时,搜索窗口大小)
expect\u循环中的第1535行文件“/usr/lib/python2.7/dist packages/pexpect/\uuuu init\uuuuuu.py”
提升超时(str(err)+'\n'+str(self))
pexpect.TIMEOUT:超过超时时间。
版本:3.2
命令:/usr/bin/ssh
参数:['/usr/bin/ssh','root@localhost']
搜索者:
缓冲区(最后100个字符):“\r\n权限被拒绝,请重试。\r\r”\nroot@localhost的密码:
之前(最后100个字符):“\r\n权限被拒绝,请重试。\r\r”\nroot@localhost的密码:
之后:
匹配:无
匹配索引:无
退出状态:无
flag_eof:False
pid:4562
儿童:3
关闭:错误
超时时间:30
分隔符:
日志文件:无
日志文件读取:无
日志文件发送:无
maxread:2000
忽略情况:错误
searchwindowsize:无
发送前延迟:0.05
延迟后关闭:0.1
延迟后终止:0.1

老实说,我还是python的新手,虽然我已经玩了好几个星期了。如果这是一个愚蠢的问题,我道歉。是的,我的密码是“g”

您在尝试以SSH方式将其作为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’ing到框中,查看1)是否允许根SSH,2)用户名/密码组合是否正确


将来,
paramiko
是一个用于Python的SSH库,它可以通过SFTP登录机器、运行命令和读/写文件。显然,这只是从书中学习,但是考虑用帕拉米科写真实的东西。

以下是帕拉米科的相同示例:

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'