1. 简介
Samba是Ubuntu和Windows进行网络共享的工具,比如分享打印机,互相之间传输资料文件。
ExpectExpect含有利用正则表达式进行模式匹配以及通用的编程功能,允许简单的脚本智能地管理如下工具:telnet,ftp和ssh(这些工具都缺少编程的功能),宏以及其它程序。Expect脚本的出现使得这些老的软件工具有了新的功能和更多的灵活性。
pexpect是expect的Python版本。
目标:提供web页面给Samba用户实现修改密码功能。
技术:python + Flask + pexpect
2. 开发环境搭建:
3. 代码实现:
目录结构:
1
2
3
4smbchpasswd/
├── server.py
└── templates
└── index.htmlserver.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'byte'
from flask import Flask, request, render_template
import pexpect
app = Flask(__name__)
# mapping path
def index():
return render_template('index.html')
def chpass():
# params
username = request.form['username']
password = request.form['password']
new1 = request.form['new1']
new2 = request.form['new2']
# validate params
if username == '' or password == '' or new1 == '' or new2 == '':
return render_template('index.html', message='Not finished.', username=username)
if new1 != new2:
return render_template('index.html', message='Two times the password is not consistent.', username=username)
# send commands
cmds = 'smbpasswd -U ' + username
child = pexpect.spawn(cmds)
child.sendline(password)
child.sendline(new1)
child.sendline(new2)
# expect result info
result_ok = 'Password changed for user ' + username
result_fail = 'Could not connect to machine 127.0.0.1: NT_STATUS_LOGON_FAILURE'
result_restriction = 'machine 127.0.0.1 rejected the password change: Error was : Password restriction.'
result_fail_two = 'Unable to connect to SMB server on machine 127.0.0.1. Error was : NT_STATUS_CONNECTION_REFUSED.'
result = child.expect([result_ok, result_fail, result_restriction, result_fail_two])
# return result an info
if result == 0 :
return render_template('index.html', result_ok='ok', username=username)
elif result == 1 :
return render_template('index.html', message='The original password is incorrect. Please try again.', username=username)
elif result == 2 :
return render_template('index.html', message='The new password is too simple.Please try again.', username=username)
elif result == 3 :
return render_template('index.html', message='The original password is incorrect. Please try again.', username=username)
# run
if __name__ == '__main__':
#host is the ip of server
app.run(host='127.0.0.1', port=8000)index.html
undefined运行server.py
python server.py
;
4. 可能出现的问题:
Internal Server Error
,原因:
1. server.py中含有中文字符(待解决);
2. 服务器未安装Samba服务;