如何使用pexpect非交互式更改密码?

0 投票
2 回答
2127 浏览
提问于 2025-04-17 14:11

我正在学习Python,想要实现不需要用户交互就能更改用户密码,但似乎没有什么方法有效。
我觉得Python的pexpect模块很有潜力,所以我想试试这个。
这个教程看起来不错,但我试了之后发现它不管用。
网上有很多相关的代码,但似乎没有一个能成功。
我的代码也不行:

#!/usr/bin/python
import pexpect
import time
def ChangePassword(user, pass):
    passwd = pexpect.spawn("/usr/bin/passwd %s" % user)

    for x in xrange(2):
        # wait for password: to come out of passwd's stdout
        passwd.expect("password: ")
        # send pass to passwd's stdin
        passwd.sendline(pass)
        time.sleep(0.1)

ChangePassword('rajesh', 'bar') # changes user "foo"'s password to "bar"

错误信息:

bash-3.00# ./solpas7.py
  File "./solpas7.py", line 4
    def ChangePassword(user, pass):
                                ^
SyntaxError: invalid syntax

补充:我把密码中的“pass”改成了“pa”,但现在出现了很多问题,而且密码也没有改变。

bash-3.00# ./solpas7.py
Traceback (most recent call last):
  File "./solpas7.py", line 14, in ?
    ChangePassword('rajesh', 'bar') # changes user "foo"'s password to "bar"
  File "./solpas7.py", line 9, in ChangePassword
    passwd.expect("password: ")
  File "/usr/lib/python2.4/site-packages/pexpect.py", line 1311, in expect
    return self.expect_list(compiled_pattern_list, timeout, searchwindowsize)
  File "/usr/lib/python2.4/site-packages/pexpect.py", line 1325, in expect_list
    return self.expect_loop(searcher_re(pattern_list), timeout, searchwindowsize                                              )
  File "/usr/lib/python2.4/site-packages/pexpect.py", line 1409, in expect_loop
    raise TIMEOUT (str(e) + '\n' + str(self))
pexpect.TIMEOUT: Timeout exceeded in read_nonblocking().
<pexpect.spawn object at 0x80e306c>
version: 2.3 ($Revision: 399 $)
command: /usr/bin/passwd
args: ['/usr/bin/passwd', 'rajesh']
searcher: searcher_re:
    0: re.compile("password: ")
buffer (last 100 chars): New Password:
before (last 100 chars): New Password:
after: pexpect.TIMEOUT
match: None
match_index: None
exitstatus: None
flag_eof: False
pid: 4683
child_fd: 3
closed: False
timeout: 30
delimiter: 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

2 个回答

0

你还可以用这个方法让你的搜索不区分大小写:

passwd.expect('(?i)password:')    
3

你不能把 pass 当作变量名来用,因为它是一个保留字。

补充说明:pexpect 正在等待字符串 "password: ",但是从错误信息来看,passwd 输出的是 "New Password: "(注意大写的 P)在你的系统上。

buffer (last 100 chars): New Password:
before (last 100 chars): New Password:

所以你应该用 passwd.expect("Password: "),而不是 passwd.expect("password: ")

撰写回答