Python 官方文档:入门教程 => 点击学习
1、 安装python的Pexpect模块 wget Http://jaist.dl.sourceforge.net/project/pexpect/pexpect/Release%202.3/pexpect-2.3.tar.gz tar
1、 安装python的Pexpect模块
wget Http://jaist.dl.sourceforge.net/project/pexpect/pexpect/Release%202.3/pexpect-2.3.tar.gz
tar xzf pexpect-2.3.tar.gz
cd pexpect-2.3
Python setup.py install
2、 执行脚本
可以登录到机器执行一些简单的命令等。。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pexpect
from getpass import getpass
passwd = getpass()
def ssh_cmd(user,ip, cmd):
ssh = pexpect.spawn('ssh %s@%s "%s"' % (user,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')
ssh.expect('password: ')
ssh.sendline(passwd)
except pexpect.EOF:
print "EOF"
except pexpect.TIMEOUT:
print "TIMEOUT"
else:
r = ssh.read()
print r
ssh.close()
if __name__ == '__main__':
file=open("/root/python/filelist",'r')
a = file.read()
file.close()
for host in a.split("\n"):
if host:
user,ip,cmd = host.split("::")
print "-- %s run:%s --" % (ip, cmd)
ssh_cmd(user,ip,cmd)
more /root/python/filelist
root::1.1.1.1::ls&&date
root::2.2.2.2::ls&&date
................
--结束END--
本文标题: python,pexpect登录ssh并
本文链接: https://www.lsjlt.com/news/187480.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
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