python 利用pexpect进行多机
短信预约 -IT技能 免费直播动态提醒
在安装之前,确认你的机器安装了python,和easy_install.通常python是自动安装的,如果没有安装easy_install,那么wget -q http://peak.telecommunity.com/dist/ez_setup.py 获取一下
python ez_setup.py
pexpect是python一个模块,可以通过:easy_install pexpect 来安装。
这里主要是用pexpect执行ssh,查看远程uptime和df -h看硬盘状况。
这里主要是用pexpect执行ssh,查看远程uptime和df -h看硬盘状况。
#ssh_cmd.py
#coding:utf-8
import pexpect
def ssh_cmd(ip, user, passwd, cmd):
ssh = pexpect.spawn('ssh %s@%s "%s"' % (user, ip, cmd))
r = ''
try:
i = ssh.expect(['password: ', 'continue connecting (yes/no)?'])
if i == 0 :
ssh.sendline(passwd)
elif i == 1:
ssh.sendline('yes')
except pexpect.EOF:
ssh.close()
else:
r = ssh.read()
ssh.expect(pexpect.EOF)
ssh.close()
return r
hosts = '''
192.168.0.12:smallfish:1234:df -h,uptime
192.168.0.13:smallfish:1234:df -h,uptime
'''
for host in hosts.split("/n"):
if host:
ip, user, passwd, cmds = host.split(":")
for cmd in cmds.split(","):
print "-- %s run:%s --" % (ip, cmd)
print ssh_cmd(ip, user, passwd, cmd)
#coding:utf-8
import pexpect
def ssh_cmd(ip, user, passwd, cmd):
ssh = pexpect.spawn('ssh %s@%s "%s"' % (user, ip, cmd))
r = ''
try:
i = ssh.expect(['password: ', 'continue connecting (yes/no)?'])
if i == 0 :
ssh.sendline(passwd)
elif i == 1:
ssh.sendline('yes')
except pexpect.EOF:
ssh.close()
else:
r = ssh.read()
ssh.expect(pexpect.EOF)
ssh.close()
return r
hosts = '''
192.168.0.12:smallfish:1234:df -h,uptime
192.168.0.13:smallfish:1234:df -h,uptime
'''
for host in hosts.split("/n"):
if host:
ip, user, passwd, cmds = host.split(":")
for cmd in cmds.split(","):
print "-- %s run:%s --" % (ip, cmd)
print ssh_cmd(ip, user, passwd, cmd)
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341