为了账号安全,请及时绑定邮箱和手机立即绑定

Python中SSH协议的实现 - Paramiko

标签:
Python

操作系统维护时, 一般会通过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)

<ipython-input-13-0e19a403e0d2> in <module>()

----> 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)

...

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]: <SFTPAttributes: [ size=3 uid=901 gid=901 mode=0100664 atime=1516792881 mtime=1516792881 ]>


#关闭连接

In [24]: sftp.close()


In [25]: ssh.close()


点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

举报

0/150
提交
取消