CentOS7.3上安装paramiko以及简单实现远程SSH运行命令实例
paramiko的安装
para支持pip、easy_install或源码安装方式,很方便解决包依赖的问题,具体安装命令如下(根据用户环境、自行选择pip或easy_install):
pip install paramiko easy_install paramiko
paramiko依赖第三方的Cryoto、Ecdsa包及Python开发包python-devel的支持,源码安装步骤如下:
# yum -y install python-devel # wget http://ftp.dlitz.net/pub/dlitz/crypto/pycrypto/pycrypto-2.6.tar.gz # tar -zxvf pycrypto-2.6.tar.gz # cd pycrypto-2.6 # python setup.py install # cd .. # wget https://pypi.python.org/packages/source/e/ecdsa/ecdsa-0.10.tar.gz --no-check-certificate # tar -zxvf ecdsa-0.10.tar.gz # cd ecdsa-0.10 # python setup.py install # cd .. # wget https://github.com/paramiko/paramiko/archive/v1.12.2.tar.gz # tar -zxvf paramiko-v1.12.2 # cd paramiko-1.12.2/ # python setup.py install
校验安装结果,导入模块没有提示异常则说明安装成功:
# python # Python 2.7.5 (default, Nov 6 2016, 00:28:07) # [GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux2 # Type "help", "copyright", "credits" or "license" for more information. # >>> import paramiko # >>>
示例,通过 exec_command()方法执行命令
#!/usr/bin/python # -*- coding: utf-8 -*- #/home/test/paramiko/simplel.py #conding:utf-8 import paramiko
hostname = '192.168.2.233' username = 'root' password = '6UYeIdSamEC0KKm' paramiko.util.log_to_file('syslogin.log') #发送 paramiko 日志到syslogin.log文件 ssh=paramiko.SSHClient() #创建一个ssh客户端client对象 ssh.load_system_host_keys() #获取客户端host_keys,默认~/.ssh/known_hosts,非默认路径需指定 ssh.connect(hostname=hostname, username=username, password=password) #创建ssh连接 stdin,stdout,stderr=ssh.exsc_command('free -m') #调用远程执行命令方法exec_command() print stdout.read() #打印命令执行结果,得到Python列表形式,可以使用stdout.readlines() ssh.close() #关闭ssh连接
以下是程序运行结果截图