Python 官方文档:入门教程 => 点击学习
python 远程批量修改密码脚本 #tar -zxvf pexpect-3.0.tar.gz #cd pexpect-3.0 #Python setup.py install #!/usr/bin/env python #coding:u
python 远程批量修改密码脚本
#tar -zxvf pexpect-3.0.tar.gz
#cd pexpect-3.0
#Python setup.py install
#!/usr/bin/env python
#coding:utf8
import pexpect
import sys
iplist = ['192.168.140.142','192.168.140.145'] ##定义主机列表
oldpasswd = '234567' ##旧密码
newpasswd = '1234567' ##新密码
while iplist:
ip = iplist[-1] ##获取一个IP
iplist.pop() ##列表去掉一个值
child = pexpect.spawn('ssh root@'+ip) ##定义触发
fout = file('passlog.txt','a') ##定义日志文件,
child.logfile = fout
try:
while True:
index = child.expect(['(yes/no)','(?i)passWord:'])
if index == 0:
child.sendline('yes')
elif index == 1:
child.sendline(oldpasswd)
child.expect('#')
child.sendline('echo '+newpasswd+' | passwd --stdin root')
child.expect('#')
child.sendline('exit')
except pexpect.TIMEOUT:
print >>sys.stderr, ip+' timeout'
except pexpect.EOF:
print >>sys.stderr, ip+' <the end>'
(1)spawn类
class pexpect.spawn(command,args=[],timeout=30,maxread=2000,searchwidowsize=None
,logfile=None,cwd=None,env=None,ignore_sighup=True)
(2)run函数
pexpect.run(command,timeout=-1,withexitstatus=False,events=None,extra_args=None,
logfile=None,cwd=None,env=None).
(3)pxssh类
class pexpect.pxssh.pxssh(timeout=30,maxread=2000,searchwidowsize=None,logfile=None,
cwd=None,env=None)
pxssh常用的三个方法:
login()建立连接;
loGout()断开连接;
prompt()等待系统提示符,用于等待命令执行结束
#!/usr/bin/python# encoding=utf-8# Filename: pexpect_test.pyimport pexpectdef sshCmd(ip, passwd, cmd):
ret = -1
ssh = pexpect.spawn('ssh root@%s "%s"' % (ip, cmd)) try:
i = ssh.expect(['password:', 'continue connecting(yes/no)?'], timeout=5) if i == 0:
ssh.sendline(passwd) elif i == 1:
ssh.sendline('yes\n')
ssh.expect('password:')
ssh.sendline(passwd)
ssh.sendline(cmd)
r = ssh.read() print r
ret = 0
except pexpect.EOF: print "EOF"
ret = -1
except pexpect.TIMEOUT: print "TIMEOUT"
ret = -2
finally:
ssh.close() return ret
sshCmd('xxx.xxx.xxx.xxx','xxxxxx','ls /root')
--结束END--
本文标题: python pexpect
本文链接: https://lsjlt.com/news/185988.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0