python与pexpect实现ssh操作
2017-02-27 16:50
501 查看
下载并安装pexpect与ptyprocess模块并结合python2.7实现如下操作
tar -zxvf pexpect-4.0.1.tar.gz
cd pexpect-4.0.1
python setup.py install
tar -zxvf ptyprocess-0.5.tar.gz
cd /ptyprocess-0.5
python setup.py install
Py脚本
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pexpect
#from getpass import getpass
#passwd = getpass()
def ssh_cmd(user,ip, cmd,passwd):
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("/mess/filelist",'r')
a = file.read()
file.close()
for host in a.split("\n"):
if host:
user,ip,cmd,passwd = host.split("::")
print "-- %s run:%s --" % (ip, cmd)
ssh_cmd(user,ip,cmd,passwd)
-------------------------------------------------------------------------------------------
/mess/filelist
root::192.168.100.100::ls -l::password
root::192.168.100.100::ps -ef|grep ssh|awk '{print $8}'::password
tar -zxvf pexpect-4.0.1.tar.gz
cd pexpect-4.0.1
python setup.py install
tar -zxvf ptyprocess-0.5.tar.gz
cd /ptyprocess-0.5
python setup.py install
Py脚本
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pexpect
#from getpass import getpass
#passwd = getpass()
def ssh_cmd(user,ip, cmd,passwd):
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("/mess/filelist",'r')
a = file.read()
file.close()
for host in a.split("\n"):
if host:
user,ip,cmd,passwd = host.split("::")
print "-- %s run:%s --" % (ip, cmd)
ssh_cmd(user,ip,cmd,passwd)
-------------------------------------------------------------------------------------------
/mess/filelist
root::192.168.100.100::ls -l::password
root::192.168.100.100::ps -ef|grep ssh|awk '{print $8}'::password
相关文章推荐
- python与pexpect实现ssh操作
- python与pexpect实现ssh操作
- Python网络编程:使用pexpect实现快速ssh连接
- 利用Python实现对linux服务器SSH远程连接和系统操作的几种方式
- Python之Fabric模块 Fabric是基于Python实现的SSH命令行工具,简化了SSH的应用程序部署及系统管理任务,它提供了系统基础的操作组件,可以实现本地或远程shell命令,包括:
- python操作ssh实现服务器日志下载的方法
- 利用python 更新ssh 远程代码 操作远程服务器的实现代码
- python操作ssh实现服务器日志下载的方法
- windows环境,用python实现SSH操作
- python实现的列表操作
- ssh批量登录并执行命令的python实现代码
- Python 文件操作实现代码
- python 布尔操作实现代码
- python 使用ssh连接服务器进行远程命令行操作
- python 使用ssh连接服务器进行远程命令行操作
- Python 字符串操作实现代码(截取/替换/查找/分割)
- python,pexpect登录ssh并执行命令
- python 的时间操作datetime ,不支持减年或月阿!!自己实现
- 如何用Python高效实现下面这样的字符串拼接操作?
- ssh批量登录并执行命令的python实现代码