栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python中SSH协议的实现

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python中SSH协议的实现

操作系统维护时, 一般会通过ssh命令连接到远端服务器, 进行某些操作. 那Python中如何完成这些呢, 当然也能执行ssh命令, 但还有更优雅的方式, 借助Paramiko, 其为实现了SSHv2协议的一开源项目, 下面主要使用了它的ssh和sftp客户端的相关功能.



安装

# pip install paramiko



SSH客户端使用

In [1]: import paramiko


#获取SSHClient对象.

In [2]: ssh = paramiko.SSHClient()


#设置host key策略.

#ssh.load_system_host_keys('/root/.ssh/known_hosts')

In [3]: ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())


#连接到SSH server, connect方法有若干参数, 可据需要设置, 如超时(timeout).

In [4]: ssh.connect('192.168.1.4')


#在SSH server上执行命令, 返回其I/O流, 类似于Python中的文件句柄, 标准输出(stdout)和标准错误(stderr)较常用.

In [5]: stdin, stdout, stderr = ssh.exec_command('ls -l /tmp/')


#获取标准输出

In [11]: for line in stdout:

    ...:     print '-> ' + line.strip('n')

    ...: 

-> total 16

-> -rw-r--r-- 1 root root 2 Jan 24 18:27 a.txt

-> -rw-r--r-- 1 root root 2 Jan 24 18:27 b.txt

-> -rw-r--r-- 1 root root 2 Jan 24 18:27 c.txt

-> -rw-r--r-- 1 root root 2 Jan 24 18:27 d.txt


SFTP客户端使用

#在连接到SSH server基础上, 获取SFTPClient对象.

sftp = ssh.open_sftp()


#上传文件

In [13]: sftp.put('/tmp/zz.txt', '/tmp/')

---------------------------------------------------------------------------

IOError                                   Traceback (most recent call last)

in ()

----> 1 sftp.put('/tmp/zz.txt', '/tmp/')


/usr/local/python27/lib/python2.7/site-packages/paramiko/sftp_client.pyc in put(self, localpath, remotepath, callback, /confirm/i)

...

IOError: Failure


In [14]:


为什么报错呢, 命令行上测试正常的...

# sftp 192.168.1.4

Connected to 192.168.1.4.

sftp> put '/tmp/zz.txt' '/tmp'

Uploading /tmp/zz.txt to /tmp/zz.txt

/tmp/zz.txt        100%    3     0.0KB/s   00:00

sftp>


查看sftp_client.py中put方法时, 发现remotepath参数, 需写明目标文件的名称.

:param str remotepath: the destination path on the SFTP server. Note

    that the filename should be included. only specifying a directory

    may result in an error.


这样就可以了.

In [21]: sftp.put('/tmp/zz.txt', '/tmp/zz.txt')

Out[21]:


#关闭连接

In [24]: sftp.close()


In [25]: ssh.close()


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/225410.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号