以下代码在python 2.6.6下测试通过
添加帐号并修改密码:
(注:linux的expect命令也可以完成,交互式自动输入的功能)
#!/usr/bin/env python account = ‘sl_t1‘ passwd=‘a1p2p3l4e5‘ cmd_useradd = ‘useradd %s‘ % (account) #添加用户命令,根据需要自行修改 import subprocess as sp def useradd(): cmd = ‘export LC_ALL=en_US && %s‘ % (cmd_useradd) f=open(‘/dev/null‘, ‘w‘) ret = sp.call(cmd, shell=True, stdout=f, stderr=f) f.close() return ret def passwd(): cmd = ‘export LC_ALL=en_US && passwd %s‘ % (account) f=open(‘/dev/null‘, ‘w‘) p = sp.Popen(cmd, shell=True, stdin=sp.PIPE, stdout=f, stderr=f) p.stdin.write("%s\n" % (passwd)) p.stdin.write("%s\n" % (passwd)) f.close() return p.wait() def pymain(): #print ‘useradd: ‘, useradd() #print ‘passwd: ‘, passwd() ret = useradd() if not 0==ret: print ‘useradd ‘,ret return ret = passwd() if not 0==ret: print ‘passwd ‘,ret return print ‘done‘ #如果工作正常返回done,否则返回失败的步骤及错误码 if __name__==‘__main__‘: pymain()
时间: 2024-10-13 07:42:06