首页
学习
活动
专区
工具
TVP
发布

Python中SSH协议的实现-Paramiko

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

...

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

  • 发表于:
  • 原文链接http://kuaibao.qq.com/s/20180124G0WD9K00?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券